Open Menu dzosoft
Close Menu dzosoft




Publish perfectly-optimized content in 1-click


How to Create Your Own Personal Assistant using ChatGPT and Python

How to Create Your Own Personal Assistant using ChatGPT and Python
In this tutorial we will see how to use Python to connect to the OpenAI API and use the same model that animates ChatGPT, called gpt-3.5-turbo , thus integrating it within our applications to exploit its full potential.
In order to integrate ChatGPT and other OpenAI models within a Python project via API we must first generate an access key (secret key) within the OpenAI platform portal , by selecting the API Keys menu item.
Once we have obtained the access key we can start writing the code.

What will you need?

In order to best apply what is shown in this tutorial, you should know at least the basics of Python.
First, let's create a new virtual environment using venv and install the openai package using pip
pip install openai

In our project folder we create a new script and a .json file called secretkey. We will use the json file to save our access key
    "api_key": "your-secret-key"


How to integrate ChatGPT into Python

We create a python file and import the json and openai modules. Make sure you don't name the file you will write code to "" as this will cause conflicts with the newly imported library of the same name! We'll just call our file

We import our secret key to authenticate by reading it from the json file using the appropriate form.
with open("secretkey.json") as f:
    secretkey = json.load(f)
    api_key = secretkey["api_key"]

In order to authenticate and therefore be able to communicate with the OpenAI backend, we assign our key to openai.api_key
openai.api_key = api_key

To be able to talk to the AI model we can now use openai.ChatCompletion.create() .
We define a response variable to which to pass the response obtained from the OpenAI backend. Let's move on to create 3 parameters: model, messages and temperature
response = openai.ChatCompletion.create(
    model = "gpt-3.5-turbo",
    messages = [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Which country is the 2010 World Cup?"},
        {"role": "assistant", "content": "2010 FIFA World Cup South Africa."},
		{"role": "user", "content": "Who won the world cup in 2010"}
    temperature = 1.0


The model, messages and temperature parameters

OpenAI has various Artificial Intelligence models that can be used through APIs. For this reason, we pass the codename of the model we intend to use to the first model
parameter , i.e. the actual "system" with which we are interacting textually. We will give a definition of a language model later in the lesson. With temperatures we can control the “confidence level” of the model when making these predictions. A low temperature value results in more deterministic and accurate predictions, while increasing temperature will result in more diverse responses. The default value for the temperature is 1.0 and accepts values in the range 0.0 - 2.0. Finally, messages
is a list of dictionaries, where each one has a role ("system", "user" or "assistant") and a content. Role system messages help set the assistant's behavior by setting the initial context, user messages issue instructions to the assistant and can be generated by users, while assistant messages represent previous responses sent by ChatGPT.
For a complete list of parameters you can take a look at the dedicated documentation page on the official website.

How to use this code on multiple modules?

The purpose of this article is to allow you to integrate this language model into your projects, and to do this, the code must be usable across multiple modules. We can then use a function, to import when needed.
The function will accept as a parameter a list called messages, which we can then pass to thecreate() function. The messages: list notation uses the Python type hint nomenclaturei.e. the type check passed to the variable is not validated in runtime but can be from development tools such as IDEs, linters, type checkers etc.
Notice the return value from get_response(): response.choices[0].message . Of all the output returned by the OpenAI backend, we are only interested in the returned message, so that it can be added to the messages list and sent together with all the other messages previously exchanged in subsequent requests.
def get_response(messages:list):
    response = openai.ChatCompletion.create(
        model = "gpt-3.5-turbo",
        temperature = 1.0 # 0.0 - 2.0
    return response.choices[0].message


Our personal assistant

To create the model in personal assistant mode it is now sufficient to create an infinite while loop in which to request input from the user, make requests to the backend for an answer and show everything in output.
We use if __name__ == "__main__" , to have this code executed whenever the file where we are executing this code (in our case is executed as a script, for example by launching it from a system terminal.
We also define messages and define in it a first message with role: system
import json
import openai

with open("secrets.json") as f: secrets = json.load(f) api_key = secrets["api_key"]
openai.api_key = api_key
def get_response(messages:list): response = openai.ChatCompletion.create( model = "gpt-3.5-turbo", messages=messages, temperature = 1.0 # 0.0 - 2.0 ) return response.choices[0].message
if __name__ == "__main__": messages = [ {"role": "system", "content": "You are a virtual assistant called DZO and you speak English."} ] try: while True: user_input = input("\nYou: ") messages.append({"role": "user", "content": user_input}) new_message = get_response(messages=messages) print(f"\nDZO: {new_message['content']}") messages.append(new_message) except KeyboardInterrupt: print("See you soon!")

And this is the video to see the running example

It might also interest you

How to install Python on Windows

How to write your first Python program

How to lock PC with voice command using Python

How to connect MySQL database using Connector/Python

How to draw shapes with python

How to create read and write to a file in python

How to create and initialize a Python dictionary

Leave comment

Save nickname and email in this browser for the next time.

close publicity