Introduction
Artificial Intelligence (AI) agents are programs that can perform tasks autonomously, make decisions, and interact with their environment. Thanks to modern AI frameworks, building your first AI agent is easier than ever—no advanced degree required!
In this tutorial, we’ll use OpenAI’s API to create a simple AI agent that can answer questions, generate text, and even assist with basic tasks. Let’s get started!
Prerequisites
Before we begin, make sure you have:
- A free OpenAI account (for API access)
- Python installed (version 3.6 or higher)
- Basic knowledge of Python (helpful but not mandatory)
Step 1: Set Up Your Environment
First, install the OpenAI Python library:
bash
pip install openai
Next, get your OpenAI API key:
- Go to OpenAI’s API Key page.
- Click “Create new secret key” and copy it.
Step 2: Create Your AI Agent
Now, let’s write a simple script to interact with OpenAI’s GPT model.
python code:
import openai # Replace with your API key openai.api_key = "your-api-key-here" def ask_ai(prompt): response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}] ) return response.choices[0].message.content # Test the AI agent user_input = input("Ask me anything: ") answer = ask_ai(user_input) print("AI says:", answer)
Explanation:
openai.ChatCompletion.create()
sends a prompt to OpenAI’s model.model="gpt-3.5-turbo"
specifies the AI model (fast and cost-effective).- The AI responds with generated text based on your input.
Step 3: Run Your AI Agent
Save the script as ai_agent.py
and run it:
bash
Copy
python ai_agent.py
When prompted, ask a question like:
- “What’s the weather like today?”
- “Write a short poem about AI.”
The AI will generate a response instantly!
Step 4: Enhance Your Agent (Optional)
Want to make it smarter? Try adding:
- Memory: Store past interactions for context.
- Custom Instructions: Guide the AI’s behavior (e.g., “You are a helpful assistant”).
- Multi-Turn Conversations: Allow follow-up questions.
Example upgrade:
python code:
messages = [{"role": "system", "content": "You are a helpful assistant."}] while True: user_input = input("You: ") if user_input.lower() in ["exit", "quit"]: break messages.append({"role": "user", "content": user_input}) response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=messages ) ai_reply = response.choices[0].message.content messages.append({"role": "assistant", "content": ai_reply}) print("AI:", ai_reply)
Now your AI remembers the conversation!
Conclusion
Congratulations! 🎉 You’ve built your first AI agent in minutes. With just a few lines of code, you can create chatbots, writing assistants, and more.
Next Steps
- Explore OpenAI’s documentation for advanced features.
- Integrate your AI into a web app (e.g., using Flask or FastAPI).
- Experiment with different models like GPT-4 for better responses.
Happy coding! 🚀
Leave a Reply