Build your first agent with a single tool — the add function.
1# calculator_agent.py
2import json
3from openai import OpenAI
4client = OpenAI()
5
6# --- Step 1: Define our Python function (THE TOOL) ---
7def add(a, b):
8 """Add two numbers together"""
9 print(f"\n[Debug: Running REAL Python code: add(a={a}, b={b})]")
10 return a + b
11
12# --- Step 2: Define the "tools" list (THE MENU) ---
13tools = [
14 {
15 "type": "function",
16 "function": {
17 "name": "add",
18 "description": "Add two numbers together",
19 "parameters": {
20 "type": "object",
21 "properties": {
22 "a": {"type": "number", "description": "The first number"},
23 "b": {"type": "number", "description": "The second number"},
24 },
25 "required": ["a", "b"]
26 }
27 }
28 }
29]
30
31# --- Step 3: Start the conversation ---
32messages = [{"role": "user", "content": "What is 45 + 13?"}]
33print(f"User: {messages[0]['content']}")
34
35# --- Step 4: First call to the model (User -> AI) ---
36print("--- 1. Sending to AI (with tools)... ---")
37response = client.chat.completions.create(
38 model="gpt-4o-mini",
39 messages=messages,
40 tools=tools,
41 tool_choice="auto"
42)
43
44message = response.choices[0].message
45messages.append(message)
46
47# --- Step 5: Handle the function call ---
48if message.tool_calls:
49 print(f"--- 2. AI decided to call: {message.tool_calls[0].function.name} ---")
50
51 tool_call = message.tool_calls[0]
52 function_name = tool_call.function.name
53 arguments = json.loads(tool_call.function.arguments)
54
55 result = add(a=arguments.get("a"), b=arguments.get("b"))
56 print(f"--- 3. Ran function, result: {result} ---")
57
58 # --- Step 6: Second call to the model ---
59 messages.append({
60 "role": "tool",
61 "tool_call_id": tool_call.id,
62 "content": str(result)
63 })
64
65 print("--- 4. Sending result back to AI... ---")
66 final_response = client.chat.completions.create(
67 model="gpt-4o-mini",
68 messages=messages
69 )
70
71 print("\n--- 5. Final Answer from AI: ---")
72 print(final_response.choices[0].message.content)
73else:
74 print("\n--- Final Answer from AI (no tool needed): ---")
75 print(message.content)No output yet...