1. Setting Up Your Environment
We'll use Python with the OpenAI API and a search tool. First, install the required packages and set up your API keys. You'll need an OpenAI API key and optionally a Tavily or SerpAPI key for web search.
pip install openai tavily-python
export OPENAI_API_KEY='your-key-here'
export TAVILY_API_KEY='your-key-here'2. Defining the Agent's Tools
Tools give your agent capabilities. We'll define a web search tool that the agent can call when it needs to find information online.
from tavily import TavilyClient
def search_web(query: str) -> str:
"""Search the web for information."""
client = TavilyClient()
results = client.search(query, max_results=5)
return "\n".join([r["content"] for r in results["results"]])3. Building the Agent Loop
The agent loop is where the magic happens. The agent receives a query, decides if it needs to use tools, executes them, and formulates a response.
from openai import OpenAI
client = OpenAI()
def run_agent(query: str) -> str:
messages = [
{"role": "system", "content": "You are a helpful research assistant."},
{"role": "user", "content": query}
]
response = client.chat.completions.create(
model="gpt-4",
messages=messages,
tools=[{"type": "function", "function": {...}}]
)
# Handle tool calls and return final response
return response.choices[0].message.contentWrap-up
Congratulations! You've built your first AI agent. From here, you can add more tools, improve the prompts, and expand its capabilities.