The assistant this track builds
Every chapter in this track works on one program: Atlas, the help assistant of an invented online bookshop, Fernhill Books. Customers ask Atlas about deliveries, returns, gift wrapping and their own orders; Atlas answers from the shop's help pages, looks an order up when asked, and never promises anything the shop has not promised. It starts, in this chapter, as the nine-line version that every team ships first and regrets by Monday, and by chapter 08 it retrieves grounded answers with citations, calls a read-only tool with the customer's own identity, refuses to be talked into a refund, costs a known number of tokens per answer, and has an evaluation set that fails before a regression reaches a customer.
Two things to say before any code. This field moves fast: model names, prices, context sizes and library interfaces change between quarters, so this track names no provider as the choice, labels every number as a dated example, and was last checked in October 2026. And the examples are TypeScript under strict, run with a fake model so that nothing here needs a key; the ideas transfer to Python or any other language, and the chapter says where a library would differ. The fake is important enough to show first.
export type Role = "system" | "user" | "assistant" | "tool";
export interface Message {
role: Role;
content: string;
name?: string; // the tool's name, on a tool message
}
export interface ModelReply {
content: string;
}
export interface Model {
complete(messages: Message[], options?: { temperature?: number }): Promise<ModelReply>;
}
// A scripted stand-in for a provider. Every real API in wide use takes roughly
// this shape: an ordered list of role-tagged messages in, one message out.
export class FakeModel implements Model {
calls: Message[][] = [];
constructor(private readonly script: (messages: Message[]) => string) {}
async complete(messages: Message[]): Promise<ModelReply> {
this.calls.push(messages);
return { content: this.script(messages) };
}
}
const lastUser = (messages: Message[]): string =>
[...messages].reverse().find((m) => m.role === "user")?.content ?? "";
const fluentGuesser = new FakeModel((messages) =>
/refund/i.test(lastUser(messages))
? "Yes, Fernhill Books offers a full refund within 30 days of delivery on any order."
: "Happy to help with that.");
async function askAtlasV1(model: Model, question: string): Promise<string> {
return (await model.complete([{ role: "user", content: question }])).content;
}
console.log(await askAtlasV1(fluentGuesser, "Can I get a refund on a book I have already read?"));
// Yes, Fernhill Books offers a full refund within 30 days of delivery on any order.
What the fake says is scripted, and the chapter says so every time it matters. The scripted line above is the shape of a real failure: a fluent, confident, well-formatted answer, and false. Fernhill does not refund read books. A model does not know Fernhill's policy because nobody gave it one, and it has no concept of the difference between "I know this" and "this is what usually comes next"; it produces the most likely continuation of a question about refunds, which across everything it learned is a description of a typical shop's refund policy. The gap between fluent and correct is the subject of this whole track, and the messages array is where it is closed: nearly everything that follows is about what goes into that list, in what order, and where it comes from.
A prompt is an input with a spec
"Ask it nicely" is not engineering, and the reason is worth being precise about: there is nothing to review, nothing to version, nothing that fails the same way twice, and no way to state what the function is supposed to do. A prompt is the input to a function. Like any input, it deserves a spec, and the first part of the spec is a system message that sits before anything the customer types:
export const SYSTEM_PROMPT = `You are Atlas, the help assistant of Fernhill Books.
Rules:
- State a policy, price, delivery time or order fact only if it was given to you in this
conversation. Never rely on how other shops usually handle something.
- If you do not have enough information to answer, say so plainly and offer a human.
- Keep answers under four sentences unless the customer asks for more.
- Never confirm that a refund, credit or order change has been made. Only a human or an
explicit tool result can confirm that.`;
export function withSystem(history: Message[], question: string): Message[] {
return [{ role: "system", content: SYSTEM_PROMPT }, ...history, { role: "user", content: question }];
}
// A fake that honours a "say so" rule when it is present: scripted, to show the shape.
const ruleFollower = new FakeModel((messages) => {
const system = messages.find((m) => m.role === "system")?.content ?? "";
const hasRule = /say so plainly/.test(system);
if (/refund/i.test(lastUser(messages))) {
return hasRule
? "I don't have Fernhill's refund policy in front of me, so I won't guess. Shall I connect you with a human?"
: "Yes, you can get a full refund within 30 days.";
}
return "Happy to help with that.";
});
console.log((await ruleFollower.complete(withSystem([], "Can I get a refund?"))).content);
// I don't have Fernhill's refund policy in front of me, so I won't guess. Shall I connect you with a human?
Notice what changed and what did not. The model still knows nothing about Fernhill's policy. What changed is that the rule against guessing sits in the highest-priority position of the conversation, ahead of whatever the customer asks, and a model follows the instruction that is in front of it more reliably than one it was never given. A system prompt can tell a model how to behave; it cannot hand the model facts it never had, which is why chapter 02 exists.
Three roles do almost all the work. system is the standing rules, written once by you and never by the customer. user is what the human typed. assistant is what the model said last time, and this one matters more than it looks, because a model has no memory between requests. What looks like remembering the last three exchanges is you resending the whole transcript, system prompt included, on every call:
export async function turn(model: Model, history: Message[], question: string): Promise<{ reply: string; history: Message[] }> {
const messages = withSystem(history, question);
const reply = (await model.complete(messages)).content;
return { reply, history: [...history, { role: "user", content: question }, { role: "assistant", content: reply }] };
}
let history: Message[] = [];
for (const q of ["Do you gift wrap?", "And for a box set?", "Can I get a refund?"]) {
({ history } = await turn(ruleFollower, history, q));
}
console.log(history.length, ruleFollower.calls.at(-1)?.length); // 6 6
The third call carried six messages: the system prompt, two earlier pairs, and the new question. A conversation that has run forty turns is forty turns of tokens sent and paid for on turn forty-one, whether or not anything past turn five still matters. That is the reason the next section exists.
Two more levers belong in the spec. A few-shot example, a worked user/assistant pair inserted after the system prompt, shows the shape of a good refusal, and two or three of these anchor tone harder than another paragraph of rules, because the model is a next-token predictor and showing it the next tokens after "I don't know" is a more direct lever than describing them. And temperature, on models that expose it, sets how far the model may stray from its single most likely next token. Near zero, the same question tends to get the same answer; turned up, answers vary, which suits brainstorming and not a shop stating its delivery times. Atlas runs low on purpose where it can: an assistant that gives two answers to the same question in one afternoon has a trust problem before it has any other.
The blocks in this track use top-level await, which Node runs in a module file; a .mts file or a package marked as a module is enough, and the fake model means no network call is ever made. In Python the message list is the same list of dictionaries; the TypeScript here gains an interface that the compiler checks, so a tool message without a name fails to build rather than to run.
Tokens: what you pay for and what fits
A well-meaning engineer's first idea for "give it the real policy" is the most direct one: paste every help page into the system prompt. Fernhill's help centre is about eighty pages; the invented bill rose by a large multiple within a week, and the answers slowed. Both trace to one unit. A model does not read words; it reads tokens, roughly a word or a word fragment each, and every provider charges by token, for what goes in and for what comes out. Counts differ between tokenizers, and between generations of one provider's: as of October 2026, documentation for one provider's recent models says the same text produces up to about thirty percent more tokens than that provider's earlier models, which is why the estimator below is a budgeting aid and the provider's own counter is the figure to trust. Every page, on every question, means paying to process the whole help centre to answer "do you gift wrap".
// A rule of thumb, not a tokenizer: about three quarters of a word per token for
// ordinary English. Real tokenizers differ by model and by language, and a real
// count comes from the provider's own tokenizer.
export function estimateTokens(text: string): number {
const words = text.trim().split(/\s+/).filter(Boolean).length;
return Math.ceil(words * 4 / 3);
}
const helpCentre: string[] = Array.from({ length: 80 }, (_, i) =>
`Help page ${i + 1}. ` + "Fernhill Books ships within two working days to mainland addresses. ".repeat(60));
const perPage = estimateTokens(helpCentre[0]);
const everything = helpCentre.reduce((n, page) => n + estimateTokens(page), 0);
console.log(perPage, everything); // 804 64320
console.log(estimateTokens("Do you gift wrap?") + estimateTokens(SYSTEM_PROMPT)); // 129
Sixty-four thousand tokens to answer a four-word question whose answer lives in one paragraph of one page, against about one hundred and thirty for the question and the rules alone. Put a dated example on it, with the caveat that prices change by the quarter and this is October 2026 arithmetic with a made-up rate: at one dollar per million input tokens, that is about six cents per question instead of about a hundredth of a cent, five hundred times the cost, before the output tokens are counted. The ratio is the point; the rate is not.
The context window is the second constraint, and it is a hard ceiling rather than a bill. Every model holds a fixed maximum of tokens across the system prompt, the whole history, anything else in the request and the reply it is about to write. Go over it and the request does not slow down; it normally fails with an error that names the limit. Some providers and libraries offer an option that trims for you instead, oldest content first, and a hand-written trimmer that treats the system prompt as just another old message can push the rules out first, so Atlas loses its own rules mid-conversation. Windows have grown every year and will keep growing, which changes the ceiling and does not change the arithmetic: a bigger window makes "paste everything" possible, not cheap, and burying the one relevant paragraph in sixty thousand irrelevant tokens also makes it measurably harder for the model to weight the right part.
The honest fix is sending less: only the handful of paragraphs relevant to this question, chosen at request time. That is a search problem, and chapter 02 starts with why keyword search is the wrong search.
Budgeting a conversation
The same discipline applies to history. A thread that has run twenty turns does not need every turn resent forever. The unglamorous fix is to fold everything older than the last few turns into a short recap and replay that instead, trading a little fidelity on old context for a budget that stops growing:
export function fitToBudget(history: Message[], budgetTokens: number, keepTurns = 2): Message[] {
const keep = history.slice(-keepTurns * 2);
const older = history.slice(0, history.length - keep.length);
if (older.length === 0) return history;
const recap = "Earlier in this conversation: " + older
.filter((m) => m.role === "user")
.map((m) => `the customer asked "${m.content}"`)
.join("; ") + ".";
const folded: Message[] = [{ role: "assistant", content: recap }, ...keep];
const total = folded.reduce((n, m) => n + estimateTokens(m.content), 0);
return total <= budgetTokens ? folded : folded.slice(-keepTurns * 2);
}
const long: Message[] = [];
for (let i = 1; i <= 10; i++) {
long.push({ role: "user", content: `Question number ${i} about delivery to the islands` });
long.push({ role: "assistant", content: `Answer number ${i}, two working days plus the ferry.` });
}
const trimmed = fitToBudget(long, 400);
console.log(long.length, trimmed.length, trimmed[0].content.slice(0, 60));
// 20 5 Earlier in this conversation: the customer asked "Question n
console.log(long.reduce((n, m) => n + estimateTokens(m.content), 0), trimmed.reduce((n, m) => n + estimateTokens(m.content), 0));
// 230 169
The recap here is built by string code, which is honest for a chapter and crude for a product: it cut the history by about a quarter, because it still lists every earlier question. A real Atlas asks the model to write the recap, which costs one short call and produces a shorter, better summary. Either way the shape holds: a fixed budget, the newest turns verbatim, the rest compressed, and a hard fallback that drops the recap rather than the rules when even the recap does not fit. Retrieved passages and conversation history compete for the same budget, and chapter 05 returns to the split between them once retrieval is in the mix.
What to carry forward
A model produces the likely continuation, not the true one, and the messages array is the whole interface. The system prompt is the spec: standing rules, an explicit permission to say "I don't know", a ban on confirming actions. History is replayed on every call, so a conversation's cost grows with its length until something folds it. Tokens are the unit of cost and the unit of the ceiling; estimate them, measure them with the provider's tokenizer, and send less rather than buying a bigger window. Every number in this chapter is a dated example from October 2026 and the fake model's words are scripted; the shapes are what to keep. Chapter 02 gives Atlas something true to say.