Prerequisites
Before starting, ensure you have:
- Python 3.9+
openailibrary (orlangchain-openai)- A valid OpenAI API Key
pip install openai
Step 1: Define Tools
Agents interact with the external world through tools. Let's define two simple tools: a calculator and a current time query.
from datetime import datetime
def get_current_time() -> str:
"""Get current date and time. Use when user asks about the time or today's date."""
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def calculator(expression: str) -> str:
"""Evaluate a math expression. Input a string like '2+3*4', returns the result."""
try:
result = eval(expression)
return str(result)
except Exception as e:
return f"Calculation error: {e}"
Step 2: Tool Schema and Call Logic
To help the LLM understand when to call tools, define a schema in OpenAI Function Calling format:
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get current system date and time",
"parameters": {"type": "object", "properties": {}}
}
},
{
"type": "function",
"function": {
"name": "calculator",
"description": "Evaluate a math expression, e.g. 2+3*4",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Math expression"}
},
"required": ["expression"]
}
}
}
]
def run_tool(name: str, args: dict) -> str:
if name == "get_current_time":
return get_current_time()
if name == "calculator":
return calculator(args.get("expression", ""))
return "Unknown tool"
Step 3: Agent Main Loop
The core Agent loop: call LLM → if tool calls returned, execute them → pass results back to LLM → repeat until final response.
import json
from openai import OpenAI
client = OpenAI()
messages = [
{"role": "system", "content": "You are an assistant that can query time and do math. Call the appropriate tools based on user needs."},
{"role": "user", "content": "What time is it? Also help me calculate (10+20)*3"}
]
while True:
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto"
)
msg = response.choices[0].message
if msg.tool_calls:
for tc in msg.tool_calls:
result = run_tool(tc.function.name, json.loads(tc.function.arguments))
messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})
messages.append({"role": "assistant", "content": None, "tool_calls": msg.tool_calls})
else:
print(msg.content)
break
Step 4: Run and Test
Run the script and input "What time is it? Also help me calculate (10+20)*3." The Agent will call get_current_time and calculator in sequence, then summarize the results.
Summary
By defining tools, writing the schema, and implementing the main loop, you've built a minimal Agent. From here, you can add more tools, introduce Memory, or switch to frameworks like LangChain to simplify development.