Skip to content
Goal: Deep understanding✓ Sources verified 2026-11-24Function CallingAgent Loop

Tool Calling: Letting the Model Call Your Functions ​

The shared foundation of agent orchestration, computer use and MCP. Both pipeline "orchestration" and "agent orchestration" are built on this layer.

Core concepts ​

  • Tool definition: a name + a description + a JSON Schema for the parameters. The model only "decides which tool to call and with what arguments"; your code does the actual execution.
  • Message loop: the model returns a tool call request → you execute it → you send the result back as a new message → the model continues, until it stops requesting tools.
  • Parallel tool calls: one reply can contain several tool calls; you can run them concurrently and return all results at once.
  • tool_choice: controls whether the model decides on its own, must call a specific tool, or must not call any tool.
  • strict mode: set strict: true on a tool definition so arguments strictly match the schema (supported by both Anthropic and OpenAI).

How it works: one full message loop (Anthropic Messages API shape) ​

user: "Check the status of order 123"
assistant: [tool_use id=tu_1 name=get_order input={"order_id":"123"}]    ← stop_reason = "tool_use"
user:      [tool_result tool_use_id=tu_1 content="Shipped"]              ← you execute and send back
assistant: "Order 123 has shipped."                                       ← stop_reason = "end_turn"
  • Every tool_result must be matched to its request by tool_use_id, or the API returns an error.
  • When a tool fails, don't throw an exception that breaks the loop. Send back is_error: true with the error message and let the model decide whether to retry or try something else.
  • The OpenAI Responses API uses function_call / function_call_output items matched by call_id; the principle is the same.

In practice: a minimal tool loop without a framework ​

python
import asyncio, json

MAX_STEPS = 8
TOOLS = {"get_order": get_order, "search_docs": search_docs}   # your async functions

async def run_tool(block):
    fn = TOOLS.get(block.name)
    if fn is None:
        return {"type": "tool_result", "tool_use_id": block.id, "is_error": True, "content": f"Unknown tool {block.name}"}
    try:
        result = await asyncio.wait_for(fn(**block.input), timeout=20)
        return {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(result, ensure_ascii=False)}
    except Exception as e:  # send the error back to the model instead of breaking the loop
        return {"type": "tool_result", "tool_use_id": block.id, "is_error": True, "content": str(e)}

async def agent(messages, tool_specs):
    for step in range(MAX_STEPS):
        resp = await client.messages.create(model=MODEL, max_tokens=2048, tools=tool_specs, messages=messages)
        messages.append({"role": "assistant", "content": resp.content})
        if resp.stop_reason != "tool_use":
            return resp
        calls = [b for b in resp.content if b.type == "tool_use"]
        results = await asyncio.gather(*(run_tool(c) for c in calls))   # run in parallel
        messages.append({"role": "user", "content": list(results)})
    raise NeedHumanReview(f"Exceeded max steps {MAX_STEPS}")

Key points: a max step count, a timeout per tool, errors sent back to the model, parallel execution, and a trace log entry for every step.

Common pitfalls ​

  1. Tool descriptions that are too terse: the model decides when to call a tool from its description. Spell out when to use it, when not to, and give argument format examples.
  2. Too many tools: dozens of tools lower selection accuracy and eat context. Group them by task, load them on demand, or narrow the set with a router first.
  3. Exposing dangerous operations directly as tools: delete, pay and send-message tools should go through human confirmation (see "human takeover").
  4. No max step count: the model gets stuck in a loop and cost runs away.
  5. Tool results that are too long: returning a whole HTML page blows up the context. Truncate or summarize first.

Common interview questions ​

  1. Draw the full tool calling message loop. What values can stop_reason take?
  2. How do you execute parallel tool calls and return their results?
  3. How do you handle a tool failure? Why not just throw an exception?
  4. How do you stop an agent from looping forever and running up costs?
  5. How does tool calling relate to MCP? (MCP is a protocol for "exposing tools in a standard way"; the model still uses them through tool calling)

How it relates to my projects ​

Sources ​

Vin Amory · AI development × content creation · Technical notes cite official docs in each page’s sources section