Master the OpenAI API and Build Your First Intelligent Chatbot
How to Use the OpenAI API
The OpenAI API allows access to models like GPT-4, GPT-3.5, and DALL-E. Here’s how to get started:
Step 1: Get an API Key
Visit platform.openai.com and create an account.
In the "API Keys" menu, click "Create new secret key."
Copy the generated key and store it securely.
Step 2: Install the OpenAI Library
Run the following command in the terminal (with the virtual environment active):
pip install openai
Step 3: First API Call
Create a file chatbot.py
and add:
import openai
openai.api_key = "your-api-key"
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Who invented the light bulb?"}]
)
print(response.choices[0].message.content)
Expected Output:
"Thomas Edison is credited as the inventor of the practical incandescent light bulb in 1879."
Creating an Interactive Chatbot with GPT
Let’s transform the above code into an interactive chatbot.
Step 1: Chatbot in a Loop
Update chatbot.py
:
import openai
openai.api_key = "your-api-key"
history = []
while True:
question = input("\nYou: ")
if question.lower() == "exit":
break
history.append({"role": "user", "content": question})
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=history,
temperature=0.7
)
ai_response = response.choices[0].message.content
print(f"\nAI: {ai_response}")
history.append({"role": "assistant", "content": ai_response})
How It Works:
-
history
stores the conversation context. -
temperature=0.7
controls creativity (0 = conservative, 1 = random).
Example Usage:
You: How do I bake a chocolate cake?
AI: To bake a chocolate cake, you’ll need...
Customizing Responses
Adjust chatbot behavior using system prompts and advanced parameters.
Example 1: Sarcastic Assistant
Add a system prompt to the history:
history = [
{"role": "system", "content": "You are a sarcastic assistant who responds with irony."}
]
Output:
You: What is the meaning of life?
AI: Oh sure, because I definitely have the answer to humanity’s biggest question...
Example 2: Controlling Style and Format
Request responses in specific topics or styles:
question = "Explain relativity theory in 3 points, like a pirate."
Output:
1. Arr! General relativity says gravity ain't no force, but space-time curving...
Advanced Parameters:
-
max_tokens=150
: Limits response size. -
top_p=0.9
: Controls word choice diversity.
Practical Project: Study Assistant
Create an AI Agent that simplifies complex concepts:
history = [
{"role": "system", "content": "You are a science tutor for 10-year-olds. Use simple analogies."}
]
question = "What is a black hole?"
Output:
"Imagine a giant vacuum cleaner in space that even light can't escape! It’s like an invisible monster swallowing everything."
Common Errors and Fixes
Authentication Error:
Error:
openai.AuthenticationError: Invalid API key
Solution: Ensure the API key is correct and active.
Token Limit Exceeded:
Error:
openai.BadRequestError: maximum context length is 4097 tokens
Solution: Reduce history size or use max_tokens
.
Rate Limit Exceeded:
Error:
openai.RateLimitError
Solution: Wait 20 seconds between requests or upgrade to a paid plan.
Next Steps
In the next chapter, you’ll learn to add memory to your AI Agent using databases. Meanwhile:
✅ Try creating a themed bot (e.g., poet, financial advisor). ✅ Explore OpenAI documentation for more parameters.
Pro Tips:
-
Use
pip install python-dotenv
to store your API key in a.env
file and keep it secure. -
System prompts define your AI Agent’s personality.
-
The
temperature
parameter adjusts creativity. -
Always manage conversation history to maintain context.
Ready to upgrade your chatbot? In the next chapter, we’ll transform it into an agent with memory!
Copyright Statement: Unless stated otherwise, all articles are original to this site, please credit the source when sharing.
Article link:http://pybeginners.com/artificial-intelligence/creating-a-simple-ai-agent-with-openai-api/
License Agreement:Attribution-NonCommercial 4.0 International License