Ir para o conteúdo

Lição 16 · Retrieval and Tools

Tool Calling with Llama

Learn how Llama asks to call functions, Meta's output formats, how Ollama, llama.cpp and vLLM support tools and how to build a safe, validated tool loop.

Tool calling lets a model ask your program to run a function, such as "look up order 1042". The model only produces a request. Your code decides whether to run it. If the general idea is new, read what are tools? first.

The loop

  1. You send messages plus tool definitions (name, description, parameter schema).
  2. The model replies with a tool call or a normal answer.
  3. Your code validates and runs the call.
  4. You send the result back as a tool message.
  5. The model writes the final answer, or asks for another call.

Llama's raw formats

Meta's documentation describes several formats. In Llama 3.x, one style is a bracketed, Python-like call such as [get_order(order_id="1042")], and other styles use JSON. Llama 4's documentation describes both a Python-style and a JSON-style call, with results returned in the ipython role.

You rarely parse these by hand. Serving software parses them into structured fields, if it is configured correctly:

  • Ollama accepts a tools list in /api/chat and returns tool_calls with a function name and arguments.
  • llama.cpp needs --jinja on the server for OpenAI-style function calling. Its documentation explains how to check that the chat template supports tools.
  • vLLM needs --enable-auto-tool-choice plus a parser that matches the model, for example llama3_json for Llama 3.x JSON calls or llama4_pythonic for Llama 4, with a matching chat template. Its documentation says that parallel calls are not supported for Llama 3, while Llama 4 supports them.

Check your exact model and server version. Support is not the same everywhere.

A real definition

JSON
{
  "type": "function",
  "function": {
    "name": "get_order_status",
    "description": "Look up the status of one order by its ID.",
    "parameters": {
      "type": "object",
      "properties": {"order_id": {"type": "string", "description": "Order ID, for example A-1042"}},
      "required": ["order_id"]
    }
  }
}

A clear description is part of your prompt. Name tools after what they do, and keep the parameter list small.

Validate before you run

Models can invent tool names, send wrong types, add extra arguments or choose the wrong tool. Check everything.

Python Stand-in: a safe tool loop with a fake model

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last two calls are rejected. The step limit prevents endless loops.

Permissions and safety

  • Give the model the fewest tools it needs.
  • Make read-only tools the default.
  • Require human approval before actions that send, pay, delete or change data.
  • Check the user's rights inside the tool. The model's request is not authorization.
  • Log calls and results, without secrets.

Text returned by a tool, such as a web page or an email, can carry instructions. Treat it as data. See executing tool calls safely.

When it fails

  • A call appears as plain text: the server is not parsing it. Check flags, parser and template.
  • The model never calls: improve the tool description or try a stronger model.
  • Wrong arguments: simplify the schema and add examples.
  • A small model picks badly: measure on your own cases, including "no tool needed".

llama.cpp's documentation also warns that extreme KV cache quantization can degrade tool calling.

Designing good tools

A tool should do one clear thing. Prefer search_orders(customer_id) over a general run_query(text), which would let a mistaken or manipulated model read or change anything. Return short, useful results. A tool that returns thousands of rows fills the context and confuses the model. When something goes wrong, return a helpful error such as "order IDs look like A-1042", so the model can correct itself within your step limit.

Keep the number of tools small. Each definition uses context, and a long list of similar tools makes the choice harder. If you have many functions, select the relevant few in your own code before calling the model.

Testing tool use

Write test cases with three kinds of questions: ones that need a tool, ones that need no tool, and ones where required information is missing. For the last kind, the right behavior is usually to ask the user, not to invent an argument. Record which tool was chosen, whether the arguments were right and whether the final answer used the result correctly. Rerun these cases whenever you change the model, quantization, template or server flags.

What to show the user

Make tool activity visible. Tell users which information was looked up and, before any change, show exactly what will happen: the action, the target and the values. A confirmation such as "Cancel order A-1043?" is useful only when it is built from the validated arguments in your code, not from the model's description of what it intends to do.

If a tool fails, say so honestly. A model may produce a confident sentence even when a call returned an error, so check the result status in your code and handle failures yourself when accuracy matters. Never report an action as done unless your function confirms that it happened.

Start read-only. Build your first tool-using feature with read-only tools. Watch the logs for a while, study the wrong choices and add them to your tests. Add actions that change data only after the read-only version behaves well and the confirmation step works.

A last review question. Before you add any tool, ask what happens if the model calls it at the wrong moment with the worst allowed arguments. If that answer worries you, narrow the tool or add an approval step.

Common mistakes

Never execute a model's output as code, for example by passing a Python-style call string to eval. Parse it and look up the function in an allowlist.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Who executes a Llama tool call?

    The model only asks. Your code decides and runs.
  2. 2. The model asks for delete_all(), and no such tool is allowed. What should happen?

    Only allowlisted tools may run.
  3. 3. What is a likely reason tool calls appear as plain text?

    The server must be configured to recognize the model's call format.
  4. 4. Which action should normally require human approval?

    Actions that move money or change data need a person in the loop.

Summary

  • Tool calling is a request from the model that your code carries out.
  • Llama has several raw formats, and servers parse them when configured.
  • Validate names and arguments, limit steps and require approval for risky actions.
  • Treat tool results as untrusted data.

Next: When to Fine-tune Llama

Seu progresso fica salvo neste navegador. Não precisa de conta.