Knowledgebase Article: https://www.libraryofcelsus.com/research/basic-open-ai-api-calls/
Chat-GPT
This guide walks you through making calls using the Open Ai Api.
1. Pre-requisites and Initial Setup
Before interacting with the OpenAI API, you must prepare your environment.
- Libraries: Import the required Python libraries.
import os
import json
import openai
import time
from time import time, sleep
- API Key Configuration: Load your OpenAI API key from a file.
with open('key_openai.txt', 'r', encoding='utf-8') as file:
openai.api_key = file.read().strip()
2. OpenAI API Request Configuration
- Define a function to communicate with the OpenAI API. This function will send a user’s query and receive a response.
def chatgpt_completion(query):
max_counter = 7
counter = 0
while True:
try:
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
max_tokens=800,
temperature=0.5,
messages=query
)
response = (completion.choices[0].message.content)
return response
except Exception as e:
counter +=1
if counter >= max_counter:
print(f"Exiting with error: {e}")
exit()
print(f"Retrying with error: {e} in 20 seconds...")
sleep(20)
3. Initializing the Main Loop
- Set up the main loop for chatbot interaction. This also involves initializing an empty list to store conversation details.
if __name__ == '__main__':
conversation = []
4. Define Chatbot & User Details
- Define user and chatbot names, and create uppercase versions for display purposes.
bot_name = open_file('./Prompts/bot_name.txt')
user_name = open_file('./Prompts/user_name.txt')
usernameupper = user_name.upper()
botnameupper = bot_name.upper()
5. Interaction and Conversation Flow
Guide the user through the chat experience:
- User Input Capture: Prompt the user and get their input.
while True:
try:
user_input = input(f'\n\n{usernameupper}: ')
- System Prompt: Introduce the assistant’s role.
conversation.append({'role': 'system', 'content': f"You are {bot_name}, a helpful Ai assistant. Give an answer to the user's inquiry in a natural, but verbose manner."})
- Chatbot Greeting: Start the interaction with a friendly message.
conversation.append({'role': 'assistant', 'content': f"Hello! I'm {bot_name}, your loyal personal assistant! How can I help you today?"})
- User Message: Add the user’s input to the conversation.
conversation.append({'role': 'user', 'content': user_input})
6. Response Generation
Utilize the configured function to generate a response using the OpenAI API.
conv_completion = chatgpt_completion(conversation)
print(f"{botnameupper}: conv_completion)
7. Clearing for Next Interaction
Reset the conversation list to prepare for the next user interaction. If any errors occur, they will be caught and displayed.
conversation.clear()
except Exception as e:
print(e)