AI Agents with Tool Use
Build autonomous AI agents that can use external tools and APIs to accomplish complex tasks.
Note: This guide follows English-language naming conventions and terminology standards common in international development teams. Examples use English identifiers and comments to maximize compatibility across codebases and tooling.
Overview
AI agents are autonomous systems that use large language models to reason, plan, and execute tasks by calling external tools. Unlike simple chatbots, agents can search the web, query databases, run code, and interact with APIs to accomplish complex, multi-step objectives.
When to Use
Use this resource when:
- Building autonomous assistants that need real-time data
- Creating workflows that require multiple API calls chained together
- Implementing reasoning over external knowledge sources
- Designing self-correcting systems that can retry failed operations
Solution
ReAct Pattern Agent (Python)
import openai
import json
from typing import Callable
def agent_react(query: str, tools: dict[str, Callable]) -> str:
messages = [
{"role": "system", "content": "You are a helpful assistant. Use tools when needed."},
{"role": "user", "content": query}
]
for _ in range(5): # Max iterations
response = openai.chat.completions.create(
model="gpt-4",
messages=messages,
tools=[
{"type": "function", "function": {"name": n, "parameters": {}}}
for n in tools.keys()
]
)
msg = response.choices[0].message
if not msg.tool_calls:
return msg.content
messages.append(msg)
for call in msg.tool_calls:
result = tools[call.function.name](**json.loads(call.function.arguments))
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": str(result)
})
return "Max iterations reached"
Tool Definition Example
def search_wikipedia(query: str) -> str:
"""Search Wikipedia for a topic."""
# Implementation omitted
return f"Results for {query}"
tools = {"search_wikipedia": search_wikipedia}
result = agent_react("Who won the 2022 FIFA World Cup?", tools)
Explanation
The ReAct (Reasoning + Acting) pattern alternates between:
- Thought: The LLM reasons about what to do next
- Action: The LLM calls a tool with structured arguments
- Observation: The tool result is fed back as context
- Repeat: Until the task is complete
Key design decisions:
- Tool schemas: Use OpenAI’s function calling format for type safety
- Iteration limits: Prevent infinite loops with a max step count
- Error handling: Tools should return errors gracefully, not crash
- Context window: Summarize long tool outputs to fit token limits
Variants
| Framework | Pattern | Best For |
|---|---|---|
| LangChain | ReAct, Plan-and-Execute | Rapid prototyping |
| AutoGen | Multi-agent conversation | Collaborative tasks |
| CrewAI | Role-based agents | Business workflows |
| Custom | ReAct with tool registry | Production systems |
Best Practices
- Define clear tool interfaces: Each tool needs a name, description, and JSON schema
- Limit tool count: 3-5 well-designed tools outperform 20 vague ones
- Add validation: Verify tool arguments before execution
- Log all steps: Agent reasoning is opaque; logging aids debugging
- Implement timeouts: External tools can hang; set generous timeouts
Common Mistakes
- Giving agents too many tools: Increases confusion and error rates
- Missing error handling: A failed tool call without recovery crashes the loop
- Ignoring token limits: Long observation histories exhaust the context window
- Not validating outputs: Agents can hallucinate tool arguments
- Skipping human review: Autonomous agents should have kill switches
Frequently Asked Questions
Q: What is the difference between RAG and an agent? A: RAG retrieves documents and answers once. Agents can take multiple actions, use tools, and iterate until a goal is met.
Q: How many tools should an agent have? A: Start with 2-3. Research shows accuracy drops significantly beyond 5-7 tools.
Q: Can agents run without OpenAI? A: Yes. Local models (Llama, Mistral) support tool calling via structured output formats like JSON mode.
Related Resources
Build Autonomous AI Agents with Tool Use and Reasoning
How to design AI agents that autonomously plan, execute tools, and iterate toward goals using ReAct, function calling, and memory architectures.
RecipeImplement Semantic Search with Embeddings
How to implement semantic search using text embeddings and vector similarity search for intelligent document retrieval
RecipeBuild a Slack Bot with OpenAI GPT-4
How to build a conversational Slack bot powered by OpenAI GPT-4 that responds to mentions and direct messages
RecipeCreate a Chatbot with OpenAI Assistants API
How to create an AI chatbot using the OpenAI Assistants API with function calling and file retrieval
RecipeGenerate Images Programmatically with AI Models
How to create, edit, and optimize images using DALL-E, Stable Diffusion, and Midjourney APIs with prompt engineering, batch processing, and content moderation.