Module 5 · Data agents & production
Tool-using agents over your indexes
6 min read
Query engines answer questions; agents accomplish tasks. An agent receives a request, chooses on its own which tools to use — an index, a business function, an API —, observes the results, and starts again until it can answer. LlamaIndex builds its agents on the workflows of the previous lesson. This lesson gives Lumen an agent able to combine the documentation, a business rule computed by code and the product graph.
Why an agent?
"The LAMP-3 lamp, delivered on March 1, 2024 — is it still under warranty?" No index contains the answer: you need to know the product's warranty length, then compute a date and compare it to today. An LLM can get this computation wrong; a Python function, never. The agent knows when to call the function; the function guarantees the result.
| Need | Tool of Lumen's agent |
|---|---|
| Documentary information | knowledge_base: the query engine of lesson 4.1 |
| Exact business computation | check_warranty(sku, purchase_date): a Python function |
| Product relationships | product_graph(sku): a read from the graph of lesson 3.3 |
Tools of two kinds
tools = [
QueryEngineTool.from_defaults(
kb.tools[0].query_engine, name="knowledge_base",
description="Recherche dans la documentation Nimbus (produits, retours, garantie, "
"livraison, FAQ). Entrée : une question complète en français.",
),
FunctionTool.from_defaults(check_warranty),
FunctionTool.from_defaults(product_graph),
]
A QueryEngineTool exposes a whole engine as a tool. A FunctionTool exposes a Python function: its name, its docstring and its type annotations become the definition sent to the model.
def check_warranty(sku: str, purchase_date: str) -> str:
"""Indique si un produit est encore sous garantie.
Args:
sku: référence du produit, par exemple LAMP-3.
purchase_date: date de livraison au format AAAA-MM-JJ.
"""
product = products.get(sku.upper())
if product is None:
return f"Référence inconnue : {sku}. Références valides : {', '.join(products)}."
start = date.fromisoformat(purchase_date)
end = start.replace(year=start.year + product["warranty_years"])
status = "sous garantie" if TODAY <= end else "hors garantie"
years = product["warranty_years"]
return f"{product['name']} ({sku}) : garantie {years} ans, jusqu'au {end.isoformat()} — {status}."
Three design rules, common to all agent tools:
- The docstring is the instruction manual for the model: what the tool does, the format of each argument, with an example.
- An error is a useful message, not an exception: an unknown reference returns the list of valid references, so the model can fix its call.
- The result is compact and explicit: a sentence containing the conclusion ("sous garantie"), not raw data to interpret.
The FunctionAgent
from llama_index.core.agent.workflow import FunctionAgent
agent = FunctionAgent(
name="nimbus_support",
tools=tools,
llm=models.main_llm(),
system_prompt=SYSTEM_PROMPT,
timeout=60,
)
The FunctionAgent uses the model's native tool calling (function calling): it's the recommended choice with Claude. The system prompt says when to use which tool — notably "never compute a date yourself":
- Pour toute question sur un produit, une règle ou une procédure, consulte la base (knowledge_base).
- Pour savoir si un produit est encore sous garantie, utilise check_warranty :
ne calcule jamais une date toi-même.
- Pour les fournisseurs et les compatibilités, utilise product_graph.
- Si l'information n'est pas disponible, dis-le clairement.
For models without native tool calling, LlamaIndex offers the ReActAgent, which makes the model reason in text (thought, action, observation); it's less reliable and of no interest with Claude.
Running and observing
The agent is a workflow: run() returns a handler, and its events show each decision.
handler = agent.run(user_msg="La lampe LAMP-3 livrée le 2024-03-01 est-elle encore sous garantie ?")
async for event in handler.stream_events():
if isinstance(event, ToolCall):
print(f"outil : {event.tool_name}({event.tool_kwargs})")
elif isinstance(event, ToolCallResult):
print(f"résultat : {event.tool_output.content}")
result = await handler
outil : check_warranty({'sku': 'LAMP-3', 'purchase_date': '2024-03-01'})
résultat : Lampe de bureau Halo (LAMP-3) : garantie 3 ans, jusqu'au 2027-03-01 — sous garantie.
Lumen's tests check the agent's trajectory (calls == ["check_warranty"]), not just its answer: an agent that gave the right date by computing it itself would pass a test on the answer… and fail one day on an edge case.
Other events are available: AgentStream for tokens as they're generated, AgentOutput for each model response. The final result (AgentOutput) also contains the list of tool calls made, which Lumen's service returns as "sources".
Agent memory and state
Without precautions, each run() starts from scratch. For an agent to remember a conversation, pass it a context, reused from one call to the next:
from llama_index.core.workflow import Context
ctx = Context(agent)
await agent.run(user_msg="Quelle est la garantie de la chaise CHAIR-7 ?", ctx=ctx)
await agent.run(user_msg="Et qui la fabrique ?", ctx=ctx) # "la" = the chair, thanks to the context
The context keeps the history (and any custom state). It serializes to be stored between two HTTP requests.
Several agents
For distinct domains, LlamaIndex offers the AgentWorkflow: several specialized agents, each with its tools, handing off to one another depending on the request — a "documentation" agent, a "warranty and after-sales" agent, an "orders" agent. The principle is that of networked multi-agent architectures (see the dedicated course). Start with a single well-equipped agent: most needs are satisfied by it.
Safeguards
- Bound execution:
timeouton the agent,max_iterationswhen callingrun(), and tools that don't block. - Read first: Lumen's tools only read and compute. A tool that acts (create a return, send an email) requires human validation (
wait_for_event) and an idempotent implementation. - Tool data are not instructions: an indexed document containing "ignore your instructions" must remain data. Keep tools read-only and permissions minimal.
Key takeaways
- An agent chooses its tools: indexes (
QueryEngineTool) and business functions (FunctionTool) combine.- Computations and rules are code; the model decides when to use them.
- Clear docstring, useful errors, compact results: an agent's quality comes from its tools.
FunctionAgent(native tool calling) with Claude; observe the trajectory and test it.- A reused
Contextgives memory; bound execution, stay read-only, validate any action.
Practice
- Run
examples/05_agent.pyand watch the agent's trajectory. - Add an
estimate_delivery(postcode, product_category)tool that applies the shipping policy's lead times, and ask a question that requires it. - Ask two successive questions with the same
Context, then without: compare the answers to "Et qui la fabrique ?".