About this notebook

Companion to Module 2: LLMs for builders. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)

Every agent talks to its model through a client, and most production incidents in agent systems start there: a rate limit, a malformed JSON reply, a bill that grew overnight. This notebook builds the client-side habits, each as a small layer you can read in full:

  1. messages: what a request contains, and why the model remembers nothing;
  2. one interface, many providers: what LiteLLM does for you;
  3. structured output with Pydantic, and a repair loop for when validation fails;
  4. concurrency with asyncio, and a semaphore to respect rate limits;
  5. retries with exponential backoff, only for errors worth retrying;
  6. caching identical requests, and how provider-side prompt caching differs;
  7. a cost budget that refuses to send a request it cannot afford.

Which model answers here?

With no MODEL set, the offline policy model answers, with two keyword rules written for this notebook (a greeting and a support-ticket classifier). Its answers are deterministic and say nothing about how a real model would classify the same emails. Failures (bad JSON, rate limits) are staged with small wrapper classes so they happen on cue. Set MODEL and re-run to see a real model; only sections 1 and 3 call it.

from agentlab.nbsetup import setup
 
nb = setup("02c_llm_client", packs=["client"])
llm = nb.llm

LLM backend

offline policy model (deterministic, rule-based, no API key used)

1. Messages, and a model that remembers nothing

A request is a list of messages, each with a role: system for the instructions, user for the person (or program) asking, assistant for the model’s earlier replies, and tool for tool results. The model reads the whole list and writes the next assistant message. Watch what happens when the second request leaves out the first:

from agentlab import LlmRequest, Message
 
SYSTEM = "You are a concise assistant."
first = [Message(role="user", content="Hi, my name is Ada and I live in Lisbon.")]
reply = await llm.generate(LlmRequest(instructions=[SYSTEM], contents=first))
print("turn 1:", reply.text)
 
alone = [Message(role="user", content="What is my name?")]
reply2 = await llm.generate(LlmRequest(instructions=[SYSTEM], contents=alone))
print("turn 2, sent alone:       ", reply2.text)
 
history = first + reply.content + alone
reply3 = await llm.generate(LlmRequest(instructions=[SYSTEM], contents=history))
print("turn 2, with the history: ", reply3.text)
turn 1: Nice to meet you, Ada.
turn 2, sent alone:        I don't know yet: nothing earlier in this conversation tells me. (A model only sees the messages included in the request.)
turn 2, with the history:  Your name is Ada.

The model is a function of the request and nothing else. A chat app that seems to remember you does what the third call did: it re-sends the whole conversation every turn. This is the root of two later topics: memory (Module 6), which is about choosing what to re-send, and cost, because every turn pays again for all the turns before it.

This is the request as it goes over the wire, in the chat-completions format most providers accept:

from agentlab.display import show_messages
from agentlab.llm import build_messages
 
show_messages(build_messages(LlmRequest(instructions=[SYSTEM], contents=history)))
   system: You are a concise assistant.
     user: Hi, my name is Ada and I live in Lisbon.
assistant: Nice to meet you, Ada.
     user: What is my name?

2. One interface, many providers

Providers differ in their wire formats: Anthropic takes the system prompt as a separate field and returns tool calls as content blocks, OpenAI returns a tool_calls list, local servers vary again. LiteLLM translates one OpenAI-style call into each provider’s format and back, so the provider is chosen by a string. agentlab.llm.LiteLLMClient is a thin wrapper around litellm.acompletion; creating one does not contact anyone:

from agentlab.llm import LiteLLMClient
 
for model_name in ["anthropic/claude-sonnet-5-5", "openai/gpt-5-mini", "ollama/qwen3"]:
    client = LiteLLMClient(model_name)
    print(f"{model_name:28} -> {type(client).__name__}, mode={client.mode}")
anthropic/claude-sonnet-5-5  -> LiteLLMClient, mode=live
openai/gpt-5-mini            -> LiteLLMClient, mode=live
ollama/qwen3                 -> LiteLLMClient, mode=live

Everything else in this course talks to a BaseLLM, the interface all backends share: await llm.generate(request) returns an LlmResponse with .text, .tool_calls and .usage_metadata. Swapping the offline model for a live one changes the object passed in, not the code that uses it. The wrappers in sections 4 to 7 rely on that: each one is a BaseLLM that holds another BaseLLM.

3. Structured output

Agents need data, not prose: a category to route on, a number to compare. Describe the shape with a Pydantic model; its JSON Schema goes into the request, and the reply is parsed and validated against the model.

from typing import Literal
 
from pydantic import BaseModel, Field
 
 
class Ticket(BaseModel):
    category: Literal["billing", "bug", "feature"]
    priority: int = Field(ge=1, le=3, description="1 = low, 3 = urgent")
    summary: str = Field(max_length=80)
 
 
print(Ticket.model_json_schema()["properties"]["priority"])
email = "Classify this email: 'I was charged twice this month. Please refund one payment.'"
ticket = await llm.ask(email, response_format=Ticket)
print(repr(ticket))
{'description': '1 = low, 3 = urgent', 'maximum': 3, 'minimum': 1, 'title': 'Priority', 'type': 'integer'}
Ticket(category='billing', priority=3, summary='I was charged twice this month.')

llm.ask(..., response_format=Ticket) adds the schema to the instructions, then runs Ticket.model_validate_json on the reply. Validation is the important half. A model can return text around the JSON, a priority of 7, or a category that does not exist, and the Literal and Field(ge=1, le=3) constraints turn each of those into an exception instead of a silent wrong value.

What to do with the exception? Usually: tell the model what was wrong and ask again. The validation error is a precise, machine-written correction. To see the loop work, stage a model that makes two mistakes before getting it right:

import json
 
from pydantic import ValidationError
 
from agentlab.llm import ScriptedLLM, strip_code_fence
 
SCHEMA_HINT = "Respond ONLY with JSON matching this schema:\n"
 
 
async def ask_structured(llm, prompt, model_cls, max_attempts=3):
    contents = [Message(role="user", content=prompt)]
    system = SCHEMA_HINT + json.dumps(model_cls.model_json_schema())
    for attempt in range(1, max_attempts + 1):
        reply = await llm.generate(LlmRequest(instructions=[system], contents=contents,
                                              response_format=model_cls))
        try:
            return model_cls.model_validate_json(strip_code_fence(reply.text))
        except ValidationError as err:
            problem = "; ".join(f"{'.'.join(map(str, e['loc'])) or 'reply'}: {e['msg']}"
                                for e in err.errors())
            print(f"attempt {attempt} rejected: {problem}")
            contents += reply.content
            contents.append(Message(role="user", content=f"Invalid: {problem}. Try again."))
    raise ValueError(f"no valid {model_cls.__name__} after {max_attempts} attempts")
 
 
clumsy = nb.track(ScriptedLLM([
    'Sure! {"category": "billing", "priority": 3, "summary": "Charged twice"}',
    '{"category": "billing", "priority": 7, "summary": "Charged twice"}',
    '{"category": "billing", "priority": 3, "summary": "Charged twice"}',
]))
print(repr(await ask_structured(clumsy, email, Ticket)))
print("what the model saw on its last attempt:")
show_messages(build_messages(clumsy.calls[-1][0])[1:])
attempt 1 rejected: reply: Invalid JSON: expected value at line 1 column 1
attempt 2 rejected: priority: Input should be less than or equal to 3
Ticket(category='billing', priority=3, summary='Charged twice')
what the model saw on its last attempt:
     user: Classify this email: 'I was charged twice this month. Please refund one payment.'
assistant: Sure! {"category": "billing", "priority": 3, "summary": "Charged twice"}
     user: Invalid: reply: Invalid JSON: expected value at line 1 column 1. Try again.
assistant: {"category": "billing", "priority": 7, "summary": "Charged twice"}
     user: Invalid: priority: Input should be less than or equal to 3. Try again.

Two rounds of feedback were enough. Each retry costs a full request, though, so it pays to make failures rare in the first place: a clear schema with descriptions, an example in the instructions, and the provider’s strict structured-output mode where it exists (Notebook 2b showed how that mode works inside). Keep validation even then: a strict mode guarantees the shape, not that the priority is right.

4. Many requests at once

A model call spends most of its time waiting on the network. Python’s asyncio lets one process wait on many calls at once. To see the effect offline, wrap the model in a layer that adds 0.1 s of simulated network latency to every call:

import asyncio
import time
 
from agentlab.llm import BaseLLM
 
 
class SlowLLM(BaseLLM):
    """Adds a fixed delay to every call, like a network round trip."""
 
    def __init__(self, inner, delay=0.1):
        super().__init__()
        self.inner, self.delay = inner, delay
        self.mode, self.model = inner.mode, inner.model
 
    async def _generate(self, request):
        await asyncio.sleep(self.delay)
        return await self.inner.generate(request)
 
 
emails = [
    "I was charged twice this month.",
    "The export button crashes the app.",
    "Could you add a dark mode?",
    "My invoice shows the wrong address.",
    "Login fails with error 500 since this morning, urgent.",
    "Please support CSV import.",
    "The dashboard is blank after the update.",
    "Can I get a refund for the annual plan?",
]
slow = SlowLLM(llm, delay=0.1)
 
 
def classify(e):
    return slow.ask(f"Classify this email: '{e}'", response_format=Ticket)
 
 
t0 = time.perf_counter()
one_by_one = [await classify(e) for e in emails]
t_seq = time.perf_counter() - t0
 
t0 = time.perf_counter()
together = await asyncio.gather(*(classify(e) for e in emails))
t_par = time.perf_counter() - t0
print(f"one by one: {t_seq:.1f} s    all at once with gather: {t_par:.1f} s")
assert one_by_one == list(together)
for e, t in zip(emails, together):
    print(f"  {t.category:8} p{t.priority}  {e}")
one by one: 0.8 s    all at once with gather: 0.1 s
  billing  p3  I was charged twice this month.
  bug      p2  The export button crashes the app.
  feature  p1  Could you add a dark mode?
  billing  p1  My invoice shows the wrong address.
  bug      p3  Login fails with error 500 since this morning, urgent.
  feature  p1  Please support CSV import.
  bug      p2  The dashboard is blank after the update.
  billing  p1  Can I get a refund for the annual plan?

asyncio.gather starts every call and waits for all of them; the results come back in the order of the inputs, whatever order the calls finish in. Providers limit how many requests you may send per minute, though, and firing 500 at once earns 500 rate-limit errors. A semaphore caps how many calls are in flight:

limit = asyncio.Semaphore(2)
 
 
async def classify_limited(e):
    async with limit:  # at most two calls in flight
        return await classify(e)
 
 
t0 = time.perf_counter()
await asyncio.gather(*(classify_limited(e) for e in emails))
print(f"at most 2 in flight: {time.perf_counter() - t0:.1f} s")
at most 2 in flight: 0.4 s

5. Retries with backoff

Some errors go away if you wait: rate limits (HTTP 429), overloaded servers (529, 503), timeouts. Others never will: a malformed request (400) or a bad key (401) fails the same way every time, and retrying it only wastes time and money. The standard recipe is to retry only the first kind, waiting twice as long after each failure (exponential backoff), with some randomness (jitter) so that many clients that failed together do not all retry at the same instant.

agentlab’s clients report provider errors in response.error_message instead of raising, so the retry layer inspects that. A staged flaky model fails twice with a rate limit:

import numpy as np
 
from agentlab.llm import LlmResponse
 
RETRYABLE = ("RateLimit", "429", "Overloaded", "529", "503", "Timeout")
 
 
class FlakyLLM(BaseLLM):
    """Fails its first `failures` calls with the given error, then delegates."""
 
    def __init__(self, inner, failures=2, error="RateLimitError: 429 Too Many Requests"):
        super().__init__()
        self.inner, self.failures, self.error = inner, failures, error
        self.mode, self.model = inner.mode, inner.model
 
    async def _generate(self, request):
        if self.failures > 0:
            self.failures -= 1
            return LlmResponse(error_message=self.error, provenance=self.inner.mode)
        return await self.inner.generate(request)
 
 
class RetryingLLM(BaseLLM):
    def __init__(self, inner, attempts=4, base_delay=0.02, seed=0):
        super().__init__()
        self.inner, self.attempts, self.base = inner, attempts, base_delay
        self.rng = np.random.default_rng(seed)
        self.mode, self.model = inner.mode, inner.model
 
    async def _generate(self, request):
        for attempt in range(self.attempts):
            response = await self.inner.generate(request)
            err = response.error_message
            if err is None or not any(k in err for k in RETRYABLE):
                return response  # success, or an error retrying cannot fix
            if attempt == self.attempts - 1:
                break
            wait = self.base * 2**attempt * (0.5 + self.rng.random())  # backoff with jitter
            print(f"  attempt {attempt + 1}: {err!r}; waiting {wait * 1000:.0f} ms")
            await asyncio.sleep(wait)
        return response
 
 
robust = RetryingLLM(FlakyLLM(llm, failures=2))
print(await robust.ask("Classify this email: 'The export button crashes the app.'",
                       response_format=Ticket))
print("a bad request is not retried:")
broken = RetryingLLM(FlakyLLM(llm, failures=1, error="BadRequestError: 400 invalid schema"))
print(" ", (await broken.generate(LlmRequest(contents=alone))).error_message)
  attempt 1: 'RateLimitError: 429 Too Many Requests'; waiting 23 ms
  attempt 2: 'RateLimitError: 429 Too Many Requests'; waiting 31 ms
category='bug' priority=2 summary='The export button crashes the app.'
a bad request is not retried:
  BadRequestError: 400 invalid schema

LiteLLMClient passes num_retries to LiteLLM, which applies a similar policy internally, so for live runs you get retries without writing them. It is worth having written them once: when a run stalls, the question “which layer is retrying what, and how long does it wait?” has to have an answer.

6. Caching

An agent under development re-sends the same requests constantly: re-running a notebook, re-running an evaluation after changing one task. An exact-match cache stores each response under a hash of the request. agentlab.llm.cassette.request_key computes that hash from the messages, tools, schema and temperature, so any change to any of them is a miss:

from agentlab.llm.cassette import request_key
 
 
class CachedLLM(BaseLLM):
    def __init__(self, inner):
        super().__init__()
        self.inner, self.store = inner, {}
        self.hits = self.misses = 0
        self.mode, self.model = inner.mode, inner.model
 
    async def _generate(self, request):
        key = request_key(request)
        if key in self.store:
            self.hits += 1
        else:
            self.misses += 1
            self.store[key] = await self.inner.generate(request)
        return self.store[key]
 
 
cached = CachedLLM(llm)
req = LlmRequest(instructions=[SYSTEM], contents=history)
for _ in range(3):
    await cached.generate(req)
await cached.generate(LlmRequest(instructions=[SYSTEM], contents=history, temperature=0.2))
print(f"hits {cached.hits}, misses {cached.misses}; key {request_key(req)}")
hits 2, misses 2; key 10fa0307663ff4b33307ab31

Exact caching is only safe where you want the same answer again (tests, evaluation replays, idempotent lookups). It is also what agentlab’s cassettes do: record live calls once, replay them offline (AGENTLAB_BACKEND=record, then replay).

Providers offer a different, complementary kind: prompt caching. The provider keeps the computed state of a request’s prefix, and a later request that starts with the same prefix is cheaper (typically a 50 to 90% discount on the cached input tokens) and faster. For an agent that is a big deal, because each step re-sends the same instructions and tools followed by a growing history:

step 1: [ system | tools ][ user ]
step 2: [ system | tools ][ user ][ call 1 | result 1 ]
step 3: [ system | tools ][ user ][ call 1 | result 1 ][ call 2 | result 2 ]
        \______________ identical prefix, cacheable _____________/

The rule that follows: keep everything stable at the front, append at the end, and never put a timestamp or a random id in the system prompt, since one changed byte early on makes everything after it a cache miss.

7. A cost budget

The last layer refuses to send a request that would take the run over its budget. It estimates the input tokens before sending (the same estimate the usage tables use) and keeps a running total:

from agentlab.llm.pricing import estimate_messages_tokens, reference_cost
 
 
class BudgetExceeded(RuntimeError):
    pass
 
 
class BudgetLLM(BaseLLM):
    def __init__(self, inner, max_usd):
        super().__init__()
        self.inner, self.max_usd, self.spent = inner, max_usd, 0.0
        self.mode, self.model = inner.mode, inner.model
 
    async def _generate(self, request):
        est = reference_cost(estimate_messages_tokens(build_messages(request)), 0)
        if self.spent + est > self.max_usd:
            raise BudgetExceeded(f"next call ~USD {est:.5f}, spent USD {self.spent:.5f} "
                                 f"of USD {self.max_usd:.5f}")
        response = await self.inner.generate(request)
        self.spent += est
        return response
 
 
budgeted = BudgetLLM(llm, max_usd=0.002)
chat = []
try:
    for turn in range(1, 50):
        chat.append(Message(role="user", content=f"Turn {turn}. {emails[turn % 8]}"))
        reply = await budgeted.generate(LlmRequest(instructions=[SYSTEM], contents=chat))
        chat += reply.content
except BudgetExceeded as err:
    print(f"stopped before turn {turn}: {err}")
stopped before turn 9: next call ~USD 0.00052, spent USD 0.00193 of USD 0.00200

Because each turn re-sends the history, the cost per turn grows, and the budget runs out sooner than a per-turn estimate would suggest. A real budget layer would also count output tokens and use the provider’s reported usage after each call; this one shows the idea.

The layers compose, because each is a BaseLLM wrapping a BaseLLM:

agent -> BudgetLLM -> CachedLLM -> RetryingLLM -> LiteLLMClient -> provider
         refuse       skip if      wait and       translate and
         if broke     seen         try again      send

The order matters: the cache sits outside the retries (a hit needs no retry), and the budget sits outside everything (a cache hit costs nothing, but the estimate here would still count it; moving the budget inside the cache fixes that).

stack = BudgetLLM(CachedLLM(RetryingLLM(FlakyLLM(llm, failures=1))), max_usd=0.01)
print(await stack.ask("Classify this email: 'Could you add a dark mode?'",
                      response_format=Ticket))
  attempt 1: 'RateLimitError: 429 Too Many Requests'; waiting 23 ms
category='feature' priority=1 summary='Could you add a dark mode?'

Going live

Put a model name and its key in .env at the repository root (it is gitignored):

MODEL=anthropic/claude-sonnet-5-5
ANTHROPIC_API_KEY=...

setup() then picks the live client, and the banner at the top says so. The headless build that produces this website always strips keys, which is why the outputs here come from the offline model.

Try this

  • Add a fourth Literal value, "account", and an email about a locked account. What does the offline model say? With a live model, does the description of each category change what it chooses?
  • Make RetryingLLM give up when the total time spent waiting would exceed a deadline, and raise an error that says how long it waited.
  • Move BudgetLLM inside CachedLLM in the stack, send the same request twice, and check that the second one no longer counts against the budget.
nb.usage()
model callsinput tokensoutput tokenscost
43 (fake: 40, scripted: 3)≈ 6,216≈ 1,032≈ USD 0.0103 (reference price)