Solution explainer · Share after the exercise

Module 3 — Tool Calling Basics: Solution Explainer

Step-by-step solutions, the message flow behind tool calling, and answers to the discussion questions.

For learners, after the exerciseExercises 3.1 – 3.3
On this page
  1. How tool calling really works (the message list)
  2. 3.1 From scratch
  3. 3.2 With LangChain
  4. 3.3 Choosing between four tools
  5. Answers to "Think about it"
  6. Common errors

How tool calling really works

Analogy: a restaurant waiter (the LLM) and the kitchen (your code). The waiter cannot cook. He reads the menu (your tool list), writes an order slip with a table number (tool_call_id), and when the dish comes back he serves it with a smile (the final answer).

Everything happens through one growing list of messages. For "What is the square root of 144?" it grows like this:

What the messages list looks like (ids are examples)
# after step 1 (the LLM asked for a tool)
[{"role": "user", "content": "What is the square root of 144?"},
 {"role": "assistant", "content": None,
  "tool_calls": [{"id": "call_abc123", "type": "function",
                  "function": {"name": "square_root", "arguments": "{\"number\": 144}"}}]}]

# after step 3 (our code ran the tool and appended the result)
 ...,
 {"role": "tool", "tool_call_id": "call_abc123", "content": "12.0"}]

# step 4: we send the whole list again; the LLM now replies with normal text
"The square root of 144 is 12."

Note that arguments is a JSON string, not a dict. That is why we need json.loads.

3.1 Tool calling from scratch

TODO 1 — Describe the square_root tool in OpenAI's JSON tool format

Solution for TODO 1
tools = [
    {
        "type": "function",
        "function": {
            "name": "square_root",
            "description": "Calculate the square root of a non-negative number.",
            "parameters": {
                "type": "object",
                "properties": {
                    "number": {
                        "type": "number",
                        "description": "The non-negative number to take the square root of.",
                    }
                },
                "required": ["number"],
            },
        },
    }
]

This is a JSON Schema: it says the tool takes one argument named number, of type number, and it is required. The description fields are the most important part. The LLM reads them to decide when to use the tool.

TODO 2 — Run the requested tool and add its result to messages

Solution for TODO 2
fn_name = tool_call.function.name
fn_args = json.loads(tool_call.function.arguments)  # e.g. {"number": 144}
result = tool_map[fn_name](**fn_args)
print(f"   [tool] {fn_name}({fn_args}) -> {result}")
messages.append({
    "role": "tool",
    "tool_call_id": tool_call.id,  # tells the LLM which request this result belongs to
    "content": str(result),
})

Three moves: read the name, turn the JSON string into a dict, call the real function with **fn_args (which means square_root(number=144)). Then append a message with role: "tool" and the same tool_call_id, so the LLM knows which request this answers. The API rejects a tool result without a matching id.

TODO 3 — Call the LLM a second time with the updated messages and return its text

Solution for TODO 3
final_response = client.chat.completions.create(
    model=MODEL,
    messages=messages,
    tools=tools,
    reasoning_effort="none",
)
return final_response.choices[0].message.content

The second call sends the full history (question, tool request, tool result). Now the LLM has the number it needs and writes a sentence.

Example output (the [tool] lines are exact; the AI's wording will vary)
Q: What is the square root of 144?
   [tool] square_root({'number': 144}) -> 12.0
A: The square root of 144 is 12.

Q: What is the capital of France?
A: The capital of France is Paris.

Q: Can you calculate the square root of 2025 for me?
   [tool] square_root({'number': 2025}) -> 45.0
A: The square root of 2025 is 45.
Why reasoning_effort="none"?

We use OpenAI's gpt-6-luna, a fast, low-cost model. In the Chat Completions API, OpenAI only allows tool calling with this model when reasoning_effort="none" (no long internal "thinking" before answering). It also makes the replies faster.

3.2 With LangChain

TODO 1 — Turn square_root into a LangChain tool

Solution for TODO 1
@tool
def square_root(number: float) -> float:
    """Calculate the square root of a non-negative number."""
    if number < 0:
        raise ValueError("Cannot compute square root of a negative number.")
    return math.sqrt(number)

@tool reads three things from your function and builds the JSON menu for you: the name (square_root), the docstring (description) and the type hints (number: float).

Output (real run)
Tool name       : square_root
Tool description: Calculate the square root of a non-negative number.
Tool arguments  : {'number': {'title': 'Number', 'type': 'number'}}

TODO 2 — Run every requested tool and add a ToolMessage with its result

Solution for TODO 2
for tc in response.tool_calls:  # Step 3: run the tools
    result = tool_map[tc["name"]].invoke(tc["args"])
    print(f"   [tool] {tc['name']}({tc['args']}) -> {result}")
    messages.append(ToolMessage(content=str(result), tool_call_id=tc["id"]))

LangChain already parsed the arguments into a dict (tc["args"]), so there is no json.loads. tool.invoke(args) runs the function. ToolMessage is LangChain's version of the role: "tool" message.

Example output (the [tool] line is exact; the wording will vary)
Q: Is 15241383937 the square of 123456?
   [tool] square_root({'number': 15241383937}) -> 123456.00000405003
A: No. The square root of 15241383937 is about 123456.000004, not exactly 123456.
   123456 squared is 15241383936, so the number you gave is one more than that.
JobFrom scratch (3.1)LangChain (3.2)
Describe the toolWrite JSON by hand@tool + docstring
Attach tools to the calltools=tools on every callllm.bind_tools(tools) once
Read argumentsjson.loads(tool_call.function.arguments)tc["args"]
Send result back{"role": "tool", ...}ToolMessage(...)
Switch to another LLM providerRewrite the codeChange one line (the chat model class)
Why .text instead of .content?

With tools bound, LangChain sends this model's requests to OpenAI's newer Responses API. There, response.content is a list of blocks (text, ids, annotations). response.text always gives you just the plain answer.

3.3 Choosing between four tools

TODO 1 — Write a 4th tool that lists every SKU at or below its reorder point

Solution for TODO 1
@tool
def list_low_stock_items() -> str:
    """List all SKUs that are at or below their reorder point and need restocking."""
    low = [
        f"{sku} ({item['name']}): stock={item['stock']}, reorder_point={item['reorder_point']}"
        for sku, item in INVENTORY.items()
        if item["stock"] <= item["reorder_point"]
    ]
    if not low:
        return "All items are adequately stocked."
    return f"Items needing reorder ({len(low)} total): " + "; ".join(low)

The docstring is the "menu description". "List all SKUs that are at or below their reorder point" matches questions like "which items need reordering?" very well, so the LLM picks this tool for them.

TODO 2 — Put all four tools in a list, build tool_map, and bind the tools to the LLM

Solution for TODO 2
tools = [get_stock_level, calculate_reorder_quantity, days_until_stockout, list_low_stock_items]
tool_map = {t.name: t for t in tools}

llm = ChatOpenAI(model="gpt-6-luna", reasoning_effort="none")
llm_with_tools = llm.bind_tools(tools)

One bind_tools call with all four tools. The LLM now sees four menu items and must choose.

Output: the [tool] lines (exact). After each one, the script prints the LLM's sentence built from that result.
Q: What is the current stock level for SKU-003?
   [tool] get_stock_level({'sku': 'SKU-003'}) -> Conveyor Belt (SKU-003): stock=5, reorder_point=10, status=LOW

Q: Which items need to be reordered right now?
   [tool] list_low_stock_items({}) -> Items needing reorder (2 total): SKU-002 (Hydraulic Pump): stock=18, reorder_point=25; SKU-003 (Conveyor Belt): stock=5, reorder_point=10

Q: How many days until SKU-002 runs out of stock?
   [tool] days_until_stockout({'sku': 'SKU-002'}) -> Hydraulic Pump (SKU-002): 6.0 days until stockout (stock=18, daily_demand=3)

Q: What quantity of SKU-003 should I order if my supplier takes 10 days to deliver?
   [tool] calculate_reorder_quantity({'sku': 'SKU-003', 'lead_time_days': 10}) -> Conveyor Belt (SKU-003): recommend ordering 35 units (lead_time_demand=20, safety_buffer=20, lead_time=10d, estimated_cost=Rs 612,500)

How the reorder number is built: 2 belts/day × 10 days = 20 needed while waiting for delivery, + 20 as a safety buffer = 40 target, − 5 in stock = 35 to order. This is a simple rule of thumb. Module 4 uses the proper safety-stock formula.

Answers to "Think about it"

1. How did "my supplier takes 10 days" become lead_time_days=10?

The tool menu says calculate_reorder_quantity takes lead_time_days: int and its description mentions "supplier lead time in days". The LLM matches the phrase to the parameter and fills it in. Clear parameter names and descriptions make this reliable.

2. Two tools with the same description?

The LLM cannot tell them apart, so it picks one more or less at random, or calls both. Every tool needs a description that says exactly when to use it.

3. Why send tool_call_id?

The LLM can ask for several tools at once. The id links each result to the request it answers, like a table number on a restaurant order slip. The API rejects results without a matching id.

4. A question needing two tools in a row?

Example: "Look up SKU-005, then calculate its reorder point" (the second tool needs the first tool's output). Our code calls tools once and then forces a final answer, so the second step never happens. The fix is a loop: keep calling the LLM until it stops asking for tools. You build exactly that in Module 4, Step 06.

5. Is it safe to expose any function?

No. Read-only tools (look up stock) are low risk. Tools that change the world (place a purchase order, send money, delete records, send emails) should need a human "approve" step, and should check their inputs, because the LLM can misunderstand or be tricked by text it reads.

Common errors and fixes

You seeFix
BadRequestError ... tools ... [] or too shortTODO 1 is still the empty placeholder tools = [].
... must be a response to a preceding message with 'tool_calls'You appended the tool result but forgot to append the assistant's message (messages.append(message)) before it, or the tool_call_id does not match.
TypeError: square_root() got an unexpected keyword argumentThe parameter name in your JSON (number) must match the Python function's argument name exactly.
KeyError: 'list_low_stock_items'The tool is not in your tools list, so it is missing from tool_map.
The answer prints as a list like [{'type': 'text', ...}]Use response.text instead of response.content.