Article
tool-useai-agentsfunction-callingpythonllmcapability-extensionautomation
Build a Simple AI Agent with Tool Use
Equip an AI with custom functions, or 'tools,' it can call to answer questions. This guide demonstrates implementing basic Tool Use in Python, allowing your agent to access external data or perform specific actions beyond its base knowledge.
intermediate30 min4 steps
The play
- Define Your ToolsCreate standard Python functions that will serve as your agent's tools. Each function should perform a single, specific task, like fetching data or performing a calculation. This isolates capabilities, making them easier for the agent to select and use.
- Describe Tools for the AgentCreate a manifest describing each tool. This metadata is crucial for the AI's `tool-selection` capability, as it explains what each tool does and what arguments it expects. Modern LLMs use a structured format like JSON Schema for this.
- Implement Tool Selection LogicCreate the agent's core logic to analyze a user query and decide which tool to use. In a real application, an LLM would make this choice based on the tool descriptions. Here, we simulate `tool-selection` with keyword matching to demonstrate the mechanism.
- Execute Tool and Interpret OutputOnce a tool is selected, the agent executes it with the required arguments (`input-marshalling`). It then takes the tool's output and uses it to formulate a final, human-readable answer, demonstrating `output-interpretation`.
Starter code
import json
# 1. Define the Tools
def get_current_weather(location: str) -> str:
"""Gets the current weather for a given location."""
print(f" [Tool Call: get_current_weather(location='{location}')]")
# In a real app, this would call a weather API
if "tokyo" in location.lower():
return json.dumps({"location": "Tokyo", "temperature": "15", "unit": "celsius"})
elif "london" in location.lower():
return json.dumps({"location": "London", "temperature": "5", "unit": "celsius"})
else:
return json.dumps({"location": location, "temperature": "unknown"})
def calculator(expression: str) -> str:
"""Evaluates a simple mathematical expression."""
print(f" [Tool Call: calculator(expression='{expression}')]")
try:
# WARNING: eval() is unsafe with untrusted input. Used here for simplicity.
result = eval(expression, {"__builtins__": {}}, {})
return json.dumps({"expression": expression, "result": result})
except Exception as e:
return json.dumps({"error": str(e)})
# A dictionary to map tool names to their functions for easy calling
available_tools = {
"get_current_weather": get_current_weather,
"calculator": calculator
}
# 2. Describe Tools (used conceptually by the simulated agent below)
tool_descriptions = [
{
"name": "get_current_weather",
"description": "Get the current weather in a given location",
},
{
"name": "calculator",
"description": "Evaluate a simple mathematical expression",
}
]
# 3. & 4. Simulate the full agent loop: select, marshall, execute, interpret
def run_agent(query: str):
"""A simplified agent that demonstrates the Tool Use skill.
This function simulates an LLM's thought process:
1. Receives a query.
2. Selects a tool based on keywords (simulating `tool-selection`).
3. Extracts arguments (simulating `input-marshalling`).
4. Calls the tool function.
5. Formats the tool's output into a response (simulating `output-interpretation`).
"""
print(f"\n--- Processing Query: '{query}' ---")
# Simulate tool selection
selected_tool_name = None
args = {}
if "weather" in query.lower():
selected_tool_name = "get_current_weather"
# Simulate argument extraction
if "london" in query.lower():
args = {"location": "London"}
else:
args = {"location": "Tokyo"} # default for example
elif any(op in query for op in ['+', '-', '*', '/', 'calculate']):
selected_tool_name = "calculator"
# Simulate argument extraction
args = {"expression": "(100 / 4) * 2"}
# Execute the selected tool or provide a fallback response
if selected_tool_name and selected_tool_name in available_tools:
print(f"Agent decided to use the '{selected_tool_name}' tool.")
tool_function = available_tools[selected_tool_name]
# Execute the tool with extracted arguments
tool_output_str = tool_function(**args)
tool_output = json.loads(tool_output_str)
# Interpret the output and generate a final response
if "error" in tool_output:
final_response = f"Sorry, the tool failed with an error: {tool_output['error']}"
elif selected_tool_name == "get_current_weather":
final_response = f"The current weather in {tool_output['location']} is {tool_output['temperature']}°C."
elif selected_tool_name == "calculator":
final_response = f"The result is {tool_output['result']}."
else:
final_response = "I've used a tool but I'm not sure how to interpret the result."
else:
final_response = "I'm sorry, I don't have a tool that can help with that."
print(f"Agent Response: {final_response}")
if __name__ == "__main__":
run_agent("What's the weather like in Tokyo?")
run_agent("Can you calculate (100 / 4) * 2 for me?")
run_agent("What is the capital of France?")