Skip to content

Module 15: Give a model tools over the graph

Learning objectives

By the end of this module, you can:

  • O1. Write a tool definition: a name, a description that says when to call the tool, and an input schema.
  • O2. Implement a tool as a walk through the graph, from a question to its code list and categories, and return a clear error when nothing matches.
  • O3. Run one model turn by hand: route a tool_use request to your function, and build the tool_result that goes back, with the matching tool_use_id.
  • O4. Choose between a grounding pack and a tool for a given need, or combine the two.

Prerequisites: Module 14

Time: 45 min self-paced / 60 min instructor-led.

Needs: No server. An Anthropic API key for the one real model loop, which you can skip: every other example runs without it.

New in this module: tool definitions, input_schema, tool_use and tool_result blocks, tool_use_id, is_error, stop_reason


1. The limit of a pack

Module 14 put facts in the prompt. That works, and it stops working for the same reason every time: you must decide what to send before you know what the model will need.

Retrieve too little, and the answer is not there. Retrieve too much, and you pay for it on every request. Some questions need a walk you cannot plan for. Here is a plain question that users of a labour force survey ask all the time. The keyword match finds the two categories with "tertiary" in their labels, and one step along the edges brings their codes. The answer, the variable EDUC, is three steps away: category, code, code list, variable.

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        if node.label != "Dataset":
            nodes[node.key] = node
    for edge in chunk.relationships:
        if edge.start in nodes:
            edges.append((edge.start, edge.end))


def text_of(node):
    """Return all the text of a node, in lower case."""
    return " ".join(
        plain(v) for v in node.properties.values() if isinstance(v, (str, Text))
    ).lower()


question = "Which variables tell me if someone has a tertiary degree?"
words = {word.lower().strip("?.,") for word in question.split() if len(word) > 3}
hits = {key for key, node in nodes.items() if any(word in text_of(node) for word in words)}
sent = (
    hits
    | {end for start, end in edges if start in hits}
    | {start for start, end in edges if end in hits}
)

print("Kinds of node sent:", sorted({nodes[key].label for key in sent}))
print(
    "Variables sent:",
    sorted(plain(nodes[key].properties["name"]) for key in sent if nodes[key].label == "Variable"),
)

Expected output:

Kinds of node sent: ['Category', 'Code', 'CodeList', 'Concept', 'QuestionConstruct', 'QuestionItem', 'Variable']
Variables sent: ['REGION']

The pack holds a variable, but the wrong one. REGION got in because its question, "In which region do you live?", has the word "which". EDUC, the answer, is not there. You could add a second step, then a third, but each step makes every request bigger, for every question. "Which variables come from questions with a yes or no answer?" is four steps from the categories Yes and No, and no keyword finds it.

The other way is to stop guessing. Give the model a tool, and let it ask.

2. A tool is a function plus a description

A tool is a function that you run on the model's behalf. The model never runs code. It asks for a call, you run the function, and you send back the result. To ask, the model needs three things from you:

  • a name;
  • a description that tells it when to call the tool;
  • an input schema, a JSON Schema for the arguments.

People spend too little effort on the description. The model reads it to decide whether the tool fits a request, so it should say when to call it, not only what it does:

ANSWER_OPTIONS_TOOL = {
    "name": "get_answer_options",
    "description": (
        "Return the answer options a respondent could choose for a survey "
        "question. Call this whenever the user asks what someone could answer, "
        "what a variable's values mean, or which categories a question uses. "
        "Matches on question text, case-insensitively."
    ),
    "input_schema": {
        "type": "object",
        "properties": {
            "question": {
                "type": "string",
                "description": "The question text, or any distinctive part of it.",
            }
        },
        "required": ["question"],
    },
}

print(ANSWER_OPTIONS_TOOL["name"], "->", sorted(ANSWER_OPTIONS_TOOL["input_schema"]["properties"]))

Expected output:

get_answer_options -> ['question']

3. The tool walks the graph

Now the function. It is the code-list path from Module 9, wrapped so that it takes a question and returns its options:

  1. Find the QuestionItem whose text matches.
  2. Follow USES_CODELIST to its code list.
  3. From the code list, follow CONTAINS to each code, or stay on the code list, then HAS_CATEGORY to the category. In Cypher, that is (cl:CodeList)-[:CONTAINS*0..1]->()-[:HAS_CATEGORY]->(cat).

The third step covers both shapes of a code list. A DDI 3.2 or 3.3 code has an ID, as in this survey, so it is a node between the code list and its category. A code with no ID, as in DDI 3.1, leaves the category on the code list itself. Exercise 3 shows both.

The Memory tab walks the IR in Python, with no database. The Neo4j tab loads the same file into Neo4j, as the dataset m15-survey, and walks it in Cypher. The tool gives the same answers on both, and the model cannot tell them apart. A database does not keep the order of the file, so the Cypher sorts the answers by the value of their code, 1 first.

import json

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        edges.append((edge.start, edge.type, edge.end))


def follow(start, rel_type):
    """Every node reachable from `start` by one `rel_type` edge."""
    return [end for s, t, end in edges if s == start and t == rel_type]


def get_answer_options(question: str) -> dict:
    """The tool's implementation. Its return value goes back to the model."""
    for key, node in nodes.items():
        if node.label != "QuestionItem":
            continue
        text = plain(node.properties.get("question_text", ""))
        if question.lower() not in text.lower():
            continue

        options = []
        for code_list in follow(key, "USES_CODELIST"):
            # A code with an ID is a node that its code list CONTAINS, and
            # the category hangs off the code. A code with no ID leaves the
            # category on the code list itself.
            for owner in [code_list, *follow(code_list, "CONTAINS")]:
                for category in follow(owner, "HAS_CATEGORY"):
                    found = nodes[category]
                    options.append(plain(found.properties.get("label")))
        return {"question": text, "options": options}

    return {"error": f"No question matching {question!r}"}


print(json.dumps(get_answer_options("education"), indent=2))
print(json.dumps(get_answer_options("income"), indent=2))

Expected output:

{
  "question": "What is the highest level of education you have completed?",
  "options": [
    "Primary or less (ISCED 0-1)",
    "Lower secondary (ISCED 2)",
    "Upper secondary (ISCED 3)",
    "Post-secondary non-tertiary (ISCED 4)",
    "Tertiary (ISCED 5-8)"
  ]
}
{
  "error": "No question matching 'income'"
}
import json
import os

from neo4j import GraphDatabase

import ddigraph
from ddigraph.lens.neo4j import Neo4jLens

ddigraph.load("tests/fixtures/lfs_lifecycle.xml", dataset_id="m15-survey", replace=True)
driver = GraphDatabase.driver(
    os.environ["DDIGRAPH_NEO4J_URI"],
    auth=(os.environ["DDIGRAPH_NEO4J_USER"], os.environ["DDIGRAPH_NEO4J_PASSWORD"]),
)

# The same walk in Cypher: question, code list, code (or none), category,
# with the answers in the order of their codes
ANSWER_OPTIONS = """
MATCH (q:QuestionItem)-[:IN_DATASET]->(:Dataset {dataset_id: $dataset})
WHERE toLower(q.question_text) CONTAINS toLower($question)
OPTIONAL MATCH (q)-[:USES_CODELIST]->(:CodeList)-[:CONTAINS*0..1]->(code)-[:HAS_CATEGORY]->(cat:Category)
WITH q, cat ORDER BY code.value
RETURN q.question_text AS question, collect(cat.label) AS options
"""


def get_answer_options(question: str) -> dict:
    """The tool's implementation. Its return value goes back to the model."""
    records, _, _ = driver.execute_query(ANSWER_OPTIONS, question=question, dataset="m15-survey")
    if not records:
        return {"error": f"No question matching {question!r}"}
    return {"question": records[0]["question"], "options": records[0]["options"]}


print(json.dumps(get_answer_options("education"), indent=2))
print(json.dumps(get_answer_options("income"), indent=2))

Neo4jLens(driver).purge("m15-survey")  # clean up: remove this module's dataset
driver.close()

Expected output:

{
  "question": "What is the highest level of education you have completed?",
  "options": [
    "Primary or less (ISCED 0-1)",
    "Lower secondary (ISCED 2)",
    "Upper secondary (ISCED 3)",
    "Post-secondary non-tertiary (ISCED 4)",
    "Tertiary (ISCED 5-8)"
  ]
}
{
  "error": "No question matching 'income'"
}

The second call matters as much as the first. This survey has no question about income, and the tool says so. Return a clear error, not an empty result. {"options": []} reads to a model as "this question has no answer options". That is false, and the model would report it as a fact. An error tells it that the lookup failed, and it will say so.

4. A model turn, by hand

How does the tool meet the model? The exchange always has the same shape:

  1. You send the question, with the tool definitions.
  2. The model answers with a tool_use block: the tool's name, its input, and an id. The reply's stop_reason is "tool_use".
  3. You run the function, and send a tool_result block back, in a user turn. Its tool_use_id repeats the id, so the API can pair the result with the call.
  4. The model reads the result and writes its answer.

You can play the model's part in step 2 yourself, with a hand-written tool_use block. That proves your side of the exchange without a key. SimpleNamespace builds an object with the same attributes as a block from the Anthropic SDK:

import json
from types import SimpleNamespace

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        edges.append((edge.start, edge.type, edge.end))


def follow(start, rel_type):
    """Every node reachable from `start` by one `rel_type` edge."""
    return [end for s, t, end in edges if s == start and t == rel_type]


def get_answer_options(question: str) -> dict:
    """The tool's implementation. Its return value goes back to the model."""
    for key, node in nodes.items():
        if node.label != "QuestionItem":
            continue
        text = plain(node.properties.get("question_text", ""))
        if question.lower() not in text.lower():
            continue
        options = []
        for code_list in follow(key, "USES_CODELIST"):
            for owner in [code_list, *follow(code_list, "CONTAINS")]:
                for category in follow(owner, "HAS_CATEGORY"):
                    options.append(plain(nodes[category].properties.get("label")))
        return {"question": text, "options": options}
    return {"error": f"No question matching {question!r}"}


TOOLS = {"get_answer_options": get_answer_options}


def tool_results(content):
    """Run each tool_use block of a reply; return the user turn that answers it."""
    results = []
    for block in content:
        if block.type != "tool_use":
            continue
        output = TOOLS[block.name](**block.input)
        result = {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(output)}
        if "error" in output:
            result["is_error"] = True
        results.append(result)
    return {"role": "user", "content": results}


# The model's reply, written by hand: some text, then a request for the tool
reply = [
    SimpleNamespace(type="text", text="I will look up the answer options."),
    SimpleNamespace(
        type="tool_use",
        id="toolu_01",
        name="get_answer_options",
        input={"question": "look for work"},
    ),
]
print(json.dumps(tool_results(reply), indent=2))

Expected output:

{
  "role": "user",
  "content": [
    {
      "type": "tool_result",
      "tool_use_id": "toolu_01",
      "content": "{\"question\": \"In the last four weeks, did you look for work?\", \"options\": [\"Yes\", \"No\"]}"
    }
  ]
}

That turn is exactly what goes back to the API. The content of a tool_result is a string, so the dictionary travels as JSON. When the tool returns an error, tool_results also sets is_error, which tells the model plainly that the call failed.

5. The real loop

With a key, the same pieces drive a real model. This block calls the Anthropic API. It needs the anthropic package and an API key, so the test suite does not run it. It uses ANSWER_OPTIONS_TOOL and get_answer_options from Sections 2 and 3:

import anthropic

client = anthropic.Anthropic()

messages = [
    {"role": "user", "content": "What can people answer when asked if they looked for work?"}
]

response = client.beta.messages.create(
    model="claude-opus-5-5",
    max_tokens=16000,
    betas=["server-side-fallback-2026-07-01"],
    fallbacks="default",
    tools=[ANSWER_OPTIONS_TOOL],
    messages=messages,
)

if response.stop_reason == "tool_use":
    tool_call = next(block for block in response.content if block.type == "tool_use")
    result = get_answer_options(**tool_call.input)

    messages.append({"role": "assistant", "content": response.content})
    messages.append(
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": tool_call.id,
                    "content": json.dumps(result),
                }
            ],
        }
    )

    response = client.beta.messages.create(
        model="claude-opus-5-5",
        max_tokens=16000,
        betas=["server-side-fallback-2026-07-01"],
        fallbacks="default",
        tools=[ANSWER_OPTIONS_TOOL],
        messages=messages,
    )

for block in response.content:
    if block.type == "text":
        print(block.text)

Model names change. The model list has the current ones. fallbacks="default" lets the API retry on another model if this one declines the request. It is a beta feature, so the call goes through client.beta.messages.

Three things are easy to get wrong:

  • Append the whole response.content, not only its text. It holds the tool_use block, and the next request needs it to match your result to the call.
  • tool_use_id must match the id of the call. It is how the API pairs a result with its call, and it is not optional.
  • One round is not the loop. A model may call a tool, read the result, and call another. Real code loops until stop_reason is no longer "tool_use", and runs every tool_use block of a reply, as tool_results in Section 4 does. The Anthropic SDK also ships a tool runner that loops for you.

6. A pack or a tool?

Grounding pack (Module 14) Tools (this module)
Graph size Small, or narrow after retrieval Any
Question shape Known in advance Open-ended
Round trips One Two or more
Fails by Leaving out what was needed Calling the wrong tool

The two combine well. A small pack tells the model what the survey is and which kinds of item it holds. The tools let it fetch the details. The pack stays cheap, because it no longer has to be complete:

from collections import Counter

from ddigraph import iter_graph

counts = Counter(
    node.label
    for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml")
    for node in chunk.nodes
    if node.label != "Dataset"
)
kinds = ", ".join(f"{count} {label}" for label, count in sorted(counts.items()))
print(f"This survey holds {kinds}. Use the tools to look up details.")

Expected output:

This survey holds 23 Category, 23 Code, 6 CodeList, 5 Concept, 1 IfThenElse, 1 Instrument, 8 QuestionConstruct, 8 QuestionItem, 2 Sequence, 2 Universe, 7 Variable. Use the tools to look up details.

That one line goes in the system prompt. Whatever the size of the survey, it stays one line.


Exercises

Scenario

Your help desk assistant from Module 14 now answers questions about a catalogue of thousands of variables, from many surveys. A pack can no longer hold them. You give the assistant tools, and you test each one before it meets a model.

Exercise 1 (O1, O2). Write a second tool, find_questions_about, over tests/fixtures/lfs_codebook.xml: given a concept, it returns each variable that uses that concept (USES_CONCEPT), with the variable's name and question text. Write its definition too, with a description that says when to call it. Print the tool's name, then the results for demographic characteristics and for health.

Expected output:

find_questions_about
{
  "concept": "demographic characteristics",
  "variables": [
    {
      "variable": "AGEGRP",
      "question": null
    },
    {
      "variable": "AGE",
      "question": "What was your age on your last birthday?"
    },
    {
      "variable": "SEX",
      "question": "What is your sex?"
    }
  ]
}
{"error": "No concept matching 'health'"}
Answer
import json

from ddigraph import iter_graph
from ddigraph.ir.model import Text

CONCEPT_TOOL = {
    "name": "find_questions_about",
    "description": (
        "Find the variables, and the questions behind them, that measure a "
        "concept. Call this when the user asks which questions or variables "
        "cover a topic or concept."
    ),
    "input_schema": {
        "type": "object",
        "properties": {"concept": {"type": "string", "description": "The concept name."}},
        "required": ["concept"],
    },
}


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_codebook.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        edges.append((edge.start, edge.type, edge.end))


def find_questions_about(concept: str) -> dict:
    """The tool's implementation: the variables that use a concept."""
    found = []
    matched = False
    for start, rel_type, end in edges:
        if rel_type != "USES_CONCEPT":
            continue
        if concept.lower() != plain(nodes[end].properties.get("label", "")).lower():
            continue
        matched = True
        variable = nodes[start]
        found.append(
            {
                "variable": plain(variable.properties.get("name")),
                "question": plain(variable.properties.get("question_text")),
            }
        )
    if not matched:
        return {"error": f"No concept matching {concept!r}"}
    return {"concept": concept, "variables": found}


print(CONCEPT_TOOL["name"])
print(json.dumps(find_questions_about("demographic characteristics"), indent=2))
print(json.dumps(find_questions_about("health")))
find_questions_about
{
  "concept": "demographic characteristics",
  "variables": [
    {
      "variable": "AGEGRP",
      "question": null
    },
    {
      "variable": "AGE",
      "question": "What was your age on your last birthday?"
    },
    {
      "variable": "SEX",
      "question": "What is your sex?"
    }
  ]
}
{"error": "No concept matching 'health'"}

AGEGRP has no question: it is derived from AGE. The tool says null, and the model can say so, rather than invent a question. The survey has no health questions, so the second call returns an error.

The tool loops over every USES_CONCEPT edge, and it does not stop at the first concept that matches. That matters here. DDI-Codebook repeats the concept's text in each variable, so this graph holds three "Demographic characteristics" nodes, one for each of SEX, AGE and AGEGRP. A tool that stopped at the first one would find SEX alone.

Keep it a separate tool rather than a mode of get_answer_options. The model chooses by reading descriptions, and "returns answer options or questions, depending on which argument you pass" describes nothing well. Two tools with clear edges beat one tool with a mode flag.

Exercise 2 (O3). A model may ask for several tools in one reply. Write a reply by hand with two tool_use blocks: get_answer_options for education (id toolu_01) and for income (id toolu_02). Send back one user turn that holds both results, each with its own tool_use_id, and mark the failed one with is_error. Print the tool_use_id and is_error of each result.

Expected output:

Turns to send: 1
toolu_01 is_error=False
toolu_02 is_error=True
Answer
import json
from types import SimpleNamespace

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        edges.append((edge.start, edge.type, edge.end))


def follow(start, rel_type):
    """Every node reachable from `start` by one `rel_type` edge."""
    return [end for s, t, end in edges if s == start and t == rel_type]


def get_answer_options(question: str) -> dict:
    """The tool's implementation. Its return value goes back to the model."""
    for key, node in nodes.items():
        if node.label != "QuestionItem":
            continue
        text = plain(node.properties.get("question_text", ""))
        if question.lower() not in text.lower():
            continue
        options = []
        for code_list in follow(key, "USES_CODELIST"):
            for owner in [code_list, *follow(code_list, "CONTAINS")]:
                for category in follow(owner, "HAS_CATEGORY"):
                    options.append(plain(nodes[category].properties.get("label")))
        return {"question": text, "options": options}
    return {"error": f"No question matching {question!r}"}


TOOLS = {"get_answer_options": get_answer_options}
reply = [
    SimpleNamespace(
        type="tool_use", id="toolu_01", name="get_answer_options", input={"question": "education"}
    ),
    SimpleNamespace(
        type="tool_use", id="toolu_02", name="get_answer_options", input={"question": "income"}
    ),
]

results = []
for block in reply:
    if block.type == "tool_use":
        output = TOOLS[block.name](**block.input)
        results.append(
            {
                "type": "tool_result",
                "tool_use_id": block.id,
                "content": json.dumps(output),
                "is_error": "error" in output,
            }
        )
turns = [{"role": "user", "content": results}]

print("Turns to send:", len(turns))
for result in turns[0]["content"]:
    print(result["tool_use_id"], f"is_error={result['is_error']}")
Turns to send: 1
toolu_01 is_error=False
toolu_02 is_error=True

All the results of one reply go back in a single user turn. Splitting them over several turns teaches the model to stop asking for tools in parallel. is_error keeps the failed lookup from reading as a fact.

Exercise 3 (O2). In DDI 3.2 and 3.3, a code has an ID of its own, as in this survey. In DDI 3.1, and in many older files from archives, it has none. Make a copy of tests/fixtures/lfs_lifecycle.xml in which each <l:Code> loses its URN, agency, ID and version. On the copy, compare two walks from the Yes or no code list to its categories: one that always goes through the codes (CONTAINS, then HAS_CATEGORY), and one that follows CONTAINS zero or one time, as get_answer_options does.

Expected output:

Through the codes: []
CONTAINS zero or one time: ['Yes', 'No']
Answer
import re
from pathlib import Path

from ddigraph import iter_graph
from ddigraph.ir.model import Text


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


# A code in the DDI 3.1 style: no URN, agency, ID or version of its own
text = Path("tests/fixtures/lfs_lifecycle.xml").read_text(encoding="utf-8")
old_style = re.sub(
    r'<l:Code isUniversallyUnique="true">\s*<r:URN>.*?</r:Version>', "<l:Code>", text
)
Path("old-codes.xml").write_text(old_style, encoding="utf-8")

nodes, edges = {}, []
for chunk in iter_graph("old-codes.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        edges.append((edge.start, edge.type, edge.end))


def follow(start, rel_type):
    """Every node reachable from `start` by one `rel_type` edge."""
    return [end for s, t, end in edges if s == start and t == rel_type]


code_list = next(
    key
    for key, node in nodes.items()
    if node.label == "CodeList" and plain(node.properties["label"]) == "Yes or no"
)
through_codes = [
    plain(nodes[c].properties["label"])
    for code in follow(code_list, "CONTAINS")
    for c in follow(code, "HAS_CATEGORY")
]
zero_or_one = [
    plain(nodes[c].properties["label"])
    for owner in [code_list, *follow(code_list, "CONTAINS")]
    for c in follow(owner, "HAS_CATEGORY")
]
print("Through the codes:", through_codes)
print("CONTAINS zero or one time:", zero_or_one)
Through the codes: []
CONTAINS zero or one time: ['Yes', 'No']

With no ID, a code is not a node of its own, so the category hangs off the code list, and the walk through the codes finds nothing. Worse, a tool built on it would return {"options": []}, which the model reads as "no answers". Following CONTAINS zero or one time covers both shapes. The copy also fails the DDI 3.3 XSD, which requires an ID on each code: it stands in for an older file, not for a valid 3.3 one.

Exercise 4 (O4). You must choose for a catalogue of 3,000 yes-or-no variables. Build such a Codebook (as in Module 13), and measure two costs: a full pack with one line per variable and its answers, and the result of one tool call for one variable. Print the size of each, and the number of tool calls that would cost as much as one pack.

Expected output:

Full pack: 73971 characters, about 18492 tokens per request
One tool result: 55 characters
Tool calls for the cost of one pack: 1344
Answer
import json
from pathlib import Path

from ddigraph import iter_graph
from ddigraph.ir.model import Text

variables = "".join(
    f'<var ID="v{n}" name="Q{n}"><labl>Question {n}</labl>'
    "<catgry><catValu>1</catValu><labl>Yes</labl></catgry>"
    "<catgry><catValu>2</catValu><labl>No</labl></catgry></var>"
    for n in range(1, 3001)
)
Path("big.xml").write_text(
    f"<codeBook><dataDscr>{variables}</dataDscr></codeBook>", encoding="utf-8"
)


def plain(value):
    """Return a property as Python has it, and a Text as its string."""
    return value.value if isinstance(value, Text) else value


nodes, answers = {}, {}
for chunk in iter_graph("big.xml"):
    for node in chunk.nodes:
        nodes[node.key] = node
    for edge in chunk.relationships:
        if edge.type == "USES_CATEGORY":
            answers.setdefault(edge.start, []).append(plain(nodes[edge.end].properties["label"]))

lines = ["The codebook has these variables. Do not invent variables that are not listed."]
for key, options in answers.items():
    lines.append(f"- {plain(nodes[key].properties['label'])}: {', '.join(options)}")
pack = "\n".join(lines)

first = next(iter(answers))
result = json.dumps(
    {"variable": plain(nodes[first].properties["label"]), "options": answers[first]}
)

print("Full pack:", len(pack), "characters, about", len(pack) // 4, "tokens per request")
print("One tool result:", len(result), "characters")
print("Tool calls for the cost of one pack:", len(pack) // len(result))
Full pack: 73971 characters, about 18492 tokens per request
One tool result: 55 characters
Tool calls for the cost of one pack: 1344

For this catalogue, a tool wins by far: one full pack costs as much as more than a thousand lookups, and you pay for it on every request. For the one questionnaire of Module 14, a pack is still a fair choice: about 3,000 tokens, in one request, with no round trip. Measure before you choose, and keep a one-line pack that tells the model what the tools can find.


Quiz

Question 1 (O1): Why is the description the most important part of a tool definition?

A. Because the API rejects a tool without one.

B. Because the model reads it to decide whether to call the tool, so it must say when the tool applies.

C. Because it is shown to the user.

D. Because it sets the types of the inputs.

Answer

B. The model chooses tools by their descriptions. A description that says only what the function does leaves the model guessing when to use it. D is the input schema's job, not the description's.

Question 2 (O2): Your tool finds no question matching the user's words. Why return an error rather than {\"options\": []}?

A. Because JSON cannot hold an empty list.

B. Because an empty list reads as "this question has no answer options", which is false, and the model will report it as a fact.

C. Because the API retries a call that returns an error.

D. Because an empty list costs more tokens.

Answer

B. An empty result is a claim about the survey. An error is a claim about the lookup, which is the truth here. C is wrong: the API does not rerun your tools; the model may choose to call again.

Question 3 (O3): You send a tool_result whose tool_use_id does not match the id of the call. What goes wrong?

A. Nothing: the API pairs results by order.

B. The API cannot pair the result with the call, and refuses the request.

C. The model ignores the result and guesses.

D. The tool runs again.

Answer

B. tool_use_id is how a result finds its call, and every tool_use block needs its result. A is the tempting shortcut: with two calls in one reply, order alone could swap two answers.

Question 4 (O3): After the first reply, you append only the reply's text to messages, then send the tool_result. Why does the next request fail?

A. Because the text is too long.

B. Because the tool_use block is missing from the history, so the tool_result refers to a call the API never saw.

C. Because a user turn cannot follow an assistant turn.

D. Because the tool must be defined again.

Answer

B. Append the whole response.content. The tool_use block in it is what the tool_result answers. D sounds plausible, but you do send tools on every request anyway; the missing piece is the call.

Question 5 (O4): A survey team asks a fixed set of five questions about one small instrument, every day. Pack or tool?

A. A tool, always: tools are the modern way.

B. A pack: the graph is small and the questions are known, so one request with the facts is cheaper and simpler.

C. Neither: the model already knows the instrument.

D. Both, with a pack that lists every node and a tool for each node.

Answer

B. A small graph and known questions are the case a pack fits best: one round trip, nothing to call. A tool earns its extra round trip when the graph is large or the questions are open. C is the mistake Module 14 began with.


Check yourself

  • I can write a tool definition with a name, a description that says when to call the tool, and an input schema. (O1)
  • I can implement a tool as a walk through the graph, from a question to its categories, and return a clear error when nothing matches. (O2)
  • I can route a tool_use request to my function by hand, and build the tool_result that goes back with the matching tool_use_id. (O3)
  • I can choose between a grounding pack and a tool for a given need, or combine the two. (O4)

Next: Module 16: Capstone projects