Lesson 15 of 23 · Part 2: Agents

Multi-Function Agent: Math Tutor

An agent with 4 tools and a loop that cycles multiple times.

Last time: The AI asked for add with tool_calls, our code ran it, and we sent back a "tool" message.
Today: Four tools and a while True loop let the AI use tools again and again until done.
Source Code
1# math_tutor.py
2import json
3from openai import OpenAI
4client = OpenAI()
5
6# --- Step 1: Define ALL our Python functions (THE TOOLS) ---
7def add(a, b):
8    print(f"\n[Debug: add(a={a}, b={b})]")
9    return a + b
10
11def subtract(a, b):
12    print(f"\n[Debug: subtract(a={a}, b={b})]")
13    return a - b
14
15def multiply(a, b):
16    print(f"\n[Debug: multiply(a={a}, b={b})]")
17    return a * b
18
19def divide(a, b):
20    print(f"\n[Debug: divide(a={a}, b={b})]")
21    if b == 0: return "Error: Cannot divide by zero."
22    return a / b
23
24# --- Step 2: Define the "tools" list (THE MENU) ---
25tools = [
26    {"type": "function", "function": {"name": "add", ...}},
27    {"type": "function", "function": {"name": "subtract", ...}},
28    {"type": "function", "function": {"name": "multiply", ...}},
29    {"type": "function", "function": {"name": "divide", ...}},
30]
31
32# --- Step 3: Start the conversation ---
33messages = [
34    {"role": "system", "content": "You are a friendly math tutor. Use tools to solve problems."},
35    {"role": "user", "content": "What is (50 * 2) - 15?"}
36]
37print(f"User: {messages[-1]['content']}")
38
39# --- Step 4: The Agent Loop ---
40while True:
41    print("\n--- 1. Sending to AI (with tools)... ---")
42    response = client.chat.completions.create(
43        model="gpt-4o-mini", messages=messages,
44        tools=tools, tool_choice="auto"
45    )
46    message = response.choices[0].message
47    messages.append(message)
48
49    if not message.tool_calls:
50        print("\n--- Final Answer from AI: ---")
51        print(message.content)
52        break
53
54    print(f"--- 2. AI calls {len(message.tool_calls)} function(s) ---")
55    for tool_call in message.tool_calls:
56        function_name = tool_call.function.name
57        arguments = json.loads(tool_call.function.arguments)
58        available_functions = {"add": add, "subtract": subtract,
59                               "multiply": multiply, "divide": divide}
60        result = available_functions[function_name](**arguments)
61        print(f"--- 3. {function_name}({arguments}) = {result} ---")
62        messages.append({
63            "role": "tool", "tool_call_id": tool_call.id,
64            "content": str(result)
65        })

No output yet...

← Prev
1/0
Next: Study Buddy →