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 model API hides the same three steps: compute a probability for every possible next token, pick one, append it and repeat. The knobs you set on an API call (temperature, top_p, “JSON mode”, structured outputs) all act on the middle step. This notebook makes that step visible with a model small enough to inspect:

  1. train a character n-gram model, a table of counts that is a genuine language model;
  2. watch context length trade memorisation against generalisation;
  3. implement greedy, temperature, top-k and top-p sampling, and see greedy decoding loop;
  4. ask the model for tool calls as JSON and count how often the output is invalid;
  5. implement constrained decoding: mask every character the grammar forbids, so the output is always valid;
  6. plug the tiny model into an agent and see why valid is not the same as correct.

Which model answers here?

The models in this notebook are trained in the notebook itself, in well under a second, on the CPU. They are far too small to be useful, which is the point: everything a large model does at decoding time can be seen here in full. No API key is used.

from agentlab.nbsetup import setup
 
nb = setup("02b_toy_lm_sampling")

LLM backend

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

1. A table of counts is a language model

A language model assigns a probability to each possible next symbol given the ones before it. The simplest way to do that is to count. For an order- model, look at the last characters and ask how often each character followed them in the training text:

Raw counts give probability zero to anything not seen in training, so agentlab.tiny.charlm.CharNGram blends every context length from 0 to (Witten-Bell smoothing: a context that was followed by many different characters trusts its own counts less). Here are the next-character probabilities after "The agent ".

import numpy as np
 
from agentlab.config import fixtures_dir
from agentlab.tiny.charlm import CharNGram
 
text = (fixtures_dir() / "text" / "field_notes.txt").read_text()
model = CharNGram(order=6).fit(text)
p = model.probs("The agent ")
top = np.argsort(-p)[:6]
print(f"vocabulary: {len(model.vocab)} characters, {model.n_contexts:,} contexts stored")
print("after 'The agent ':", ", ".join(f"{model.vocab[i]!r} {p[i]:.2f}" for i in top))
vocabulary: 51 characters, 8,365 contexts stored
after 'The agent ': 'i' 0.27, 't' 0.21, 'c' 0.13, 'o' 0.13, 'w' 0.07, 'l' 0.07

A transformer does the same job with a neural network instead of a table: it maps the context to one score (a logit) per token, and a softmax turns scores into probabilities. The rest of this notebook only uses model.probs(context) and model.logits(context), so everything below applies unchanged to a real model.

2. Context length: memorising against generalising

A longer context should predict better, but a table of counts can only use contexts it has seen. Measure the average number of bits per character on the training text and on a held-out part of the file (lower is better):

split = int(len(text) * 0.85)
train, held_out = text[:split], text[split:]
orders = [1, 2, 3, 4, 5, 6, 8, 10]
bits_train, bits_held = [], []
for n in orders:
    m = CharNGram(n).fit(train)
    bits_train.append(m.cross_entropy(train[:1500]))
    bits_held.append(m.cross_entropy(held_out))
    print(f"order {n:2}: {bits_train[-1]:.2f} bits/char on training text, "
          f"{bits_held[-1]:.2f} held out, {m.n_contexts:6,} contexts")
order  1: 4.21 bits/char on training text, 4.31 held out,      1 contexts
order  2: 3.21 bits/char on training text, 3.48 held out,     51 contexts
order  3: 2.05 bits/char on training text, 2.72 held out,    447 contexts
order  4: 1.29 bits/char on training text, 2.46 held out,  1,830 contexts
order  5: 0.85 bits/char on training text, 2.56 held out,  4,303 contexts
order  6: 0.60 bits/char on training text, 2.67 held out,  7,617 contexts
order  8: 0.28 bits/char on training text, 2.85 held out, 15,905 contexts
order 10: 0.14 bits/char on training text, 2.95 held out, 25,450 contexts
import matplotlib.pyplot as plt
 
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.plot(orders, bits_train, "o-", color="#2c5f9e", label="training text")
ax.plot(orders, bits_held, "s--", color="#b5523b", label="held-out text")
best = orders[int(np.argmin(bits_held))]
ax.axvline(best, color="#81796f", lw=0.8, ls=":")
ax.set_xlabel("order n (context of n - 1 characters)")
ax.set_ylabel("bits per character")
ax.spines[["top", "right"]].set_visible(False)
ax.legend(frameon=False, loc="upper right")
plt.show()
Bits per character for n-gram models of increasing order. Training loss keeps falling as the model memorises longer contexts; held-out loss is lowest at order 4 and rises after that.

Bits per character for n-gram models of increasing order. Training loss keeps falling as the model memorises longer contexts; held-out loss is lowest at order 4 and rises after that.

This is overfitting in its plainest form. Past order 4 the model mostly recalls exact phrases from 5,000 characters of training text, and new text rarely contains them. Neural models escape this because similar contexts get similar representations, so they can use long contexts they have never seen exactly. That, and not size alone, is what separates them from a count table.

Generating text makes the difference audible. Each sample below starts from the same prompt with the same random seed:

for n in [2, 4, 8]:
    m = CharNGram(n).fit(text)
    sample = m.generate("The agent ", max_chars=110, rng=np.random.default_rng(1))
    print(f"order {n}: The agent {sample!r}")
order 2: The agent 'mr whes, Eveas ild coiowron.\nthanset me rthather the t atotha ros bmowanten rusthas t t hde h chaolninthean y '
order 4: The agent 'loop need search find must into noth reads bothe times answer responswers. Add or say what go do somemory reve'
order 8: The agent 'lists the part you building an agent limit and not a feature before you expect: a tool. Instead of writing an '

Order 2 knows letter pairs, order 4 knows words, order 8 strings together phrases copied from the notes.

3. Choosing the next token

The model gives a distribution; a decoding strategy turns it into one choice. All of these fit in a few lines (the same functions live in agentlab.tiny.sampling):

def softmax(logits, temperature=1.0):
    z = logits / temperature
    z = z - z[np.isfinite(z)].max()
    e = np.where(np.isfinite(z), np.exp(z), 0.0)
    return e / e.sum()
 
 
def top_k(logits, k):
    keep = np.argsort(-logits)[:k]
    out = np.full_like(logits, -np.inf)
    out[keep] = logits[keep]
    return out
 
 
def top_p(logits, p):
    probs = softmax(logits)
    order = np.argsort(-probs)
    n_keep = int(np.searchsorted(np.cumsum(probs[order]), p) + 1)
    out = np.full_like(logits, -np.inf)
    out[order[:n_keep]] = logits[order[:n_keep]]
    return out
 
 
def decode_step(logits, rng, temperature=1.0, k=None, p=None):
    if temperature == 0:
        return int(np.argmax(logits))  # greedy
    z = logits / temperature
    if k:
        z = top_k(z, k)
    if p:
        z = top_p(z, p)
    return int(rng.choice(len(z), p=softmax(z)))

Temperature divides the logits before the softmax. Below 1 it sharpens the distribution towards the most likely token; above 1 it flattens it. Entropy (in bits) measures how spread out the choice is:

from agentlab.tiny.sampling import entropy_bits
 
logits = model.logits("The agent ")
for t in [0.5, 1.0, 2.0]:
    q = softmax(logits, t)
    best5 = np.argsort(-q)[:5]
    shown = ", ".join(f"{model.vocab[i]!r} {q[i]:.2f}" for i in best5)
    kept_p = np.isfinite(top_p(logits / t, 0.9)).sum()
    print(f"T={t}: {entropy_bits(q):.2f} bits; top-p 0.9 keeps {kept_p:2} chars; {shown}")
T=0.5: 2.19 bits; top-p 0.9 keeps  4 chars; 'i' 0.44, 't' 0.26, 'c' 0.11, 'o' 0.11, 'w' 0.03
T=1.0: 2.90 bits; top-p 0.9 keeps  7 chars; 'i' 0.27, 't' 0.21, 'c' 0.13, 'o' 0.13, 'w' 0.07
T=2.0: 3.82 bits; top-p 0.9 keeps 12 chars; 'i' 0.16, 't' 0.14, 'c' 0.11, 'o' 0.11, 'w' 0.08

Top-k keeps the most likely tokens; top-p (nucleus sampling) keeps the smallest set whose probability adds up to , so it keeps few tokens when the model is confident and many when it is not. Both cut off the long tail of unlikely tokens, where most of the nonsense in a sample comes from.

Greedy decoding (temperature 0) always takes the most likely token. It sounds like the safe choice. Watch what it does:

m6 = CharNGram(6).fit(text)
 
 
def generate(m, prompt, n_chars, rng, **kw):
    out = ""
    for _ in range(n_chars):
        out += m.vocab[decode_step(m.logits(prompt + out), rng, **kw)]
    return out
 
 
rng = np.random.default_rng(1)
print("greedy:       ", repr(generate(m6, "The agent ", 120, rng, temperature=0)))
print("T=0.7, p=0.9: ", repr(generate(m6, "The agent ", 120, rng, temperature=0.7, p=0.9)))
greedy:        'is a tool call and the model the model the model the model the model the model the model the model the model the model t'
T=0.7, p=0.9:  'limit timeout. Each steps before you change and arguments with the step returns. A plan that a tool is for a fact is har'

Greedy decoding falls into a loop: once the model is the most likely continuation of the model, it repeats forever. Large models loop less, but the effect is real, which is why chat APIs default to a temperature near 1 with top-p below 1.

For agents the usual advice is a low temperature for tool calls and structured output, where there is one right answer, and a higher one for open-ended writing. Two caveats. Temperature 0 on a hosted API is still not fully deterministic (batching and floating point vary between calls), so an agent must not rely on exact repeats. And low temperature makes a model consistent, not correct.

4. Asking for JSON

An agent needs the model to write tool calls in an exact format. To see what can go wrong, train the same kind of model on 1,200 synthetic examples of a question followed by the tool call that answers it:

from collections import Counter
 
from agentlab.tiny.charlm import TOOLCALL_TOOLS, toolcall_corpus
 
corpus = toolcall_corpus(n=1200, seed=0)
print(corpus[:250])
lm = CharNGram(order=8).fit(corpus)
print("tools and their arguments:", TOOLCALL_TOOLS)
Q: What is 51 times 28?
A: {"name": "calculator", "arguments": {"expression": "51*28"}}
Q: Weather for Oslo, please.
A: {"name": "get_weather", "arguments": {"city": "Oslo"}}
Q: Email dara@example.com about the report.
A: {"name": "send_email", "argu
tools and their arguments: {'get_weather': [('city', 'string')], 'calculator': [('expression', 'string')], 'search_web': [('query', 'string')], 'send_email': [('to', 'string'), ('subject', 'string')]}

Now sample 200 answers freely for one question and check each one: is it JSON, does it name a known tool, and does it pass exactly that tool’s arguments with the right types?

from agentlab.tiny.constrained import check_tool_call
 
PROMPT = "Q: What is the weather in Oslo?\nA: "
rng = np.random.default_rng(0)
free = [lm.generate(PROMPT, max_chars=120, rng=rng, stop="\n") for _ in range(200)]
verdicts = Counter(check_tool_call(s, TOOLCALL_TOOLS) for s in free)
print(verdicts)
for kind in ["not JSON", "wrong arguments"]:
    example = next(s for s in free if check_tool_call(s, TOOLCALL_TOOLS) == kind)
    print(f"{kind:16} {example}")
Counter({'wrong arguments': 98, 'not JSON': 53, 'ok': 49})
not JSON         {"name": "send_email", "arguments": {"to": "chen@example.com about volcanoes.
wrong arguments  {"name": "calculator", "arguments": {"to": "fay@example.com", "subject": "lunch"}}

Only about a quarter of the samples are usable. The model learned the shape of a tool call, but with an 8-character window it cannot remember, by the time it writes the arguments, which tool it named 30 characters earlier, so it mixes them. Large models fail far less often, but a failure rate of even 1% means a long agent run will meet one. There are two remedies: validate and ask again (Notebook 2c), or make invalid output impossible.

5. Constrained decoding

The idea: before each sampling step, ask a grammar which characters may come next, set the probability of every other character to zero, and renormalise. A tool call has a rigid skeleton, so the grammar is simple:

{"name": "<a tool name>", "arguments": {"<arg>": "<string>", ...}}
          \___ trie of ___/              \__ fixed by the chosen tool __/
             tool names                     values: any string, max 32 chars

ToolCallGrammar.allowed(prefix) returns the set of allowed next characters:

from agentlab.tiny.constrained import ToolCallGrammar
 
grammar = ToolCallGrammar(TOOLCALL_TOOLS)
for prefix in ['{"na', '{"name": "', '{"name": "s', '{"name": "send_email',
               '{"name": "calculator", "arguments": {"expression": "12',
               '{"name": "calculator", "arguments": {"expression": "12*7"}}']:
    allowed = grammar.allowed(prefix)
    shown = "".join(sorted(allowed)) if len(allowed) < 12 else f"<{len(allowed)} chars>"
    print(f"{prefix:58} -> {shown!r}")
{"na                                                       -> 'm'
{"name": "                                                 -> 'cgs'
{"name": "s                                                -> 'e'
{"name": "send_email                                       -> '"'
{"name": "calculator", "arguments": {"expression": "12     -> '<94 chars>'
{"name": "calculator", "arguments": {"expression": "12*7"}} -> ''

Where only one character is allowed, there is no decision to make: write it without asking the model. This “fast-forwarding” is why constrained decoding can be faster than free decoding. The decoding loop:

def constrained_decode(m, prompt, grammar, rng, temperature=1.0):
    out, forced, removed = "", 0, []
    while allowed := grammar.allowed(out):
        if len(allowed) == 1:
            out += next(iter(allowed))
            forced += 1
            continue
        p = m.probs(prompt + out)
        chars = sorted(c for c in allowed if c in m.stoi)
        mass = np.array([p[m.stoi[c]] for c in chars])
        removed.append(1 - mass.sum())  # probability the grammar took away
        out += chars[decode_step(np.log(mass), rng, temperature)]
    return out, forced, removed
 
 
rng = np.random.default_rng(0)
runs = [constrained_decode(lm, PROMPT, grammar, rng) for _ in range(200)]
print(Counter(check_tool_call(out, TOOLCALL_TOOLS) for out, _, _ in runs))
out, forced, removed = runs[0]
print(f"example: {out}")
share = np.mean([np.mean(r) for _, _, r in runs])
print(f"{forced} of {len(out)} characters forced; the grammar removed on average "
      f"{share:.1%} of the probability per sampled step")
Counter({'ok': 200})
example: {"name": "get_weather", "arguments": {"city": "Lima"}}
48 of 54 characters forced; the grammar removed on average 0.9% of the probability per sampled step

Every sample is now valid, and the model was consulted for only a handful of characters per call. The grammar also removed little probability on average: the model mostly wanted to write valid output anyway, and the mask only cut off its occasional mistakes.

Hosted APIs offer the same guarantee as “structured outputs” or “strict” tool schemas, and open-source servers implement it with libraries such as Outlines or XGrammar, which compile a full JSON Schema into this kind of mask over a vocabulary of 100,000 tokens rather than a few dozen characters. A token can span several grammar positions (one token might be ", "), which is what makes the real implementations hard.

Now the catch. Which tool did the constrained model choose for the weather question?

import json
 
chosen = Counter(json.loads(out)["name"] for out, _, _ in runs)
in_corpus = Counter(json.loads(line[3:])["name"] for line in corpus.splitlines()
                    if line.startswith("A: "))
for name in TOOLCALL_TOOLS:
    print(f"{name:12} chosen {chosen[name]:3}/200 times; "
          f"{in_corpus[name] / 1200:.0%} of the training examples")
get_weather  chosen  84/200 times; 41% of the training examples
calculator   chosen  42/200 times; 23% of the training examples
search_web   chosen  59/200 times; 26% of the training examples
send_email   chosen  15/200 times; 10% of the training examples

The choices follow how often each tool appears in the training data, not the question. When the model writes the tool name, its 8-character window holds name": ", and the word weather is far out of sight. The grammar guaranteed the form of the output; it could not supply the content. That is true of the real thing too: a strict schema guarantees parseable arguments, not correct ones. You still validate the values (Module 3) and evaluate the behaviour (Module 10).

6. A tiny model behind the agent interface

get_llm("tiny:toolcall") wraps this n-gram model and the grammar in the same BaseLLM interface as every other backend: it reads the tools from the request, builds the grammar from their schemas, and decodes a tool call. Hand it to the agent from Notebook 1:

from agentlab import Agent
from agentlab.display import show_trajectory
from agentlab.llm import get_llm
from agentlab.tools import tool
 
from agentlab.tiny.charlm import CITIES
 
# a weather table for every city the tiny model has seen, so its calls always succeed
WEATHER = {c.lower(): f"{8 + 2 * i}C" for i, c in enumerate(CITIES)}
 
 
@tool
def get_weather(city: str) -> str:
    """Current weather for a city."""
    return WEATHER[city.lower()]
 
 
@tool
def calculator(expression: str) -> str:
    """Evaluate an arithmetic expression such as '12*7'."""
    from agentlab.tools.builtins import safe_eval
 
    return str(safe_eval(expression))
 
 
tiny = nb.track(get_llm("tiny:toolcall"))
print(tiny.describe())
agent = Agent(model=tiny, tools=[get_weather, calculator], max_steps=4)
for question in ["What is the weather in Oslo?", "What is 12 times 7?"]:
    print(f"\n>>> {question}")
    show_trajectory(await agent.run(question))
tiny local model `tiny:toolcall` (a character n-gram trained in Notebook 2b, decoded under a tool-call grammar; it cannot read the question)

>>> What is the weather in Oslo?
[user] What is the weather in Oslo?
[agent -> get_weather] {"city": "Lima"}
    [get_weather ok] 14C
[agent] Result: 14C
--- status: complete, steps: 2

>>> What is 12 times 7?
[user] What is 12 times 7?
[agent -> get_weather] {"city": "Seoul"}
    [get_weather ok] 18C
[agent] Result: 18C
--- status: complete, steps: 2

The loop runs, every tool call parses and succeeds, and the answers are confidently about the wrong city, or the wrong tool altogether; any right answer would be luck. The agent code from Notebook 1 did not change at all: the model is a swappable part behind one interface. What a real model adds is the thing the n-gram lacks, the ability to read the whole request (the question, the tool descriptions, the results so far) when it chooses the next token. The rest of the course assumes such a model and builds the harness around it.

Try this

  • In section 3, generate with temperature=1.5 and with k=3. Which produces more invented words, and why does top-k with a small start to behave like greedy?
  • Give CharNGram order 30 and repeat the tool-choice count in section 5. A 30-character window reaches back into the question. Does the model now pick get_weather? What happens for a city that never appears in the training data?
  • Add a "number" argument to a tool (ToolCallGrammar supports ("x", "number")) and print grammar.allowed for a few prefixes inside the number. Which characters are allowed after -? After 3.?
nb.usage()
model callsinput tokensoutput tokenscost
4 (tiny: 4)≈ 560≈ 15≈ USD 0.0006 (reference price)