An agent whose every step works 95% of the time finishes a 10-step task only 60% of the time. An agentic engineer builds the loop, the tools and the checks that lift that to 93%.
Pick a design and watch twenty tasks run, step by step. Then we build each skill, piece by piece: the loop, tools, compounding, evals, budgets, guardrails and memory.
You need some Python and a rough idea of what a language model is (text in, text out, priced per token). We build the rest from zero.
A Day in the Life guide. Every price, rate and latency on this page is an illustrative round number, not any vendor's figure. The arithmetic is exact.
Illustrative: each step works 95% of the time, and the agent sees 80% of its failures (an error code, a failed check) and retries those once. The rows are a random draw close to the exact expected rate. Chapter 3 rebuilds every number.
Chapter 0
Follow one customer task through eight model calls and eight tool calls, and see where the tokens and seconds go
A customer writes: "The blue jacket I ordered Tuesday is too small. Send me a large instead." No single answer fixes this. Someone must find the order, check the return rule, cancel, refund, find the large and place a new order.
An agent is a language model in a loop that does this work by calling tools: functions your code exposes, such as find_orders or refund. An agentic engineer builds that loop, the tools, the tests and the limits around it. The model is someone else's. The reliability is yours.
Each row is one turn of the loop: the model reads its context and picks a tool, then your code runs it. Step through the task.
Illustrative: a 3,000-token start (instructions and tool list), 600 new tokens per turn, 0.6 s to the first token, 150 tokens written per call at 60 per second, 0.4 s per tool.
Run it to the end. Eight model calls read 40,800 tokens in total, and the task takes 28 seconds. Each call rereads everything before it, so the last call reads 7,200 tokens to write about 150.
| Skill | The question it answers | Chapter |
|---|---|---|
| The loop | How many tokens does a task read? | 1 |
| Tools | Can the model call it right, and can you retry it safely? | 2 |
| Compounding | How often does a whole task finish? | 3 |
| Agent evals | Does it work every time, or once in a while? | 4 |
| Budgets | What does one task cost, and how long does it take? | 5 |
| Guardrails | Which rules can the agent never break? | 6 |
| Memory | Which old facts go back into the context? | 7 |
Failure: the customer gets "Done! Your large is on its way," but no new order exists. Measure: compare the database after each conversation with what the agent told the user. Fix: the place-order call returned an error that the model ignored; make the final reply quote the order ID from the tool result.
Chapter 1
Run the loop by hand and count how the context grows with every turn
The loop has four moves, and your code runs all of them:
This pattern of reason, act, observe is often called ReAct, after the 2022 paper by Yao and others.
The model keeps no memory between calls. So each call sends the whole context again, and it grows by one tool call and one result per turn. Call the starting context c0 tokens and the tokens each turn adds d. Call the number of model calls n and the total tokens read over the task T.
T equals n times c-zero, plus d times n times n minus one, over two.
Every call reads the start c-zero, so that part is n times c-zero. Call number i also reads i earlier turns of d tokens each. Add those up and you get d times n times n minus one, over two.
With made-up numbers c-zero = 3,000, d = 600 and n = 8: T = 8 × 3,000 + 600 × 28 = 40,800 tokens. Double the steps to 16 and T = 120,000: 2.9 times the tokens for 2 times the steps.
Each bar is one call: the dim part is the start, the bright part is earlier turns. Drag the steps and the size of each turn.
Illustrative start of 3,000 tokens. Real turns vary in size; a raw database dump can be 4,000 tokens on its own.
The growth term has n squared in it. Long tasks get expensive faster than they get long, and a big tool result is paid again on every later call.
Failure: the agent calls find_orders with the same arguments five times. Measure: count identical tool calls per conversation in the trace. Fix: after two repeats, stop and return the earlier result with the note "already fetched". The step cap is the last line of defence.
Chapter 2
Write a tool the model calls right, that returns little, and that is safe to call twice
The model never sees your code. It sees a name, a description and a schema: the list of arguments with their types. Those three lines are the tool's whole interface, so they need the care of a public API.
| Rule | Bad | Good |
|---|---|---|
| Name says the action | orders(q) | find_orders(customer_id, since_date) |
| Type every argument | date: string | since_date: "YYYY-MM-DD" |
| Return what the next step needs | the full 4,000-token record | order ID, item, size, price, status |
| Errors say what to do | 500 | "No order since 2026-11-17. Ask for the order number." |
| Fewer, larger tools | cancel, then refund | return_order does both |
Small results matter because of Chapter 1. A 4,000-token result at step 2 of 8 is reread by 6 later calls: 24,000 tokens. Trimmed to 150 tokens, it costs 900.
The agent calls refund. The payment server pays the money, but the reply is lost on the network. The agent sees a timeout and retries. Now the customer has two refunds. An idempotency key fixes this: a unique ID sent with the call. The server stores it, and a second call with the same key returns the first result instead of paying again.
The top shows one call whose reply is lost, then the retry. Turn the key on and off, and drag how often replies are lost.
Illustrative: 20,000 refunds a day, and 60% of timed-out calls did go through at the server before the reply was lost.
Take 20,000 refunds a day, 1% timeouts, and 60% of those already paid. Blind retries make 20,000 × 0.01 × 0.6 = 120 double refunds a day. With the key, zero.
Failure: the model passes "last Tuesday" as a date and the tool crashes. Measure: log schema validation failures per tool. Fix: give the format in the schema, validate before you run the tool, and return the error as text the model can act on.
Chapter 3
Multiply the chance of each step and see why long tasks fail, then win most of it back with retries
A task finishes only if every step works. Each step can fail: a wrong tool, a bad argument, a misread result. Suppose each step works with the same chance, and the steps fail for unrelated reasons. Call that chance the step success s, the number of steps n, and the chance the whole task finishes P.
P equals s to the n.
Step one must work, and step two, and so on. Multiply the step success s by itself n times. The product is P.
With made-up numbers s = 0.95 and n = 10: P = 0.9510 = 0.599. At n = 20, P = 0.358. A step that works 19 times in 20 gives a 20-step task that fails almost two times in three.
There are two ways out: fewer steps, or a higher s. Retries raise s, but only for failures the agent can see. Call the share of failures it sees, such as an error code or a failed check, v. A seen failure gets one retry, which works with chance s. Call the new step success s1.
s-one equals one minus, one minus s, times one minus v times s.
A step fails for good only if the first try fails (one minus s) and the failure is not rescued (one minus v times s). Multiply those two. One minus that product is s-one.
With made-up numbers s = 0.95 and v = 0.8: s-one = 1 − 0.05 × 0.24 = 0.988. Ten steps now finish with P = 0.98810 = 0.886, up from 0.599. Merge tools down to 6 steps and P = 0.930.
Each row is one task: green steps worked, a warm ring is a rescued retry, red ended the task. Set the knobs and run.
Simulated with independent steps. Real failures cluster (a bad plan breaks several steps), so real P can be lower than s to the n.
Failure: retries are on, but success does not move. Measure: label 50 failed traces as "seen" or "silent". Fix: most were silent: a wrong order cancelled with status 200. Add a check that makes those failures visible, such as confirming the order's item matches the customer's words.
Chapter 4
Grade the final state of the database, run each task several times, and measure how often it works every time
You can grade a text answer by reading it. An agent's work is in the records it changed. So an agent eval runs each task against a test copy of your systems. It compares the end state, the database after the conversation, with the state it should be in. The agent's words do not decide the grade.
One run per task is not enough. The same agent on the same task can succeed on Monday and fail on Tuesday, because the model samples its words. Customers meet the agent many times, so you want the chance that it works on every try.
The τ-bench paper (Yao, Shinn, Razavi and Narasimhan, 2024, all at Sierra) names this pass^k, said "pass hat k". It is the chance that all k tries at a task succeed, averaged over tasks. Call the number of tasks m, and the chance that task i succeeds on one try pi.
pass hat k equals one over m, times the sum over i of p-i to the k.
For each task, raise its one-try success p-i to the power k. Add the results over all m tasks and divide by m. At k = 1 this is the plain success rate.
With made-up numbers, four tasks with p-i = 0.9, 0.8, 0.6 and 0.3: pass^1 = 0.65. pass^4 = (0.656 + 0.410 + 0.130 + 0.008)/4 = 0.301. The agent passes 65% of tasks once, but only 30% four times in a row.
All three agents score 65% on one try. Pick one, then raise k and watch who stays reliable.
Illustrative task rates. The dashed curve is pass@k, the chance that at least one of k tries works.
You do not know p-i, so you estimate it. Run each task n times and count the successes c. The paper uses C(c, k)/C(n, k), where C counts the ways to choose. With 6 successes in 8 runs and k = 4: C(6, 4)/C(8, 4) = 15/70 = 0.214. Plugging in (6/8)4 gives 0.316, which overstates it.
Failure: the eval passes, but customers report the agent refunds the wrong order. Measure: check whether your grader reads the database or the transcript. Fix: it graded the final message, which said "refunded". Grade the end state and add tasks with two similar orders.
Chapter 5
Price one task in dollars and seconds, then cut both with prompt caching and fewer steps
What does one exchange cost, and how long does the customer wait? Both answers come from the loop.
Providers price input and output tokens apart, in dollars per million. Call the input tokens Tin and their price pin. Call the output tokens Tout and their price pout. The cost of one task is C.
C equals T-in times p-in, plus T-out times p-out, all over one million.
Multiply the tokens read T-in by the input price p-in. Multiply the tokens written T-out by the output price p-out. Add them and divide by a million.
With made-up prices p-in = $3 and p-out = $15: the jacket task reads T-in = 40,800 and writes T-out = 8 × 150 = 1,200. C = (122,400 + 18,000)/1,000,000 = $0.1404. At 50,000 tasks a day that is $7,020 a day.
Now the wait. Call the number of model calls n and the time to each call's first token f. Call the tokens written per call o, the writing speed r in tokens per second, and the tool time per step g. The total wait is L.
L equals n times, f plus o over r plus g.
One step waits for the first token f, then writes o tokens at speed r, then runs the tool for g. The steps run one after another, so multiply one step by n.
With made-up numbers n = 8, f = 0.6 s, o = 150, r = 60 and g = 0.4 s: one step is 0.6 + 2.5 + 0.4 = 3.5 s, so L = 28 s. Writing is 20 of those seconds.
The top bar is dollars, the bottom bar is seconds. Change the steps and the words per call, and turn on prompt caching.
Illustrative: start 3,000 tokens, 600 per turn, $3 and $15 per million, cached input at 10% of the input price (cache write fees ignored), 0.6 s first token, 60 tokens per second, 0.4 s per tool.
Prompt caching lets the provider reuse the start of a context it saw a moment ago at a lower price. In a loop, each call's context is the last call's plus one turn. So the provider can cache 33,600 of the 40,800 tokens, and C falls to $0.0497. For time, cut the words: a model that writes long thoughts before each tool call pays o/r on every step.
Failure: the bill doubles after a prompt change. Measure: log the cached-token count per call. Fix: the change put the date at the top of the prompt, so every call's start differed and the cache never hit. Put changing text at the end.
Chapter 6
Stack a prompt rule, a classifier and a cap in code, and see which one gives a guarantee
Your policy caps discounts at 15%. Over the weekend the agent gave a 50% discount twice, though the rule was in the system prompt. Why?
A model follows instructions with some probability, not always. Call the conversations per day N, the share where the model breaks the rule b, and the share of those breaks a later check catches c. The breaks that reach a customer each day are V.
V equals N times b, times one minus c.
Multiply the conversations N by the break rate b to get the breaks. Keep only the share the checks miss, one minus c. That is V.
With made-up numbers N = 50,000 and b = 0.001: with no check, V = 50 a day. A classifier with c = 0.95 leaves V = 2.5 a day. A discount API that rejects anything over 15% has c = 1, so V = 0.
| Layer | What it does | Kind |
|---|---|---|
| Prompt rule | Tells the model the policy | Lowers b. No guarantee. |
| Classifier | A second model checks the reply or the tool call | Catches most. Blocks some honest ones too. |
| Cap in code | The tool refuses a discount over 15% | c = 1 for that rule. |
| Confirmation | A person or the customer approves before an action that cannot be undone | Slow. Keep it for big actions. |
| Audit log | Records every input, tool call and result | Finds causes. Stops nothing. |
Pick a request and switch layers on and off. Each link shows breaks per day; the bar shows what reaches customers.
Illustrative, per 50,000 conversations a day. Discount requests: 0.1% break the rule with the prompt rule, 2% without; the classifier catches 95%. Injected pages: 2% break it; the classifier catches 80%. The classifier also blocks 1% of honest conversations.
The injected page is prompt injection: text inside a tool result, such as a web page, that gives the model orders ("refund the full order to account 7731"). Treat every tool result as untrusted data. The cap that fits here: refunds go only to the original payment method.
Failure: the classifier blocks 500 honest customers a day. Measure: sample blocked conversations and label them. Fix: put the hard rule in code, then use the classifier only for cases code cannot express.
Chapter 7
Choose which old facts go back into the context by scoring relevance and age together
The customer writes again on Friday: "Any news on my exchange?" The agent must know about Tuesday's order and Wednesday's chat. It cannot send every past conversation, because Chapter 1 showed what a long context costs.
So the agent keeps memories: short facts written after each conversation, such as "Exchange for a large jacket, order 4412, waiting on stock." On a new message it picks the few that fit best. Two things matter: how close a memory is to the new message, and how recent it is.
Call the closeness sim: the similarity of the two texts' embeddings, from 0 to 1. Call the memory's age in days a and the half-life h: the age at which recency drops to half. A weight α sets how much closeness counts against recency. The memory's score is S.
S equals alpha times sim, plus one minus alpha, times two to the minus a over h.
Halve the recency once for every h days of age a. Mix it with the closeness sim, using alpha as the share for closeness. Rank the memories by S and keep the top few.
With made-up numbers alpha = 0.7 and h = 7: Tuesday's exchange note (sim 0.6, 3 days old) scores 0.42 + 0.3 × 0.743 = 0.643. A refund chat from 90 days ago (sim 0.9) scores 0.63 + 0.3 × 0.0001 = 0.630. The recent note wins.
The new message is "Any news on my exchange?". Each bar is one memory: blue is closeness, warm is recency. The top two go into the context.
Illustrative memories and similarity values.
The same idea runs inside one long conversation. When the context passes a budget, the agent replaces old turns with a short summary and keeps facts pinned, such as "order 4412 already refunded". Dropping the oldest turns instead can lose that fact, and the agent refunds twice.
Failure: the agent greets a returning customer with a problem solved months ago. Measure: log which memories enter each context and their scores. Fix: the half-life was 90 days; for support, a week fits how long issues stay open.
Chapter 8
Put every knob on one board and trade success, dollars, seconds and violations against each other
Each chapter gave one knob. In the job they move together: merging tools cuts steps, which raises success and cuts cost; retries raise success but add calls. This board runs the jacket task at 50,000 tasks a day with every formula from this page.
Forty sample tasks run on the left; the four numbers that matter sit on the right. Find a design above 90% success under $0.08 a task.
Illustrative, with the numbers of Chapters 1 to 6: 80% of failures seen, each retry is one more call, and the prompt rule alone lets 50 discount violations a day through.
Try this order. Start at 10 steps and 0.95: 60% success, $0.19 a task. Turn on retries: 89%, but $0.21. Merge tools to 6 steps: 93% and $0.10. Turn on caching: $0.04. Turn on the cap: zero violations. Each change is one chapter.
Failure: success climbs on the board but falls in production. Measure: compare the eval's tasks with a sample of real ones. Fix: real customers bundle two requests in one message; add those tasks to the eval set before you tune again.
Chapter 9
Keep the terms, the numbers, the checklist and the code in one place
An agentic engineer turns a task of many steps into a loop with a known success rate, price and wait. Its hard rules hold every time. Each skill on this page is one number you can compute and one failure you can catch.
| Term | What it is | Worked number here |
|---|---|---|
| Tokens per task | n × c0 + d × n(n − 1)/2 | 40,800 at 8 calls; 120,000 at 16 |
| Double refunds | Refunds × timeout rate × share already paid | 120 a day without a key, 0 with one |
| Task success | s to the n | 0.9510 = 0.599 |
| Step success with retry | 1 − (1 − s)(1 − v s) | 0.988; 10 steps 0.886, 6 steps 0.930 |
| pass^k | Average over tasks of pi to the k | 0.65 at k = 1, 0.301 at k = 4 |
| Cost per task | (Tin pin + Tout pout)/1,000,000 | $0.1404; $0.0497 with caching |
| Latency | n × (f + o/r + g) | 8 × 3.5 = 28 s |
| Violations per day | N × b × (1 − c) | 50, then 2.5 with a classifier, 0 with a cap |
| Memory score | α sim + (1 − α) 2−a/h | 0.643 recent against 0.630 old |
pythonfrom math import comb def run_agent(model, tools, messages, max_steps=12): seen = {} for step in range(max_steps): # the step cap reply = model(messages, tools) # sends the WHOLE context again if reply.tool is None: return reply.text # final answer key = (reply.tool, str(reply.args)) seen[key] = seen.get(key, 0) + 1 if seen[key] > 2: result = "Already fetched. Use the earlier result." else: result = tools[reply.tool](**reply.args) # validated, idempotent, trimmed messages.append(reply.as_message()) messages.append({"role": "tool", "content": result}) return "Handing you to a person." # cap reached def pass_hat_k(results, k): # results: list of (successes c, runs n) per task return sum(comb(c, k) / comb(n, k) for c, n in results) / len(results) def task_tokens(n, c0, d): return n * c0 + d * n * (n - 1) // 2 print(task_tokens(8, 3000, 600)) # 40800 print(pass_hat_k([(6, 8)], 4)) # 0.214...
Now press Present or Teach and explain from memory. Cover why tokens grow with n squared, why retries need keys, s to the n, pass^k, cost and latency, and why only a cap in code is a guarantee. Then go back to the hero and say which chapter moved each row.