TExcelTAD
Home › Generative AI & LLMs › Tool Use / Function Calling

Tool Use / Function Calling

An LLM on its own can only produce text. Tool use (also called function calling) lets it ask your code to do things: look up an order, query a database, do exact maths, call a weather service, search documents. The model never runs anything itself — it outputs a structured request, your application executes it, and you send the result back.

The loop

text
1. You send: messages + a list of tool definitions (name, description, JSON schema)
2. Model replies: stop_reason = "tool_use", with a block {name, input}
3. Your code runs the tool with that input
4. You send back: a "tool_result" block with the output
5. Model replies with a final answer (or asks for another tool)

Defining a tool (Anthropic API)

python
import anthropic

client = anthropic.Anthropic()
tools = [{
    "name": "get_order_status",
    "description": "Look up the shipping status of a customer order by its ID.",
    "input_schema": {
        "type": "object",
        "properties": {"order_id": {"type": "string", "description": "e.g. A-1042"}},
        "required": ["order_id"],
    },
}]

response = client.messages.create(
    model="claude-sonnet-5-5", max_tokens=500, tools=tools,
    messages=[{"role": "user", "content": "Where is my order A-1042?"}],
)
# response.stop_reason == "tool_use"
# response.content contains a block like:
#   {"type": "tool_use", "id": "toolu_...", "name": "get_order_status", "input": {"order_id": "A-1042"}}

(Reference code.) The description matters a lot: it is how the model decides when to use a tool. Other providers use the same idea with slightly different field names.

A complete loop with a fake model

Below, the model is replaced by a deterministic function that behaves like a real one: on the first call it requests a tool; once it sees a tool result, it writes the answer. Everything else — the tool registry, argument validation, the loop and the message format — is what you would write for a real API.

python · try it yourself
import json

ORDERS = {"A-1042": {"status": "shipped", "carrier": "ParcelGo", "eta": "Thursday"}}

def get_order_status(order_id):
    order = ORDERS.get(order_id)
    return order if order else {"error": f"no order {order_id}"}

TOOLS = {"get_order_status": {"fn": get_order_status, "required": ["order_id"]}}

def fake_model(messages):
    last = messages[-1]
    if last["role"] == "user" and isinstance(last["content"], str):
        order_id = last["content"].split()[-1].strip("?")
        return {"stop_reason": "tool_use", "content": [
            {"type": "tool_use", "id": "call_1", "name": "get_order_status", "input": {"order_id": order_id}}]}
    result = json.loads(last["content"][0]["content"])
    text = (f"Your order is {result['status']} with {result['carrier']} and should arrive on {result['eta']}."
            if "error" not in result else "I couldn't find that order. Could you check the ID?")
    return {"stop_reason": "end_turn", "content": [{"type": "text", "text": text}]}

def run(user_text, max_steps=5):
    messages = [{"role": "user", "content": user_text}]
    for step in range(max_steps):
        reply = fake_model(messages)
        messages.append({"role": "assistant", "content": reply["content"]})
        if reply["stop_reason"] != "tool_use":
            return reply["content"][0]["text"]
        results = []
        for block in reply["content"]:
            if block["type"] != "tool_use":
                continue
            tool = TOOLS.get(block["name"])
            missing = [k for k in tool["required"] if k not in block["input"]] if tool else []
            output = ({"error": "unknown tool"} if not tool else
                      {"error": f"missing {missing}"} if missing else tool["fn"](**block["input"]))
            print(f"tool call: {block['name']}({block['input']}) -> {output}")
            results.append({"type": "tool_result", "tool_use_id": block["id"], "content": json.dumps(output)})
        messages.append({"role": "user", "content": results})
    return "Stopped: too many steps."

print(run("Where is my order A-1042?"))
tool call: get_order_status({'order_id': 'A-1042'}) -> {'status': 'shipped', 'carrier': 'ParcelGo', 'eta': 'Thursday'}
Your order is shipped with ParcelGo and should arrive on Thursday.

Notice that the tool result goes back as a user message containing a tool_result block that references the tool_use id. The model then sees the data and writes a natural answer.

A calculator tool

Tools are the standard fix for things LLMs do poorly, such as exact arithmetic. A safe calculator must never pass model output to eval — parse it instead:

python · try it yourself
import ast
import operator

OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
       ast.Div: operator.truediv, ast.Pow: operator.pow, ast.USub: operator.neg}

def calculate(expression):
    def ev(node):
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in OPS:
            return OPS[type(node.op)](ev(node.left), ev(node.right))
        if isinstance(node, ast.UnaryOp) and type(node.op) in OPS:
            return OPS[type(node.op)](ev(node.operand))
        raise ValueError("unsupported expression")
    try:
        return {"result": ev(ast.parse(expression, mode="eval").body)}
    except (ValueError, SyntaxError, ZeroDivisionError) as e:
        return {"error": str(e)}

for expr in ["123456 * 789", "(17 + 5) / 4", "2 ** 10 - 1", "__import__('os').remove('x')", "1/0"]:
    print(f"{expr:<30} -> {calculate(expr)}")
123456 * 789                   -> {'result': 97406784}
(17 + 5) / 4                   -> {'result': 5.5}
2 ** 10 - 1                    -> {'result': 1023}
__import__('os').remove('x')   -> {'error': 'unsupported expression'}
1/0                            -> {'error': 'division by zero'}

Designing good tools

Guideline Why
Clear names and descriptions, including when not to use the tool the model chooses tools from their descriptions
Small, strict input schemas (enums, required fields) fewer malformed calls
Validate inputs in your code anyway the model can still send wrong values
Return errors as results, not crashes the model can apologise, retry or ask the user
Least privilege: read-only where possible limits damage from mistakes or prompt injection
Ask a human before irreversible actions (payments, deletes, emails) keeps people in control
Limit the number of steps in the loop prevents endless tool calling

Note: Some providers also offer server-side tools (web search, code execution) that run on their infrastructure, and standards such as the Model Context Protocol (MCP) let you connect tools to many different AI applications in a uniform way.

Test yourself

Who actually executes a tool when an LLM 'calls' it?

  1. The model, inside the GPU
  2. Your application code
  3. The tokenizer
  4. The user's browser automatically

How is a tool's output given back to the model in the Anthropic Messages API?

  1. As a new system prompt
  2. As a tool_result block in a user message that references the tool_use id
  3. As an assistant message
  4. It isn't; the model guesses

Why should a calculator tool not simply call eval() on the model's input?

  1. eval is too slow
  2. eval would execute arbitrary code the model (or an attacker) supplied
  3. eval can't do multiplication
  4. Python has no eval