About this notebook
Companion to Module 5: RAG and knowledge. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
In Notebook 5a the program decided when to retrieve and what to search for: one search, with the user’s question as the query, before the model saw anything. Here the agent decides. Retrieval becomes a tool, and the model can search, read the result, and search again with a better query. That handles questions a single search cannot, and it brings new problems: long tool outputs, repeated calls, access the agent should not have, and actions a person should approve first. This notebook covers:
- retrieval as a tool: the model writes the query;
- multi-hop questions: the second search depends on the first result;
- files as a knowledge source: list, read and grep instead of an index;
- tool callbacks: one place to log, cache and block tool calls;
- compressing long results, and what compression can lose;
- a human approves the risky step before an email is sent.
Which model answers here?
With no
MODELset, the offline policy model drives the agent with rules written for this notebook. It searches with the user’s question minus its question words, and it answers by copying the passage line that covers most of the question, with its source. The multi-step behaviour in Sections 2 and 3 is scripted in those rules: it shows what the loop, the tools and the callbacks do, not that a model would choose those steps. A real model writes its own queries, may search more or less often, and phrases its answers. The callbacks, the compression and the approval step are ordinary code and behave the same with any model.
from agentlab.nbsetup import setup
nb = setup("05b_agentic_rag", packs=["rag"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. Retrieval as a tool
The retriever from Notebook 5a (structure-aware chunks, BM25 and hashed vectors fused by reciprocal rank fusion) becomes a function the model can call. The tool returns the top three chunks, numbered and labelled with their source document.
from agentlab import Agent
from agentlab.display import show_trajectory
from agentlab.rag import Retriever, chunk_corpus, load_handbook, make_retrieval_tool
docs = load_handbook()
retriever = Retriever(chunk_corpus(docs, "structure", max_chars=600))
search_handbook = make_retrieval_tool(retriever, name="search_handbook", k=3)
print(search_handbook.name, "-", search_handbook.description.splitlines()[0])
HANDBOOK_INSTRUCTIONS = (
"You answer employees' questions about the Orrin Valley Instruments handbook. "
"Search the handbook before answering, answer only from what the search returns, "
"and cite the source id of every passage you use. If the handbook does not answer "
"the question, say so.")
agent = Agent(model=llm, tools=[search_handbook], instructions=HANDBOOK_INSTRUCTIONS,
max_steps=6)
result = await agent.run("What is the weekly on-call stipend?")
show_trajectory(result)search_handbook - Search the company handbook and return the most relevant passages with their source ids.
[user] What is the weekly on-call stipend?
[agent -> search_handbook] {"query": "the weekly on-call stipend"}
[search_handbook ok] [1] source: eng-on-call On-call rotation Each product team runs a weekly on-call rotation. Sh...
[agent] On-call engineers receive a stipend of USD 400 per week. [source: eng-on-call]
--- status: complete, steps: 2
The loop is the one from Module 4: the model asked for a search, the tool ran, the result went back, and the model answered. The difference from Notebook 5a is who chose the query. The offline model used the question minus “what is”. A real model rewrites it (“on-call stipend amount per week”), and if the first result looks wrong it can search again. That freedom is the point of agentic retrieval, and it costs a model call per search.
2. A question that needs two searches
“What is the hotel cap in Oslo in US dollars?” needs two facts from two documents: the cap, which is in Norwegian kroner, and the exchange rate the company uses. A single search with the whole question finds the first, and does it find the second?
question = "What is the nightly hotel cap in Oslo in US dollars?"
hits = retriever.search(question, k=3)
print("one search returns:", [h.chunk.doc_id for h in hits])
print("exchange rate among them:", any("10.50" in h.chunk.text for h in hits))one search returns: ['travel-lodging', 'travel-lodging', 'travel-currency'] exchange rate among them: False
The search reached the currency document, through the words “US dollars” in its introduction, but not the chunk with the table of rates. The row that matters, “Norwegian krone (NOK) | 10.50”, shares no word with the question. You only know to search for it once you have seen that the cap is in NOK. That is a multi-hop question: each search depends on what the previous one returned. Give the agent a calculator too:
from agentlab.tools import calculator_tool
agent = Agent(model=llm, tools=[search_handbook, calculator_tool],
instructions=HANDBOOK_INSTRUCTIONS
+ " Convert amounts with the handbook's fixed exchange rates.",
max_steps=8)
result = await agent.run(question)
show_trajectory(result)[user] What is the nightly hotel cap in Oslo in US dollars?
[agent -> search_handbook] {"query": "the nightly hotel cap in Oslo in US dollars"}
[search_handbook ok] [1] source: travel-lodging Lodging caps The company pays for lodging up to a nightly cap that...
[agent -> search_handbook] {"query": "exchange rate for the Norwegian krone (NOK) per US dollar"}
[search_handbook ok] [1] source: travel-currency Currency and exchange rates for expenses Expense reports are alwa...
[agent -> calculator] {"expression": "1800 / 10.50"}
[calculator ok] 171.42857142857142
[agent] NOK 1,800 is about USD 171.43, using the handbook's fixed rate of 10.50 NOK per US dollar [so...
--- status: complete, steps: 4
Three tool calls, each chosen after seeing the last result. The offline rule follows this order by construction. A real model usually finds it too, but it has a tempting shortcut: it knows roughly what a krone is worth and may convert from memory, at a rate that is not the one Finance uses. The instruction to use the handbook’s fixed rates closes that shortcut. Check for it whenever an answer has a number the tools did not return.
3. Files: search by structure instead of by index
An index is one way to find text. The other is the way a person uses a shared drive:
look at the folders, open the file whose name fits, search for a word. Coding agents
work mostly this way, with ls, grep and file reads, because code changes faster than
any index could be rebuilt. FileTools gives the agent three tools over a folder. The
handbook is copied into the notebook’s work folder first, so the agent works on a copy.
import shutil
from agentlab.rag import FileTools, handbook_dir
workspace = nb.workdir / "handbook"
shutil.rmtree(workspace, ignore_errors=True) # start from a clean copy on every run
shutil.copytree(handbook_dir(), workspace)
files = FileTools(workspace)
print(files.list_files())
print()
print(files.search_files("Ledgerline"))Folder: . engineering/ expenses/ office/ people/ products/ security/ support/ travel/ expenses/expenses-corporate-card.md:7: Card transactions appear in Ledgerline automatically, but you still need to attach expenses/expenses-home-office.md:7: Buy the items yourself and claim the reimbursement in Ledgerline with the receipts. Items expenses/expenses-submitting.md:3: File expenses in Ledgerline, the expense app, within 30 days of the purchase. Reports expenses/expenses-submitting.md:9: Your manager approves reports in Ledgerline. Reports approved by the 20th of the month are travel/travel-currency.md:16: To convert an amount to dollars, divide it by the rate: NOK 1,050 is USD 100. Ledgerline
read_file numbers its lines, so the model can ask for a range (start_line,
end_line) instead of a whole long file. Every path is resolved inside the folder. A
path that tries to leave it is refused, which matters as soon as the model, or text it
has read, chooses the path:
try:
files.read_file("../../../../pyproject.toml")
except PermissionError as exc:
print("PermissionError:", exc)PermissionError: path '../../../../pyproject.toml' is outside the workspace
Now the agent browses. It lists a folder, picks a file by name, reads it, and answers from the line that matches:
browser = Agent(model=llm, tools=files.tools(), max_steps=6,
instructions="Answer from the files in the handbook folder. "
"Name the file you used.")
result = await browser.run("In the products folder, what does error code E-312 mean?")
show_trajectory(result)[user] In the products folder, what does error code E-312 mean?
[agent -> list_files] {"path": "products"}
[list_files ok] Folder: products prod-calibration-service.md prod-error-codes.md prod-tern-rg1.md prod-tern-w...
[agent -> read_file] {"path": "products/prod-error-codes.md"}
[read_file ok] 1 | # Device error codes 2 | 3 | Tern devices report problems to Skyline as error codes. The ...
[agent] The error codes are in products/prod-error-codes.md. E-312 means: no network connection for 2...
--- status: complete, steps: 3
| an index (5a, Section 1 here) | browsing files (this section) | |
|---|---|---|
| finds | text similar to the query | what the folder names and exact words point to |
| freshness | stale until re-indexed | always current |
| cost per question | one search | several calls, each one a model step |
| good for | many documents, vague questions | structured collections, exact names and codes |
The two combine well. An agent can search an index to find the right document, then read that document in full or grep it for an exact term.
4. Tool callbacks: one place to watch, cache and block
Some concerns apply to every tool: logging, caching, permissions, size limits. Putting
them inside each tool repeats code and makes it easy to forget one. Agent runs
callbacks around every tool call instead:
the model asks for a tool call
|
v
before_tool callbacks ---- one returns a ToolResult? --> skip the tool, use that result
| (all return None)
v
the tool runs (an exception becomes an error result)
|
v
after_tool callbacks ----- one returns a ToolResult? --> it replaces the result
|
v
the result goes back to the modelThree small callbacks: a log line for every call, a cache for repeated identical calls,
and a guard that keeps this agent out of the security folder.
import json
from agentlab import ToolResult
def log_call(context, tool_call):
print(f" [log] step {context.current_step + 1}: {tool_call.name}"
f"({json.dumps(tool_call.arguments)})")
cache: dict[str, list] = {}
def cache_key(tool_call) -> str:
return tool_call.name + json.dumps(tool_call.arguments, sort_keys=True)
def cached_result(context, tool_call):
hit = cache.get(cache_key(tool_call))
if hit is not None:
print(" [cache] hit, the tool does not run")
return ToolResult(tool_call_id=tool_call.tool_call_id, name=tool_call.name,
status="success", content=hit)
return None
def store_result(context, tool_call, result):
if result.status == "success":
cache[cache_key(tool_call)] = list(result.content)
return None # keep the result as it is
BLOCKED_FOLDERS = ("security",)
def folder_guard(context, tool_call):
path = str(tool_call.arguments.get("path", "")).strip("./")
if path.split("/")[0] in BLOCKED_FOLDERS:
return ToolResult(tool_call_id=tool_call.tool_call_id, name=tool_call.name,
status="error",
content=[f"Access to {path!r} is not allowed for this assistant. "
"Ask the security team for security documents."])
return None
browser = Agent(model=llm, tools=files.tools(), max_steps=6,
instructions="Answer from the files in the handbook folder. "
"Name the file you used.",
before_tool_callbacks=[log_call, folder_guard, cached_result],
after_tool_callbacks=[store_result])
for question in ["In the products folder, what does error code E-312 mean?",
"In the products folder, what does error code E-312 mean?",
"In the security folder, how long must a password be?"]:
result = await browser.run(question)
print(f"{question}\n -> {result.output}\n") [log] step 1: list_files({"path": "products"})
[log] step 2: read_file({"path": "products/prod-error-codes.md"})
In the products folder, what does error code E-312 mean?
-> The error codes are in products/prod-error-codes.md. E-312 means: no network connection for 24 hours; check the SIM or Wi-Fi settings.
[log] step 1: list_files({"path": "products"})
[cache] hit, the tool does not run
[log] step 2: read_file({"path": "products/prod-error-codes.md"})
[cache] hit, the tool does not run
In the products folder, what does error code E-312 mean?
-> The error codes are in products/prod-error-codes.md. E-312 means: no network connection for 24 hours; check the SIM or Wi-Fi settings.
[log] step 1: list_files({"path": "security"})
In the security folder, how long must a password be?
-> I could not complete this: Access to 'security' is not allowed for this assistant. Ask the security team for security documents.
The second run asked for the same two calls, and both came from the cache. The guard answered the third question’s first call with an error result. The model saw that error as an observation and reported it. It did not crash and it did not get around the rule.
Order matters: log_call runs first, so even blocked and cached calls are logged, and
the guard runs before the cache, so a forbidden call cannot be answered from an earlier
allowed one. A cache like this is safe only for tools whose answer does not change. A
cached get_weather or get_exchange_rate would serve stale data with full confidence.
5. Compressing long results
Web pages are long, and most of a page is irrelevant to the question that found it.
FixtureSearch searches six synthetic pages stored in fixtures/search/, so this
notebook runs offline. agentlab.search.TavilySearch has the same interface for a live
search with an API key. Three results cost this much:
from agentlab.llm.pricing import estimate_tokens
from agentlab.search import FixtureSearch, format_results, make_search_tool
engine = FixtureSearch()
query = "What does an adult single ticket on the Airport Express cost"
raw = format_results(engine.search(query, max_results=3))
print(f"{len(raw):,} characters, about {estimate_tokens(raw):,} tokens")
print([r["title"] for r in engine.search(query, max_results=3)])5,072 characters, about 1,268 tokens ['Oslo Airport to the city centre: every option compared', 'The Norwegian krone: a short guide for visitors', 'Packing for a winter business trip to Norway']
Every later step of the run would resend those tokens. An after_tool callback can
shrink the result before the model ever sees it. This one is adapted from the book’s
search compressor. It cuts the result into pieces of whole sentences, ranks the pieces
against the query the model searched for (BM25 and hashed vectors, fused as in Notebook
5a), and keeps the best three in their original order:
from agentlab.rag import make_compression_callback
compress = make_compression_callback(tool_names=("web_search",), max_chars=2000, keep=3)
web_agent = Agent(model=llm, tools=[make_search_tool(engine, name="web_search")],
instructions="Search the web and answer with the source URL.",
after_tool_callbacks=[compress], max_steps=4)
question = "What does an adult single ticket on the Airport Express cost?"
result = await web_agent.run(question)
show_trajectory(result)[user] What does an adult single ticket on the Airport Express cost?
[agent -> web_search] {"query": "What does an adult single ticket on the Airport Express cost"}
[web_search ok] [compressed from 5,072 to 1,043 characters for the query 'What does an adult single ticket on...
[agent] Since the fare change in January the adult single ticket costs NOK 240 when bought in the app...
--- status: complete, steps: 2
Five thousand characters became one thousand, and the answer survived. Compression is lossy, though, and it ranks pieces by the model’s query, so a vaguer query can rank the key sentence out. Nothing tells the model that this happened:
from agentlab.rag import compress_text
for q in ["What does an adult single ticket on the Airport Express cost",
"the Airport Express train from Oslo airport cost"]:
kept = compress_text(format_results(engine.search(q, max_results=3)), q, keep=3)
print(f"{q!r:66} keeps the fare: {'NOK 240' in kept}")'What does an adult single ticket on the Airport Express cost' keeps the fare: True 'the Airport Express train from Oslo airport cost' keeps the fare: False
In the second query “cost” and “train” do not match “costs” and “Trains” in the fare sentence, so the lexical ranking misses it, and the piece is dropped. Three habits limit the damage. Compress only when a result is really long. Rank against the user’s question as well as the tool query. And say in the result that it was compressed, as the note at the top of the compressed result does, so a model can search again for the full text.
Notice one more thing in the answer: the web page says NOK 240 “since the fare change in January”. The handbook says something else:
lines = (workspace / "travel" / "travel-ground-transport.md").read_text().splitlines()
first = next(i for i, line in enumerate(lines) if "Airport Express" in line)
print("travel-ground-transport.md:", " ".join(x.strip() for x in lines[first:first + 2]))travel-ground-transport.md: - Oslo: the Airport Express train runs from Oslo Airport to Oslo Central Station every 10 minutes and costs NOK 230 each way. The Oslo office is a short walk from the station.
Two sources, two numbers. The web page is probably newer, while the handbook is the company’s own rule for expense estimates. Neither is simply right. A good agent reports the conflict and both sources instead of silently picking one, and its instructions can say which source wins for which kind of question. The offline model does not compare sources at all. A real model might, but only if the instructions ask it to.
6. A human approves the risky step
Searching and reading are safe to retry. Sending an email is not: once sent, it cannot be
taken back. A tool marked requires_confirmation=True makes the agent stop before the
call runs and return the call for a person to approve, edit or reject. The “email” here
is a line appended to a file in the work folder.
from agentlab import tool
outbox = nb.workdir / "outbox.jsonl"
outbox.unlink(missing_ok=True)
@tool(requires_confirmation=True, confirmation_message="Send an email to {arguments[to]}?")
def send_email(to: str, subject: str, body: str) -> str:
"""Send an email from the assistant's account.
Args:
to: The recipient's email address.
subject: The subject line.
body: The plain-text body.
"""
with outbox.open("a", encoding="utf-8") as f:
f.write(json.dumps({"to": to, "subject": subject, "body": body}) + "\n")
return f"Email sent to {to} with the subject {subject!r}."
assistant = Agent(model=llm, tools=[search_handbook, send_email],
instructions=HANDBOOK_INSTRUCTIONS, max_steps=6)
result = await assistant.run(
"Look up the meal per diem for Oslo and email it to ada@example.com")
def show_email(email: dict) -> None:
print(f" to: {email['to']}\n subject: {email['subject']}")
print("\n".join(" | " + line for line in email["body"].splitlines()))
print("status:", result.status)
for pending in result.pending_tool_calls:
print(pending.confirmation_message)
show_email(pending.tool_call.arguments)status: pending_confirmation Send an email to ada@example.com? to: ada@example.com subject: The meal per diem for Oslo | Hello, | | From the handbook: Meal per diem: city Oslo; per diem NOK 750 [source: travel-per-diem] | | Best regards
The run stopped with status pending_confirmation. The search ran, but the email did
not, and nothing has been written to the outbox. The person reviewing can approve the
call as it is, approve it with edited arguments, or reject it with a reason. Here they
approve and add a line to the body:
from agentlab import ToolConfirmation
pending = result.pending_tool_calls[0]
edited = dict(pending.tool_call.arguments)
edited["body"] = edited["body"].replace(
"Best regards", "The per diem is paid per night away from home.\n\nBest regards")
result = await assistant.run(context=result.context, confirmations=[
ToolConfirmation(tool_call_id=pending.tool_call.tool_call_id, approved=True,
modified_arguments=edited)])
print("status:", result.status, "|", result.output)
print("in the outbox:")
for line in outbox.read_text(encoding="utf-8").splitlines():
show_email(json.loads(line))status: complete | Done: Email sent to ada@example.com with the subject 'The meal per diem for Oslo'. in the outbox: to: ada@example.com subject: The meal per diem for Oslo | Hello, | | From the handbook: Meal per diem: city Oslo; per diem NOK 750 [source: travel-per-diem] | | The per diem is paid per night away from home. | | Best regards
And a rejection. The reason goes back to the model as the tool’s error result, so the model can explain what happened or try something else:
result = await assistant.run(
"Look up the meal per diem for Oslo and email it to all-staff@example.com")
pending = result.pending_tool_calls[0]
result = await assistant.run(context=result.context, confirmations=[
ToolConfirmation(tool_call_id=pending.tool_call.tool_call_id, approved=False,
reason="Do not email the whole company; send it to me instead.")])
show_trajectory(result)
print("emails in the outbox:", len(outbox.read_text(encoding="utf-8").splitlines()))[user] Look up the meal per diem for Oslo and email it to all-staff@example.com
[agent -> search_handbook] {"query": "the meal per diem for Oslo"}
[search_handbook ok] [1] source: travel-per-diem Meal per diem Instead of collecting meal receipts, employees on a...
[agent -> send_email] {"to": "all-staff@example.com", "subject": "The meal per diem for Oslo", "body": "Hello,\n\nF...
[send_email ERROR] The user rejected this call. Reason: Do not email the whole company; send it to me instead.
[agent] I did not send the email. The user rejected this call. Reason: Do not email the whole company...
--- status: complete, steps: 3
emails in the outbox: 1
Which tools deserve a confirmation? The ones whose effects are hard to undo, visible to
other people, or expensive: sending, paying, deleting, publishing. Asking for everything
trains people to click “approve” without reading. The paused state is just data in
result.context, so it can wait for minutes or days. Notebook 6b stores it in a session
file and resumes it after a restart.
Try this
- Give the cache a time-to-live of five steps, keyed by step number. Which tools in this course should never be cached?
- Change
folder_guardinto an allow-list (ALLOWED = ("products", "travel")). Which is safer when someone adds a new folder to the handbook?- Run Section 5 with
max_chars=800, keep=1. When does the fare disappear? Then change the callback to rank against the user’s last message as well as the tool query.- With a live model, ask Section 2’s question without the sentence about fixed exchange rates. Does the model still search for the rate, or does it convert from memory?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 25 (fake: 25) | ≈ 12,936 | ≈ 522 | ≈ USD 0.0150 (reference price) |