Module 14: Ground a language model in the graph¶
Learning objectives
By the end of this module, you can:
- O1. Explain why a model's plausible answer about a survey is a risk, and what a grounding pack changes.
- O2. Build a grounding pack from
iter_graph, withTextvalues unwrapped,urn.textas a fallback name, and the edges included. - O3. Retrieve only the nodes a question needs by keyword, and add their neighbours one edge away.
- O4. Send a pack to a model: put it in the system prompt, say what to do when the answer is absent, and read
response.contentby block type.
Prerequisites: Module 13
Time: 40 min self-paced / 55 min instructor-led.
Needs: No server. An Anthropic API key for the one model call, which you can skip: every other example runs without it.
New in this module: grounding pack, urn.text, keyword retrieval, the anthropic client, response.content
1. What a model does not know¶
Ask a language model which answers a survey question offered, and it gives you a plausible list. Plausible is the problem. The model has read many surveys, so it knows what an education question usually looks like: high school, college, a bachelor's degree, and so on. It will write such a list, and the list will read well. It will not be yours.
Your answers are in your metadata. This module uses the course's sample
survey, a Labour Force Survey in DDI-Lifecycle. Here is what it really
offers for its education question. The code walks from the code list to
each code (CONTAINS), then to the code's category (HAS_CATEGORY):
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]
education = next(
key
for key, node in nodes.items()
if node.label == "CodeList" and plain(node.properties["label"]) == "Highest level of education"
)
for code in follow(education, "CONTAINS"):
for category in follow(code, "HAS_CATEGORY"):
print("Answer option:", plain(nodes[category].properties["label"]))
Expected output:
Answer option: Primary or less (ISCED 0-1)
Answer option: Lower secondary (ISCED 2)
Answer option: Upper secondary (ISCED 3)
Answer option: Post-secondary non-tertiary (ISCED 4)
Answer option: Tertiary (ISCED 5-8)
Five options, each named after its ISCED levels, the international classification of education. The last one puts levels 5 to 8 together, so the survey never asks which degree a person holds. No model could guess that. So the job is not to make the model smarter. It is to put the facts in front of it, and to say clearly that they are the facts. That is called grounding the model.
2. A grounding pack¶
The simplest way is a grounding pack: a short, plain-text description of the graph that goes into the request with the question. You already have what you need from Modules 4 and 12. Three details matter:
- A text property such as
labelis aText, which keeps its language. Theplainfunction below takes the string out of it. - A variable has a short name, such as
EDUC, and a label, such as "Highest level of education". Users ask about both, soname_ofwrites both. - The Dataset node stands for the file, not for an item in it, so the pack leaves it out, with its edge.
When a node has no name and no label, urn.text writes its identity as a
URN, so every line still names something. In this survey, that is the case
of each code.
The whole pack is about 200 lines, so the block prints its size, then only
the lines about the education question, EDUC:
from ddigraph import iter_graph, urn
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
def name_of(node):
"""Name a node by its name and label, or by its URN when it has neither."""
name = plain(node.properties.get("name"))
label = plain(node.properties.get("label"))
if name and label and name != label:
return f'{name} "{label}"'
return name or label or urn.text(node.identity)
nodes, edges = {}, []
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
for node in chunk.nodes:
if node.label != "Dataset": # the file itself, not an item in it
nodes[node.key] = node
for edge in chunk.relationships:
if edge.start in nodes: # leaves out the Dataset's edge
edges.append((edge.start, edge.type, edge.end))
lines = ["The survey contains these items. Do not invent items that are not listed."]
for key, node in sorted(nodes.items(), key=lambda item: item[1].label):
text = node.properties.get("question_text")
lines.append(f"- {node.label}: {name_of(node)}" + (f' — asks "{plain(text)}"' if text else ""))
lines.append("")
lines.append("Links between them:")
for start, rel_type, end in edges:
lines.append(
f"- {nodes[start].label} {name_of(nodes[start])} --{rel_type}--> "
f"{nodes[end].label} {name_of(nodes[end])}"
)
pack = "\n".join(lines)
print(len(lines), "lines,", len(pack), "characters")
for line in lines:
if "EDUC" in line:
print(line)
Expected output:
196 lines, 12264 characters
- QuestionConstruct: EDUC
- QuestionItem: EDUC — asks "What is the highest level of education you have completed?"
- Variable: EDUC "Highest level of education"
- QuestionConstruct EDUC --REFERENCES_QUESTION--> QuestionItem EDUC
- Sequence Main sequence --HAS_CONSTRUCT--> QuestionConstruct EDUC
- QuestionItem EDUC --USES_CODELIST--> CodeList Highest level of education
- QuestionItem EDUC --USES_CONCEPT--> Concept Educational attainment
- Variable EDUC "Highest level of education" --IN_UNIVERSE--> Universe Persons aged 15 and over living in private households
- Variable EDUC "Highest level of education" --REFERENCES_QUESTION--> QuestionItem EDUC
- Variable EDUC "Highest level of education" --USES_CODELIST--> CodeList Highest level of education
- Variable EDUC "Highest level of education" --USES_CONCEPT--> Concept Educational attainment
About 12,000 characters for a questionnaire of 8 questions, and it answers
questions the model would otherwise guess. Note that the pack holds the
links, not only the items. "Which code list does the education question
use?" is a question about an edge, and only the link
QuestionItem EDUC --USES_CODELIST--> CodeList Highest level of education
answers it.
The first line matters too. It tells the model that the list is complete, so it should not add items of its own.
3. Send the pack to a model¶
Put the pack in the system prompt, the part of a request that sets the
rules, and ask the question as usual. This block calls the Anthropic API.
It needs the anthropic package and an API key, so the test suite does not
run it, and you can skip it:
import anthropic
client = anthropic.Anthropic()
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
betas=["server-side-fallback-2026-07-01"],
fallbacks="default",
system=(
"Answer questions about this survey using only the structure below. "
"If the answer is not there, say so rather than guessing.\n\n" + pack
),
messages=[{"role": "user", "content": "Which questions use the Yes or no list?"}],
)
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.
Two details are easy to get wrong.
response.content is a list of blocks, not a string. A response can
start with a thinking block, or hold other kinds of block. Check
block.type before you read block.text. Code that reads
response.content[0].text breaks the first time the first block is not text.
Say what to do when the answer is absent. Without the sentence "If the answer is not there, say so", a model asked about something the pack does not cover will often answer anyway. Ask about income, which this survey does not cover, and it may describe a typical income question. With the sentence, you get "the metadata does not say", which is the answer you want.
The part around the call needs no key, so check it before you spend money. This block builds the system prompt from a shorter pack, the items only, and shows its size. A token is about 4 characters of English, and you pay for the system prompt on every request:
from ddigraph import iter_graph, urn
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
lines = ["The survey contains these items. Do not invent items that are not listed."]
for chunk in iter_graph("tests/fixtures/lfs_lifecycle.xml"):
for node in chunk.nodes:
if node.label != "Dataset":
name = node.properties.get("name") or node.properties.get("label")
lines.append(f"- {node.label}: {plain(name) if name else urn.text(node.identity)}")
pack = "\n".join(lines)
system = (
"Answer questions about this survey using only the structure below. "
"If the answer is not there, say so rather than guessing.\n\n" + pack
)
print(system.splitlines()[0])
print(len(system), "characters, about", len(system) // 4, "tokens")
Expected output:
Answer questions about this survey using only the structure below. If the answer is not there, say so rather than guessing.
2822 characters, about 705 tokens
4. When the graph is too big, retrieve first¶
Ninety nodes fit in a prompt. Sixty thousand do not, and sending them all would waste money even if they did: most of the graph has nothing to do with any one question.
So retrieve first: pick the nodes that the question is about, and send only those. You do not need a vector database to start. Matching the words of the question against the text already in the graph goes a long way. Here is a question a data user often asks about a labour force survey:
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
def relevant(path, question, limit=10):
"""Return nodes whose text overlaps the question."""
words = {word.lower().strip("?.,") for word in question.split() if len(word) > 3}
hits = []
for chunk in iter_graph(path):
for node in chunk.nodes:
haystack = " ".join(
plain(value) for value in node.properties.values() if isinstance(value, (str, Text))
).lower()
score = sum(1 for word in words if word in haystack)
if score:
hits.append((score, node))
hits.sort(key=lambda item: -item[0])
return [node for _score, node in hits[:limit]]
question = "What does ILOSTAT mean and where does it come from?"
for node in relevant("tests/fixtures/lfs_lifecycle.xml", question):
print(node.label, "-", plain(node.properties.get("name")))
Expected output:
QuestionItem - SEX
QuestionItem - AGE
QuestionItem - EDUC
Concept - Place of residence
Concept - Educational attainment
Variable - AGEGRP
Variable - ILOSTAT
Seven nodes instead of ninety. On a real file, it is two hundred instead of sixty thousand, and that is what makes each request affordable.
But look at the hits. All seven score 1. The variable ILOSTAT matches
"ilostat", which is what the question is about. The three questions match
"what", from their question text. Two concepts and the variable AGEGRP
match "where" or "from", from their descriptions. None of those words says
anything about the topic. Python's sort is stable, so a tie keeps the order
of the file, and the one useful hit comes last. With a limit of 5, it would
not have been sent at all. That is fine for a first pass, and it is also
the first thing to improve: Exercise 2 does.
5. Bring the neighbours too¶
A node on its own is half an answer. The variable ILOSTAT has a label,
"Labour force status (ILO)", but where it comes from is in its edges: the
questions it is derived from, its code list and its concept. So once you
have your hits, follow their edges one step, either way, and send what you
find:
from ddigraph import iter_graph, urn
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
def name_of(node):
"""Name a node by its name and label, or by its URN when it has neither."""
name = plain(node.properties.get("name"))
label = plain(node.properties.get("label"))
if name and label and name != label:
return f'{name} "{label}"'
return name or label or urn.text(node.identity)
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.type, edge.end))
def relevant(question, limit=10):
"""Return the keys of the nodes whose text shares a word with the question."""
words = {word.lower().strip("?.,") for word in question.split() if len(word) > 3}
hits = []
for key, node in nodes.items():
haystack = " ".join(
plain(value) for value in node.properties.values() if isinstance(value, (str, Text))
).lower()
score = sum(1 for word in words if word in haystack)
if score:
hits.append((score, key))
hits.sort(key=lambda item: -item[0])
return [key for _score, key in hits[:limit]]
def pack_for(question):
"""Return the edges that touch a hit: the hits and their neighbours."""
hits = relevant(question)
return "\n".join(
f"- {nodes[start].label} {name_of(nodes[start])} --{rel_type}--> "
f"{nodes[end].label} {name_of(nodes[end])}"
for start, rel_type, end in edges
if start in hits or end in hits
)
print(pack_for("What does ILOSTAT mean and where does it come from?"))
Expected output:
- QuestionConstruct EDUC --REFERENCES_QUESTION--> QuestionItem EDUC
- QuestionConstruct SEX --REFERENCES_QUESTION--> QuestionItem SEX
- Variable AGE "Age in completed years" --REFERENCES_QUESTION--> QuestionItem AGE
- Variable SEX "Sex of the person" --REFERENCES_QUESTION--> QuestionItem SEX
- QuestionItem AGE --USES_CONCEPT--> Concept Demographic characteristics
- QuestionItem EDUC --USES_CODELIST--> CodeList Highest level of education
- QuestionItem EDUC --USES_CONCEPT--> Concept Educational attainment
- QuestionItem SEX --USES_CODELIST--> CodeList Sex
- QuestionItem SEX --USES_CONCEPT--> Concept Demographic characteristics
- Variable ILOSTAT "Labour force status (ILO)" --IN_UNIVERSE--> Universe Persons aged 15 and over living in private households
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem LOOK
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem WORK
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem AVAIL
- Variable ILOSTAT "Labour force status (ILO)" --USES_CODELIST--> CodeList Labour force status (ILO)
- Variable ILOSTAT "Labour force status (ILO)" --USES_CONCEPT--> Concept Labour market status
- Variable EDUC "Highest level of education" --REFERENCES_QUESTION--> QuestionItem EDUC
- Variable EDUC "Highest level of education" --USES_CONCEPT--> Concept Educational attainment
- QuestionItem REGION --USES_CONCEPT--> Concept Place of residence
- QuestionConstruct AGE --REFERENCES_QUESTION--> QuestionItem AGE
- Variable AGEGRP "Age group" --IN_UNIVERSE--> Universe Persons aged 15 and over living in private households
- Variable AGEGRP "Age group" --REFERENCES_QUESTION--> QuestionItem AGE
- Variable AGEGRP "Age group" --USES_CODELIST--> CodeList Age group
- Variable AGEGRP "Age group" --USES_CONCEPT--> Concept Demographic characteristics
- Variable REGION "Region of residence" --USES_CONCEPT--> Concept Place of residence
Now the answer is in the pack: ILOSTAT is derived from the questions
WORK, LOOK and AVAIL, it takes its values from the code list
"Labour force status (ILO)", and it covers persons aged 15 and over. Most
lines are noise, though. They come from the six hits that matched "what",
"where" or "from", and the model does not need them. Exercises 2 and 4 clean that up.
The pack can hold only what the graph holds. The file also says, in words,
how ILOSTAT is derived: employed if WORK is Yes, and so on. ddigraph
keeps that sentence as the variable's description, but this pack prints
only names and labels, so the sentence is not in it. Check what your graph
keeps, and what your pack sends, before you promise users an answer.
Retrieval decides what to send before you know how the model will reason. Module 15 turns this around: the model asks the graph for what it needs. AI readiness has the same ideas as Cypher, for a graph loaded into Neo4j, and vector search.
Exercises¶
Scenario
Your statistics office wants a help desk assistant that answers questions about its Labour Force Survey. A first test gave education levels that the survey never used. You ground the assistant in the DDI metadata, and you keep each request small.
Exercise 1 (O2). Build a grounding pack from
tests/fixtures/lfs_codebook.xml, the same survey as a DDI Codebook. Give
one line per variable, with its name and label, its question text if it has
one, its answers with their codes (USES_CATEGORY, and each category's
code), and its concept (USES_CONCEPT). Start with a line that says the
list is complete.
Expected output:
The codebook has these variables. Do not invent variables that are not listed.
- SEX: Sex of the person; asks "What is your sex?"; answers: 1 = Male, 2 = Female; concept: Demographic characteristics
- AGE: Age in completed years; asks "What was your age on your last birthday?"; concept: Demographic characteristics
- AGEGRP: Age group; answers: 1 = 15-24, 2 = 25-34, 3 = 35-44, 4 = 45-54, 5 = 55-64, 6 = 65 and over; concept: Demographic characteristics
- REGION: Region of residence; asks "In which region do you live?"; answers: 1 = Capital region, 2 = North, 3 = South, 4 = East, 5 = West; concept: Place of residence
- EDUC: Highest level of education; asks "What is the highest level of education you have completed?"; answers: 1 = Primary or less (ISCED 0-1), 2 = Lower secondary (ISCED 2), 3 = Upper secondary (ISCED 3), 4 = Post-secondary non-tertiary (ISCED 4), 5 = Tertiary (ISCED 5-8); concept: Educational attainment
- ILOSTAT: Labour force status (ILO); answers: 1 = Employed, 2 = Unemployed, 3 = Not in the labour force; concept: Labour market status
- HOURS: Usual weekly hours in the main job; asks "How many hours a week do you usually work in your main job?"; concept: Working time
Answer
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_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 linked(key, rel_type):
"""Return the nodes that `key` reaches by one `rel_type` edge."""
return [nodes[end] for start, kind, end in edges if start == key and kind == rel_type]
lines = ["The codebook has these variables. Do not invent variables that are not listed."]
for key, node in nodes.items():
if node.label != "Variable":
continue
line = f"- {plain(node.properties['name'])}: {plain(node.properties['label'])}"
if "question_text" in node.properties:
line += f'; asks "{plain(node.properties["question_text"])}"'
if answers := linked(key, "USES_CATEGORY"):
codes = [f"{c.properties['code']} = {plain(c.properties['label'])}" for c in answers]
line += f"; answers: {', '.join(codes)}"
if concepts := linked(key, "USES_CONCEPT"):
line += f"; concept: {', '.join(plain(c.properties['label']) for c in concepts)}"
lines.append(line)
print("\n".join(lines))
The codebook has these variables. Do not invent variables that are not listed.
- SEX: Sex of the person; asks "What is your sex?"; answers: 1 = Male, 2 = Female; concept: Demographic characteristics
- AGE: Age in completed years; asks "What was your age on your last birthday?"; concept: Demographic characteristics
- AGEGRP: Age group; answers: 1 = 15-24, 2 = 25-34, 3 = 35-44, 4 = 45-54, 5 = 55-64, 6 = 65 and over; concept: Demographic characteristics
- REGION: Region of residence; asks "In which region do you live?"; answers: 1 = Capital region, 2 = North, 3 = South, 4 = East, 5 = West; concept: Place of residence
- EDUC: Highest level of education; asks "What is the highest level of education you have completed?"; answers: 1 = Primary or less (ISCED 0-1), 2 = Lower secondary (ISCED 2), 3 = Upper secondary (ISCED 3), 4 = Post-secondary non-tertiary (ISCED 4), 5 = Tertiary (ISCED 5-8); concept: Educational attainment
- ILOSTAT: Labour force status (ILO); answers: 1 = Employed, 2 = Unemployed, 3 = Not in the labour force; concept: Labour market status
- HOURS: Usual weekly hours in the main job; asks "How many hours a week do you usually work in your main job?"; concept: Working time
One line per variable, built from its edges, says more than a list of
every node. Each line also holds what a data user needs to read the
data file: the code behind each answer. AGE and HOURS have no
answers line, because they are numbers, not codes. AGEGRP and
ILOSTAT have no question, because they are derived from other
variables. The pack says so by leaving the line out, not by inventing.
Exercise 2 (O3). In Section 4, six nodes were hits only because their
text holds the word "what", "where" or "from". Give relevant a set of
stop words, common words that say nothing about the topic, such as
what, which, does, where and from. Then print the pack for "What does ILOSTAT mean and
where does it come from?" again.
Expected output:
- Variable ILOSTAT "Labour force status (ILO)" --IN_UNIVERSE--> Universe Persons aged 15 and over living in private households
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem LOOK
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem WORK
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem AVAIL
- Variable ILOSTAT "Labour force status (ILO)" --USES_CODELIST--> CodeList Labour force status (ILO)
- Variable ILOSTAT "Labour force status (ILO)" --USES_CONCEPT--> Concept Labour market status
Answer
from ddigraph import iter_graph, urn
from ddigraph.ir.model import Text
STOP_WORDS = {"what", "which", "does", "mean", "where", "from", "have", "this", "that", "with"}
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
def name_of(node):
"""Name a node by its name and label, or by its URN when it has neither."""
name = plain(node.properties.get("name"))
label = plain(node.properties.get("label"))
if name and label and name != label:
return f'{name} "{label}"'
return name or label or urn.text(node.identity)
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.type, edge.end))
def relevant(question, limit=10):
"""Return the keys of the nodes whose text shares a topic word with the question."""
words = {word.lower().strip("?.,") for word in question.split() if len(word) > 3}
words -= STOP_WORDS
hits = []
for key, node in nodes.items():
haystack = " ".join(
plain(value) for value in node.properties.values() if isinstance(value, (str, Text))
).lower()
score = sum(1 for word in words if word in haystack)
if score:
hits.append((score, key))
hits.sort(key=lambda item: -item[0])
return [key for _score, key in hits[:limit]]
hits = relevant("What does ILOSTAT mean and where does it come from?")
for start, rel_type, end in edges:
if start in hits or end in hits:
print(
f"- {nodes[start].label} {name_of(nodes[start])} --{rel_type}--> "
f"{nodes[end].label} {name_of(nodes[end])}"
)
- Variable ILOSTAT "Labour force status (ILO)" --IN_UNIVERSE--> Universe Persons aged 15 and over living in private households
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem LOOK
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem WORK
- Variable ILOSTAT "Labour force status (ILO)" --REFERENCES_QUESTION--> QuestionItem AVAIL
- Variable ILOSTAT "Labour force status (ILO)" --USES_CODELIST--> CodeList Labour force status (ILO)
- Variable ILOSTAT "Labour force status (ILO)" --USES_CONCEPT--> Concept Labour market status
The only hit now is ILOSTAT, and its neighbours bring what the user
asked: the three questions it comes from, its code list, its concept
and its universe. The lines about other questions are gone, because no
hit touches them. A better score made a smaller and more useful pack.
Exercise 3 (O4). Write a function ask(client, pack, question) that sends
the request of Section 3 and returns the text of the reply. You have no key,
so test it with a stand-in client: a small class with the same
client.beta.messages.create shape, which records what it was sent and
returns a reply whose first block is a thinking block. Ask "Which
questions use the Yes or no list?", and print the model it was sent, the
last line of the system prompt, and the answer.
Expected output:
Model: claude-opus-5-5
System ends with: - QuestionItem AVAIL --USES_CODELIST--> CodeList Yes or no
Answer: WORK, LOOK and AVAIL use the Yes or no list.
Answer
from types import SimpleNamespace
def ask(client, pack, question):
"""Ask a question about the survey; return the text blocks of the reply."""
response = client.beta.messages.create(
model="claude-opus-5-5",
max_tokens=16000,
betas=["server-side-fallback-2026-07-01"],
fallbacks="default",
system=(
"Answer questions about this survey using only the structure below. "
"If the answer is not there, say so rather than guessing.\n\n" + pack
),
messages=[{"role": "user", "content": question}],
)
return "".join(block.text for block in response.content if block.type == "text")
class StandInMessages:
"""Records the request, and replies as the API can: thinking first, then text."""
def create(self, **request):
self.request = request
return SimpleNamespace(
content=[
SimpleNamespace(type="thinking", thinking=""),
SimpleNamespace(type="text", text="WORK, LOOK and AVAIL use the Yes or no list."),
]
)
client = SimpleNamespace(beta=SimpleNamespace(messages=StandInMessages()))
pack = "\n".join(
[
"- QuestionItem WORK --USES_CODELIST--> CodeList Yes or no",
"- QuestionItem LOOK --USES_CODELIST--> CodeList Yes or no",
"- QuestionItem AVAIL --USES_CODELIST--> CodeList Yes or no",
]
)
answer = ask(client, pack, "Which questions use the Yes or no list?")
sent = client.beta.messages.request
print("Model:", sent["model"])
print("System ends with:", sent["system"].splitlines()[-1])
print("Answer:", answer)
Model: claude-opus-5-5
System ends with: - QuestionItem AVAIL --USES_CODELIST--> CodeList Yes or no
Answer: WORK, LOOK and AVAIL use the Yes or no list.
response.content[0] here is the thinking block, which has no text.
Reading by block.type skips it. With a real key, pass
anthropic.Anthropic() as client, and nothing else changes.
Exercise 4 (O2). In the pack of Section 2, the sequences, the question
constructs and the IfThenElse are wiring: they say how the questionnaire
flows, not what it asks. Leave out Sequence, QuestionConstruct and
IfThenElse nodes. In their place, follow the chain from the instrument
down to its questions (HAS_CONSTRUCT, THEN and ELSE, then
REFERENCES_QUESTION) and write one ASKS line for each question. Print
the ASKS lines and the size of the new pack.
Expected output:
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem SEX
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem AGE
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem REGION
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem EDUC
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem WORK
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem LOOK
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem AVAIL
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem HOURS
11225 characters
Answer
from ddigraph import iter_graph, urn
from ddigraph.ir.model import Text
WIRING = {"Sequence", "QuestionConstruct", "IfThenElse"}
FLOW = {"HAS_CONSTRUCT", "THEN", "ELSE"}
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
def name_of(node):
"""Name a node by its name and label, or by its URN when it has neither."""
name = plain(node.properties.get("name"))
label = plain(node.properties.get("label"))
if name and label and name != label:
return f'{name} "{label}"'
return name or label or urn.text(node.identity)
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.type, edge.end))
def questions_under(key):
"""Follow the flow (HAS_CONSTRUCT, THEN, ELSE) down to the questions."""
found = []
for start, rel_type, end in edges:
if start == key and rel_type in FLOW:
found += questions_under(end)
elif start == key and rel_type == "REFERENCES_QUESTION":
found.append(end)
return found
items = {key: node for key, node in nodes.items() if node.label not in WIRING}
lines = ["The survey contains these items. Do not invent items that are not listed."]
for key, node in sorted(items.items(), key=lambda item: item[1].label):
text = node.properties.get("question_text")
lines.append(f"- {node.label}: {name_of(node)}" + (f' — asks "{plain(text)}"' if text else ""))
lines.append("")
lines.append("Links between them:")
for start, rel_type, end in edges:
if start in items and end in items:
lines.append(
f"- {nodes[start].label} {name_of(nodes[start])} --{rel_type}--> "
f"{nodes[end].label} {name_of(nodes[end])}"
)
for key, node in items.items():
if node.label == "Instrument":
for question in questions_under(key):
lines.append(
f"- Instrument {name_of(node)} --ASKS--> QuestionItem {name_of(nodes[question])}"
)
pack = "\n".join(lines)
for line in lines:
if "--ASKS-->" in line:
print(line)
print(len(pack), "characters")
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem SEX
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem AGE
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem REGION
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem EDUC
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem WORK
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem LOOK
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem AVAIL
- Instrument LFS questionnaire "Labour Force Survey questionnaire, 2025" --ASKS--> QuestionItem HOURS
11225 characters
The pack keeps every fact a reader asks about, and it is smaller:
11,225 characters instead of 12,264. Every line costs money on every
request, so a line that nobody asks about never earns its cost. ASKS
is a name made up for the pack, not a relationship type of the graph:
the model needs a clear word, not the schema.
One fact is lost, though: the routing. HOURS is asked only of people
who worked last week, and LOOK and AVAIL only of people who did not.
The universe of the variable HOURS, "Employed persons aged 15 and
over", still says part of it. If your users ask who answers which
question, keep the IfThenElse and its label in the pack.
Quiz¶
Question 1 (O1): Why is a plausible but ungrounded answer about a survey worse than no answer?
A. Because models are always wrong about surveys.
B. Because it reads as correct, so nobody checks it, and it is not what your survey asked.
C. Because it costs more tokens than a grounded answer.
D. Because the model refuses questions it cannot ground.
Answer
B. A model that has read many surveys writes answer options that look right. That is the danger: a wrong answer that looks wrong gets caught, a plausible one does not. A is too strong: the model is often close, which is exactly why its errors slip through.
Question 2 (O2): Your pack lists every node of a survey, but no edges. Which question can it not answer?
A. "Is there a question about education?"
B. "Which code list does the education question use?"
C. "What is the questionnaire called?"
D. "Is there a category called Unemployed?"
Answer
B. Which code list a question uses is a link between two nodes,
USES_CODELIST. A list of nodes shows that the question and the
code list exist, but not that one uses the other. The other three
ask about a single node, so the list alone answers them.
Question 3 (O3): Keyword retrieval returns the variable ILOSTAT for the question \"Where does ILOSTAT come from?\". Why add its neighbours before you send it?
A. To make the pack longer, so the model takes it seriously.
B. Because the questions it is derived from are one edge away, and no word of the question names them.
C. Because the API refuses a pack with one node.
D. Because neighbours are always more relevant than the hit.
Answer
B. The answer, the questions WORK, LOOK and AVAIL, is in
the nodes one edge from the variable, and no word of the question
matches them. One step along the edges brings them in. D overstates
it: neighbours complete a hit, they do not replace it.
Question 4 (O4): Your code prints response.content[0].text. It worked yesterday and fails today with an AttributeError. What is the likely cause?
A. The API key ran out.
B. The first block of today's reply is not a text block, such as a thinking block.
C. The pack was too long.
D. content is a string, and strings have no text.
Answer
B. response.content is a list of blocks of several types, and
the first one is not always text. Loop over the blocks and keep those
whose type is "text". D is the tempting picture, but content is
a list, never a string.
Question 5 (O4): Why does the system prompt say \"If the answer is not there, say so rather than guessing\"?
A. Without it, the API returns an error for questions the pack does not cover.
B. Without it, a model often answers anyway from what it knows, which is the guess you set out to prevent.
C. It makes the reply shorter.
D. It turns on the fallback model.
Answer
B. The pack limits what the model should use, and this sentence
says what to do at that limit. A is wrong: the API never checks your
pack. D mixes it up with fallbacks="default", which is about a
model that declines a request.
Check yourself¶
- I can explain why a model's plausible answer about a survey is a risk, and what a grounding pack changes. (O1)
- I can build a grounding pack from
iter_graph, withTextvalues unwrapped,urn.textas a fallback name, and the edges included. (O2) - I can retrieve only the nodes a question needs by keyword, and add their neighbours one edge away. (O3)
- I can send a pack to a model in the system prompt, say what to do when the answer is absent, and read
response.contentby block type. (O4)