tutorials· 2 min read
Getting Started: Your First AI Agent in 30 Minutes
Step-by-step tutorial to build a functional AI agent from scratch using Python and an LLM API. No prior agent experience required.
Prerequisites
- Python 3.10+
- An OpenAI or Anthropic API key
- Basic Python knowledge
What We're Building
A simple research agent that can search the web, summarize findings, and answer follow-up questions. By the end, you'll understand the core agent loop: perceive, reason, act.
Step 1: Set Up the Environment
pip install openai duckduckgo-search
Step 2: Define Tools
Tools are functions the agent can call. Let's start with web search:
from duckduckgo_search import DDGS
def web_search(query: str) -> str:
"""Search the web and return top results."""
results = DDGS().text(query, max_results=3)
return "\n".join(
f"- {r['title']}: {r['body']}" for r in results
)
Step 3: The Agent Loop
The core of any agent is a loop: get input, decide what to do, execute, repeat.
import openai
tools = [
{
"type": "function",
"function": {
"name": "web_search",
"description": "Search the web for information",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"}
},
"required": ["query"]
}
}
}
]
def run_agent(user_message: str):
messages = [
{"role": "system", "content": "You are a research assistant."},
{"role": "user", "content": user_message}
]
while True:
response = openai.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools
)
choice = response.choices[0]
if choice.finish_reason == "stop":
return choice.message.content
# Execute tool calls
for tool_call in choice.message.tool_calls:
result = web_search(tool_call.function.arguments)
messages.append(choice.message)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
Step 4: Run It
answer = run_agent("What are the latest developments in AI agents?")
print(answer)
What Just Happened?
- The agent received a question
- It decided to search the web (tool use)
- It received search results
- It synthesized an answer from the results
This is the fundamental agent pattern. Everything else — memory, planning, multi-agent collaboration — builds on this core loop.
Next Steps
- Add memory (conversation history)
- Add more tools (file reading, code execution)
- Add planning (break complex tasks into steps)
Related Posts
0 Comments
Loading comments...