I will give a quick dive into ChatGPT API in this post. I am assuming you have the knowledge of the basics of Python and have the IDE’s setup.
The installation of Python is in this link. For any latest chatGPT changes please refer to their webpage. Lets dive into chatgpt integration in python.
Table of Contents
1. Create an API key in the account-> API Keys->Create a new Secret Key.
Copy the key and store it for your reference. You cannot view it again after you confirm.
2. Add the following variable and paste the key in the value. Keep the name OPENAI_API_KEY
3. Invoke ChatGPT client in Python code
Invoke the client with OpenAI() call. The client is used to create a chat that will ask a question and return a message as a response. Querying the response JSON object one can find the answer to the question requested.
def print_hi(name):
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "What is the name of the person who set foot on the moon for the first time"}
]
)
print(completion.choices[0].message)
# Use a breakpoint in the code line below to debug your script.
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
The output for print_hi is as follows
ChatCompletionMessage(content='The name of the person who set foot on the moon for the first time was Neil Armstrong.', role='assistant', function_call=None, tool_calls=None)
4. The program prompts the user to ask the question
getcontentfromuser() function expects the user to present with a question. Remember that ChatGPT pricing is based on the number of tokens in the response. You can review more on their pricing page.
def getcontentfromuser():
content = input("User: ")
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": content}
]
)
chatgptresponse = completion.choices[0].message.content
print(chatgptresponse)
4. Creating a simple chatbot
The code below can be used for creating the most simple chatbot that stores the history and responds based on the previous context. Please review the function chatbotchatgptsimplesample().
Sample output for better understanding.
5. Create a sample finance bot
I created a sample finance bot here. It is a very basic version. You can train the model and also add text to respond better. You can indicate Chatgpt about some keywords that it should be aware of. By adding more enhancements one can build custom bots that work better for your requirements.
A sample output.
In the upcoming tutorials, I can demonstrate more about custom-built chatbots.
Please leave a comment or subscribe for more updates about AI.