Building a Chatbot with OpenAI's Chat Models 🤖
The /v1/chat/completions
endpoint is designed for conversational AI, using message history to generate context-aware responses. Instead of a single prompt, you send an array of messages with roles (system
, user
, assistant
). Here's a Python example:
import requests
api_key = 'your-api-key'
headers = {
'Authorization': f'Bearer {api_key}',
'Content-Type': 'application/json'
}
messages = [
{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': 'What is the weather today?'}
]
data = {
'model': 'gpt-4',
'messages': messages,
'max_tokens': 150,
'temperature': 0.5
}
response = requests.post('https://api.openai.com/v1/chat/completions', headers=headers, json=data)
print(response.json()['choices'][0]['message']['content'])
This setup allows dynamic conversations, retaining context over multiple exchanges, essential for building sophisticated chatbots.