Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 6
Module 3 · Vector search and LLM applications · Chapter 6 of 24
Building LLM applications: chains, tools and memory
Builds on Generative AI and how LLMs work, Working with model APIs, Prompt engineering and Embeddings and vector databases. Next up: Retrieval-augmented generation.
Part 1 · Templates and chains
One call is rarely the whole job
Most useful features need several model calls, not one. A support tool reads a customer message, pulls out the facts, checks that it has what it needs, and only then writes a reply.
A prompt template is a string with slots that your code fills at run time: the customer's message, a product name, a limit on length. It keeps the fixed wording of an instruction in one place and the changing data in another. In Python an f-string is enough. Nothing about a template needs a library.
A chain is a fixed sequence of steps in which the output of one model call becomes the input of the next. The Anthropic article on building effective agents calls this prompt chaining and describes the key point: your code can run a programmatic check between steps, so a bad intermediate result is caught before it spoils the rest. The path through the code is decided in advance by you, not by the model, which is what separates a chain from an agent.
Why split a task at all? Each call does one small job and is easier to test. You can give each call its own instruction, and even its own model, small and cheap for extraction and larger for writing. And the places where the model can go wrong are visible, because each step's output is a value you can print, validate and log.
Extract, check, then write
The example has three steps. First the model extracts three fields from a customer message into a Ticket: the order id, the problem and what the customer wants. The schema marks the order id as optional, so the model returns null when the message does not contain one. Second, plain code checks the result. If there is no order id, the chain stops and asks for it, with no more model calls. Third, only when the check passes, the model drafts a short reply from the validated fields.
Structured output, from the model APIs chapter, makes the first step reliable: parse takes a Pydantic class and returns an instance, and it raises an error if the reply cannot be read as that class. The template for the draft is an f-string that inserts the fields. Notice that the draft step never sees the raw message, only the validated fields. That limits what a strange message can do to the second call.
import textwrap from pydantic import BaseModel from llm import client, MODEL, chat class Ticket(BaseModel): order_id: str | None problem: str wants: str MESSAGES = [ "Hi, order AB-1042 reached me with a dent on the steel flask. " "Please send a replacement. - Meera", "My pressure cooker lid does not close properly. I want my " "money back. - Ravi", ] def extract(text): r = client.chat.completions.parse( model=MODEL, reasoning_effort="none", response_format=Ticket, messages=[{"role": "system", "content": "Extract the fields. Use null if the order id is " "not in the message."}, {"role": "user", "content": text}]) return r.choices[0].message.parsed
def draft(t): msg, _ = chat([{"role": "user", "content": f"Write a two-sentence polite reply. Order {t.order_id}. " f"Problem: {t.problem}. Customer wants: {t.wants}."}]) return msg.content if __name__ == "__main__": for text in MESSAGES: t = extract(text) for field, value in t: print(f"{field}: {value}") if t.order_id is None: print("reply: Could you share your order number?\n") else: print(textwrap.fill("reply: " + draft(t), 66), "\n")
Running the chain
Two made-up messages go through the chain. The first contains an order number and the second does not.
order_id: AB-1042 problem: dent on the steel flask wants: replacement reply: Thank you for bringing the issue with your steel flask to our attention regarding order AB-1042. We are very sorry for the dent and would be happy to ship out a replacement for you immediately. order_id: None problem: pressure cooker lid does not close properly wants: refund reply: Could you share your order number?
Output from one run; yours will differ. Wording of the reply varies between runs.
The first message passes the check and gets a drafted reply. The second fails it, because order_id came back as None, and the chain returns a fixed question instead of drafting anything. That gate cost nothing and cannot be talked out of its decision, which is the main reason to put checks in code and not in a prompt. Notice also that the extracted value for wants is free text: in this run the second message gave refund, in another run it gave other wording. If a later step depends on a fixed set of values, make the schema a Literal of allowed values, as the routing lesson does.
Testing follows from the structure. A test for the gate needs no model: call the gate function with a Ticket that has no order id and assert on the result. A test for extraction runs the model and asserts on fields it should find, such as the order id, never on exact wording. Chains are easier to test than a single large prompt for exactly this reason.
What is the difference between a chain and an agent?
- In a chain the sequence of steps is fixed by your code. In an agent the model decides which step comes next and when to stop.
Why does the draft step take the validated Ticket and not the raw message?
- The step only sees fields that passed validation, so odd or hostile text in the message has less chance of steering the second call.
- It also makes the step easy to test with hand-made tickets.
Predict: if a message has no order number, how many model calls does this chain make, and what does the customer receive?
Part 2 · Tool calling
The model asks, your code acts
A language model produces text. It cannot look up an order, read a file or send an email. Tool calling, also called function calling, is the mechanism that lets it ask for those things. You describe your functions to the model. When it decides one is needed, it replies with a structured request instead of an answer. Your code runs the function and sends the result back. Only then does the model write its answer. The model never executes anything.
The description of a tool has three parts: a name, a plain-language description that tells the model when to use it, and a JSON Schema for the arguments. In Chat Completions a tool is an object of type function, and you pass the list in the tools parameter. Writing the argument schema from a Pydantic class, as the code below does, keeps the schema and the validator in one place.
The OpenAI function-calling guide describes the flow in five steps: send a request with tool definitions, receive a function call, run it in your code, send a second request with the output, then receive the final answer or more calls. Everything the model knows about the result arrives through that second request. It has no other connection to your program.
Two details trip people up. First, the arguments field of a tool call is a JSON-encoded string, not an object, so your code must parse it, and the model can produce text that is not valid or does not match the schema. Second, in Chat Completions the result goes back as a message with the role tool, carrying the tool_call_id of the call it answers. The assistant message that contained the calls must also stay in the list, because the tool message refers to it.
A full round trip
The script defines one tool, get_order_status, over a small dictionary of made-up orders. It validates the arguments with Pydantic before running anything. It sends a question that mentions two orders, so the model may call the tool twice in a single turn. The code answers every call and then asks again.
import textwrap from types import SimpleNamespace as NS from pydantic import BaseModel, ValidationError from llm import client, MODEL ORDERS = {"AB-1042": "delivered on 12 Nov", "AB-2210": "out for delivery"} class StatusArgs(BaseModel): order_id: str TOOLS = [{"type": "function", "function": { "name": "get_order_status", "description": "Look up the delivery status of one order.", "parameters": StatusArgs.model_json_schema()}}] def run_tool(call): try: args = StatusArgs.model_validate_json(call.function.arguments) except ValidationError as e: return "error: " + e.errors()[0]["msg"] return ORDERS.get(args.order_id, "unknown order")
def ask(messages): r = client.chat.completions.create( model=MODEL, messages=messages, tools=TOOLS, reasoning_effort="none") return r.choices[0] messages = [{"role": "user", "content": "Where are my orders AB-1042 and AB-2210?"}] choice = ask(messages) print(choice.finish_reason) for c in choice.message.tool_calls: print(c.id, c.function.name, repr(c.function.arguments)) messages.append(choice.message) for c in choice.message.tool_calls: messages.append({"role": "tool", "tool_call_id": c.id, "content": run_tool(c)}) final = ask(messages) print(final.finish_reason) print(textwrap.fill(final.message.content, 66)) bad = NS(function=NS(arguments='{"id": 5}')) print(run_tool(bad))
tool_calls call_xjlzl2ed get_order_status '{"order_id":"AB-1042"}' call_1pyggpwf get_order_status '{"order_id":"AB-2210"}' stop Order AB-1042 was delivered on November 12th, and order AB-2210 is currently out for delivery. error: Field required
Output from one run; call ids and wording differ every run.
The first reply has finish_reason set to tool_calls and holds two calls with different ids, each with an arguments string. This is parallel tool calling: the model asked for both lookups in one turn, and a correct loop must return a tool message for every id. The second request carries the whole conversation so far, the assistant message with its two calls and the two tool results, and the model answers with stop.
Validation, errors and limits
The last two lines of the script feed a call with arguments {"id": 5}, a field name the schema does not have. Validation fails and run_tool returns the text error: Field required. Returning the error as the tool result, instead of raising it, lets the model see what went wrong and often fix its next call. Raising would stop your loop unless you caught the error.
Treat tool arguments as untrusted input. The model may have been steered by text it read earlier, so validate type, range and allowed values the way you would for a web form, and never run a model-supplied string as code or as a database query.
OpenAI's guide also lists a strict mode that makes the model follow the schema exactly, and a tool_choice setting that can force or forbid a call. Ollama's OpenAI-compatibility page does not list tool_choice, so on this local server you cannot force a call, and the calls above are the model's own decision. When you move to another provider, read its own limits before relying on either setting.
What is the type of the arguments field in a tool call, and what must your code do with it?
- A JSON-encoded string. Parse it, validate it against the schema, and only then run the function.
The model returns two tool calls in one turn. What must the next request contain?
- The earlier messages, the assistant message holding both calls, and one
toolmessage for each call, each carrying the matchingtool_call_id.
A tool call arrives with a missing field. Why return an error string as the result and not raise an exception?
- The model sees the message and can repair the call, while an uncaught exception would stop the loop.
- Return the error to the model, and log it for yourself.
Part 3 · Conversation memory
The API remembers nothing
A chat model call is stateless: the server keeps nothing between requests. When a conversation seems to continue, it is because your code sent the earlier messages again. Memory in an application means the code that decides which past messages go into the next request.
Sending everything works until the conversation outgrows the model's context window, and long before that it makes every request slower and dearer, because you pay for the whole history each time. Three simple strategies cover most needs. Buffer memory keeps every message. Window memory keeps only the most recent ones, counted in messages or, better, in tokens. Summary memory replaces older turns by a short summary written by the model and keeps the recent turns word for word.
| Strategy | Keeps | Cost | Weakness |
|---|---|---|---|
| Buffer | Every message | Grows without limit | Hits the context limit |
| Window | The last few turns that fit a token budget | Fixed | Forgets earlier facts completely |
| Summary | A summary plus the recent turns | Fixed, plus a model call | The summary can drop or distort details |
KeepsEvery message
CostGrows without limit
Weakness
A window, then a summary
The window class walks the history from the newest message backwards and stops when the next message would go over the budget. The demonstration uses a made-up trip-planning chat of seven turns and a budget of 60 tokens. Then it asks a question whose answer was stated in the third turn.
import textwrap import tiktoken from llm import chat enc = tiktoken.get_encoding("o200k_base") def size(m): return len(enc.encode(m["content"])) + 4 class WindowMemory: def __init__(self, budget): self.budget, self.turns = budget, [] def add(self, role, content): self.turns.append({"role": role, "content": content}) def messages(self): kept, used = [], 0 for m in reversed(self.turns): used += size(m) if used > self.budget: break kept.append(m) return kept[::-1]
HISTORY = [
("user", "I am Meera, planning 3 days in Mysuru this December."),
("assistant", "Lovely. Do you prefer palaces or food walks?"),
("user", "Palaces mostly. My budget is 15,000 rupees in total."),
("assistant", "Then the palace and two museums fit well."),
("user", "I will travel by train from Hyderabad."),
("assistant", "Book early, December trains fill up."),
("user", "Good. Which day should I see the palace?"),
]
mem = WindowMemory(budget=60)
for role, text in HISTORY:
mem.add(role, text)
kept = mem.messages()
print(len(HISTORY), "turns,", len(kept), "kept,",
sum(size(m) for m in kept), "tokens")
q = {"role": "user", "content": "What is my total budget?"}
msg, _ = chat(kept + [q])
print("window :", textwrap.shorten(msg.content, 62))Four of the seven turns fit the budget, 51 tokens, and the budget answer was in one of the dropped turns. The model has no way to recover it, and it says so, in its own words. That is the characteristic failure of window memory: the facts you lose are silent.
Summary memory subclasses the window. When turns have been dropped, it asks the model for a short summary of just those turns, with an instruction to keep every number and name, and puts the result in a system message before the kept turns.
class SummaryMemory(WindowMemory): def messages(self): kept = super().messages() old = self.turns[:len(self.turns) - len(kept)] if not old: return kept text = "\n".join(f"{m['role']}: {m['content']}" for m in old) s, _ = chat([{"role": "user", "content": "Summarise these earlier chat turns in one short " "paragraph, keeping every number and name:\n" + text}]) self.summary = s.content note = "Summary of the earlier conversation: " + s.content return [{"role": "system", "content": note}] + kept smem = SummaryMemory(budget=60) smem.turns = list(mem.turns) msgs = smem.messages() print("summary:", textwrap.fill(smem.summary, 60)) msg, _ = chat(msgs + [q]) print("answer :", textwrap.shorten(msg.content, 62))
Choosing and testing memory
In the run, the summary kept the figure of 15,000 rupees and the model answered the budget question correctly. That single run does not prove summaries are safe. A summary is a model output and can drop or change a detail, so an application that must never forget something, such as an allergy, a deadline or a consent, should store that fact separately in a structured record and put it in every request, and not rely on a summary.
Other designs exist. A long-term memory stores facts in a database and retrieves the relevant ones by search, using the vector search of the previous chapter. Choosing among those memory types is a design question for agents. Whatever you choose, keep the policy in one class, test it without a model by feeding it scripted turns, and make the token budget a setting.
The cost of summary memory is an extra model call whenever turns are dropped. The sketch above recomputes the summary on every request, which is wasteful. A real implementation would store the summary and update it only when new turns fall out of the window.
Why is window memory counted in tokens and not messages?
- Messages differ greatly in length, so a message count gives an unpredictable prompt size, while a token budget bounds it.
In the run above the window answered that it could not tell the user's budget. Why?
- The turn that stated the budget was older than the window, so it was never sent. The model has no other copy.
Name one kind of fact that should not live only in a conversation summary.
- Anything that must never be lost or altered, such as an allergy, a deadline or a consent. Store it in a structured record and send it with every request.
Part 4 · Routing
Send each request to the right handler
A single prompt that handles billing questions, delivery tracking, product advice and everything else becomes long and hard to test. Routing splits it: first classify the request, then pass it to a handler built for that class. Each handler can have its own prompt, tools and even model. The Anthropic article on building effective agents describes routing in the same terms, and notes that it lets you optimise one category without hurting the others.
The classifier can be rules, a trained model or a language model. A rule such as "contains the word invoice" is cheap and predictable but misses paraphrases. A language model reads meaning, at the price of a call and occasional mistakes. Many systems use rules first for the obvious cases and the model for the rest.
Three design points keep a router dependable. Constrain the output to a fixed set of labels, using a schema with a Literal type so the reply cannot be anything else. Always keep a deterministic default, a route that takes anything the classifier cannot place, usually a person or a general handler. And wrap the call, because a model call can fail, time out or return something unreadable, and the default should catch that too.
A router on eight requests
The router below asks the model for one label from four: billing, shipping, product and other. A dictionary maps each label to a handler. Here the handlers are small stand-ins that return their name, and in a real system each would be its own chain or agent. Any error during classification returns other, so the dictionary lookup can never fail.
from typing import Literal from pydantic import BaseModel from llm import client, MODEL class Route(BaseModel): route: Literal["billing", "shipping", "product", "other"] SYSTEM = ("Classify the customer message. billing: payments, refunds, " "invoices. shipping: delivery and tracking. product: how a " "product works or its features. other: anything else.") def classify(text): try: r = client.chat.completions.parse( model=MODEL, reasoning_effort="none", response_format=Route, messages=[{"role": "system", "content": SYSTEM}, {"role": "user", "content": text}]) return r.choices[0].message.parsed.route except Exception: return "other" HANDLERS = { "billing": lambda t: "billing desk", "shipping": lambda t: "tracking lookup", "product": lambda t: "product guide", "other": lambda t: "human agent", }
REQUESTS = [
"I was charged twice for my last order",
"Where is my parcel, it is two days late",
"Does the pressure cooker work on induction?",
"Can you send me a copy of my invoice?",
"How do I wash the cotton bedsheet?",
"My delivery address changed, can you update it?",
"Tell me a joke",
"Is the desk lamp bulb replaceable?",
]
for text in REQUESTS:
route = classify(text)
print(f"{route:<9} -> {HANDLERS[route](text):<16} {text[:34]}")
def broken(*args, **kwargs):
raise RuntimeError("model down")
client.chat.completions.parse = broken
print("model down ->", classify("Where is my parcel?"))billing -> billing desk I was charged twice for my last or shipping -> tracking lookup Where is my parcel, it is two days product -> product guide Does the pressure cooker work on i billing -> billing desk Can you send me a copy of my invoi product -> product guide How do I wash the cotton bedsheet? shipping -> tracking lookup My delivery address changed, can y other -> human agent Tell me a joke product -> product guide Is the desk lamp bulb replaceable? model down -> other
Output from one run; yours will differ. Requests are cut to 34 characters here.
All eight made-up requests landed in a sensible place. The address change went to shipping, which is a fair reading, though a team might want it handled by an account desk instead. The joke went to other, which is the point of the default. The last line replaces the model call with a function that raises an error: the router still returns other, so a model outage turns into a handover to a person and not into a crash.
Making a router trustworthy
Eight cases is a demonstration and not an evaluation. To trust a router, collect real requests, label each with the route a person would choose, and measure accuracy, and look at the confusion between pairs of labels. Mistakes cost differently: sending a billing question to the product guide is annoying, while sending a safety complaint to a bot may not be acceptable. Route sensitive classes to people by rule first, before the model sees them.
Descriptions matter. The classifier prompt above explains each label in a few words, and the quality of those descriptions decides most of the accuracy. If two labels confuse the model, merge them or sharpen the descriptions before reaching for a bigger model. Adding a new route is then a change in three places, the Literal, the prompt and the handler map, and a test for each.
Routing also saves money. A cheap model can handle the easy majority of requests, and a harder request can go to a stronger one. That is a routing decision too, and it is the idea behind a model gateway.
Why make the route a Literal in the schema instead of free text?
- The reply can then only be one of the allowed labels, so the handler lookup cannot hit an unknown key, and a bad reply fails at parsing.
What does the other route protect against in this code?
- Requests that fit no handler, and failures such as a model error or an unreadable reply. Both end up with a person, and nothing crashes.
The router sent an address change to shipping. How would you decide whether that is a mistake?
- Compare the model's label with the label a person chooses on real requests, count the disagreements, and decide from that, not from one example.
Part 5 · When a framework helps
What frameworks give you
Everything so far is plain Python and the OpenAI-compatible client. A framework, a library that supplies ready-made parts for these patterns, can save time, and it also adds a layer between you and the model. The Anthropic article on agents recommends starting with direct API calls, because frameworks can hide the prompts and responses and make problems harder to debug, and advises that if you use one you should understand what it does underneath. This lesson follows that advice by showing what a framework replaces.
| Plain code in this chapter | What a framework offers |
|---|---|
The chat helper and one client | Chat-model wrappers with one interface over many providers |
| A tool schema from a Pydantic class | Decorators that build the schema from a function's signature |
| An f-string template | Prompt-template objects with variables and partial filling |
| The chain: functions called in order | Graphs: nodes, edges and shared state |
| A memory class | Checkpointers that save state per conversation |
| Retry and error handling by hand | Built-in retries, streaming of intermediate steps, tracing hooks |
The most distinctive pieces are the graph and the checkpointer rows. A state graph describes a flow as nodes (functions), edges (what runs next, possibly chosen by a condition) and a state that each node reads and updates. Once a flow is a graph, a framework can save the state after every step. That is useful for pausing for human approval, resuming after a crash, and replaying a failed run.
The same chain as a graph
LangGraph is an open-source library for graphs of this kind. The version used here is 1.2.20. The code below rebuilds the extract-and-draft chain from the first lesson as a two-node graph, reusing the same two functions. A State type names what flows between nodes, each node returns the keys it changes, and edges join START, the two nodes and END.
from typing import TypedDict from langgraph.checkpoint.memory import MemorySaver from langgraph.graph import END, START, StateGraph from a1_chain import Ticket, draft, extract class State(TypedDict, total=False): text: str ticket: dict reply: str def extract_node(state): return {"ticket": extract(state["text"]).model_dump()} def draft_node(state): return {"reply": draft(Ticket(**state["ticket"]))} g = StateGraph(State) g.add_node("extract", extract_node) g.add_node("draft", draft_node) g.add_edge(START, "extract") g.add_edge("extract", "draft") g.add_edge("draft", END) app = g.compile(checkpointer=MemorySaver())
The compiled graph is given a checkpointer, here an in-memory one that keeps checkpoints in RAM and loses them on restart. LangGraph's documentation lists SQLite and PostgreSQL checkpointers for persistence. A checkpointer stores a snapshot of the state, and you choose which conversation a run belongs to with a thread_id in the config. The state holds the ticket as a plain dictionary, because the checkpointer serialises it and a plain dictionary needs no extra registration.
cfg = {"configurable": {"thread_id": "t-1"}}
text = "Order AB-2210: the notebook pages are torn. Refund please."
out = app.invoke({"text": text}, cfg)
print(out["ticket"]["order_id"], out["ticket"]["wants"])
print(out["reply"][:70])
snap = app.get_state(cfg)
print(snap.next, sorted(snap.values))
print(len(list(app.get_state_history(cfg))), "checkpoints")AB-2210 Refund We are very sorry to hear that the pages in your notebook arrived dama () ['reply', 'text', 'ticket'] 4 checkpoints
Output from one run; yours will differ. The reply is cut to 70 characters by the script.
The graph gave the same result as the chain. The extra information is in the history: four checkpoints for one run. The earliest was taken before the first node, the next held the input with extract waiting, then one after extract with draft waiting, and one after draft with nothing left to run. A graph can pause between any two of those and continue later, which is how approval steps are built.
Deciding whether to adopt one
For a two-step chain the graph is more code than the plain version, and it adds a dependency whose interfaces change between releases. The balance shifts as the flow grows. Branches and loops, long-running work that must survive a restart, human approval in the middle, and several people working on the same flow are the cases where a graph earns its keep. A simple chain, or a router with three handlers, does not need one.
Whatever you adopt, keep three habits from this chapter. Keep prompts in code you can read, and avoid templates you cannot see. Keep validation and the gates in plain functions that tests can call without a model. And keep the model calls behind one small helper, so a switch of provider or framework changes one file.
Later topics build on the patterns here. Retrieval adds a search step in front of the model. Agents let the model choose its own steps within a budget. Both reuse the helper, the tool round trip, the memory class and the router you have just seen.
In the run, the graph's history held four checkpoints for one run of two nodes. Why four and not two?
- One is taken before the first node, one with the input waiting for
extract, one afterextractand one afterdraft, so there is a checkpoint at each boundary, not one per node.
What does thread_id select?
- Which conversation's saved state the run reads and writes, so separate users or conversations stay separate.
A flow has two model calls in a fixed order, no branches, and no need to pause or resume. Would you add a state graph and a checkpointer? Why?
- Probably not. Plain functions called in order are shorter, easier to test and have no extra dependency.
- A graph pays off once there are branches or loops, work that must survive a restart, or a human approval step in the middle.