Function calling: giving the model tools

The tool-call loop, parallel calls, error handling and the safety rules that apply the moment a model can act.

Intermediate about 4 h

The picture

  1. 01

    Describe tools

    name, schema

  2. 02

    Model decides

    tool_use block

  3. 03

    You execute

    validated, sandboxed

  4. 04

    Return result

    tool_result

  5. 05

    Model answers

    or calls again

The key insight

The model never runs anything. It asks for a function to be called, by emitting a structured request. Your code decides whether and how to run it, and sends the result back. That is the whole mechanism behind every agent.

A complete loop

import json, anthropic
client = anthropic.Anthropic()

def get_weather(city: str) -> dict:
    return {"city": city, "temp_c": 31, "conditions": "humid"}       # stand-in for a real API

REGISTRY = {"get_weather": get_weather}
TOOLS = [{
    "name": "get_weather",
    "description": "Current weather for a city. Use for any question about present conditions.",
    "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
}]

def run(question: str, max_turns: int = 6) -> str:
    messages = [{"role": "user", "content": question}]
    for _ in range(max_turns):
        resp = client.messages.create(model="claude-sonnet-5-5", max_tokens=1024, tools=TOOLS, messages=messages)
        if resp.stop_reason != "tool_use":
            return "".join(b.text for b in resp.content if b.type == "text")
        messages.append({"role": "assistant", "content": resp.content})
        results = []
        for b in resp.content:
            if b.type == "tool_use":
                try:
                    out = REGISTRY[b.name](**b.input)
                    results.append({"type": "tool_result", "tool_use_id": b.id, "content": json.dumps(out)})
                except Exception as e:                       # tell the model what went wrong
                    results.append({"type": "tool_result", "tool_use_id": b.id, "is_error": True, "content": str(e)})
        messages.append({"role": "user", "content": results})
    raise RuntimeError("tool loop did not finish")

print(run("Is it hotter in Kolkata or Chennai right now?"))

The model can request several tools in one turn (parallel calls); execute them all and return every result in a single user message, each tied to its tool_use_id.

Safety rules the moment a model can act

  1. Validate arguments with a schema before executing. Model output is untrusted input.
  2. Least privilege. A read-only database role for a query tool; no shell unless sandboxed.
  3. Confirm irreversible actions (payments, deletes, emails) with a human or a policy check.
  4. Bound the loop: maximum turns, maximum cost, wall-clock timeout.
  5. Never let tool output act as instructions. Text fetched from the web or a document can contain injected commands; treat it as data.
  6. Make tools idempotent where you can, so a retry does not duplicate an effect.

Writing good tool descriptions

The description is the prompt for tool selection. State when to use the tool and when not to, document each parameter, and return compact, relevant results. Vague descriptions cause wrong calls more than weak models do.

Common mistakes

  • No iteration cap, so a confused model loops until the budget is gone.
  • Returning huge raw payloads that flood the context.
  • Swallowing errors instead of returning them so the model can adapt.

Exercises

  1. Add a calculator and a date tool and ask a question that needs both in the same turn.
  2. Write a test that feeds a malicious argument (a path traversal string) and confirms your validation rejects it.

You are done when you can…

  • Implement the complete tool-call loop with a hard iteration limit
  • Return tool errors to the model in a form it can recover from
  • List the checks you apply before executing any model-chosen action