Here is an example of how to use the chat completion API using python. Same process can be used for programming in other languages.
Step 1: Set Up Your OpenAI Account
- Sign Up for an OpenAI Account:
- Visit the OpenAI website and create an account.
- Generate API Key:
- Once registered, obtain your API key from the OpenAI platform.
Step 2: Install OpenAI Python Package
- Install the OpenAI Python Package:
pip install openai
Step 3: Define a Chat Conversation
- Structure the Conversation:
- Define a conversation as a list of messages, each with a role (“system”, “user”, or “assistant”) and content.
conversation = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Tell me a joke."},
]
Step 4: Make an API Call
- Use the OpenAI API:
- Make an API call to the
openai.ChatCompletion.create
method.
- Make an API call to the
import openai
# Set your API key
openai.api_key = 'your-api-key'
# Make an API call for chat completion
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # Specify the model
messages=conversation
)
Step 5: Extract and Print the Response
- Extract Assistant’s Reply:
- Extract the model’s response from the API response.
# Extract and print the assistant's reply
assistant_reply = response['choices'][0]['message']['content']
print("Assistant:", assistant_reply)
Step 6: Adjust Parameters
- Experiment with Parameters: Explore different parameters like
temperature
andmax_tokens
to control the output.
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=conversation,
temperature=0.8,
max_tokens=100
)
Step 7: Iterate and Test
- Refine Conversations:
- Adjust the conversation based on the model’s responses to improve interactions.
- Experiment with Prompts:
- Test different prompts to see how the model responds.
Example Python Script
import openai
# Set your API key
openai.api_key = 'your-api-key'
# Define a chat-based conversation
conversation = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Tell me a joke."},
]
# Make an API call for chat completion
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # Specify the model
messages=conversation
)
# Extract and print the assistant's reply
assistant_reply = response['choices'][0]['message']['content']
print("Assistant:", assistant_reply)
Important Notes:
- Read Documentation:
- Always refer to the official OpenAI API documentation for the latest information.
- API Usage Limits:
- Be aware of API usage limits to avoid interruptions in service.
- Stay Informed:
- Follow OpenAI’s communication channels for announcements and updates.