Ask which other device can control the program the Apple Remote was built for. Answering alone, a model says iPod; reasoning alone, it says iPhone, iPad and iPod Touch. Reasoning and searching in turns, it finds the answer, keyboard function keys, in 4 rounds of thought and action, after one search that finds nothing.
Switch between the four ways to answer, and press Run. Warm text is what the model writes; teal text is what the search tool sends back. Then we build each part from zero: retrieval, RAG, the loop of thought and action, memory, tools, and how to grade an agent.
You need a little Python, what a probability is and what a language model does (Lectures 7 and 8). We build the rest from zero.
Lecture 10, "Agents, Tool Use, and RAG", of Stanford CS224N, Natural Language Processing with Deep Learning (Winter 2026, Diyi Yang and Yejin Choi; this lecture’s slides, "RAG and Language Agents", are Diyi Yang’s). Its readings are ReAct (Yao et al., 2023), the tutorial "Language Agents: Foundations, Prospects, and Risks" (Su, Yang, Yao and Yu, EMNLP 2024), RAG (Lewis et al., 2020) and Toolformer (Schick et al., 2023). Before: Lecture 9, Efficient Adaptation. Next: Lecture 11, Benchmarking and Evaluation.
The question and the four traces are Figure 1 of the ReAct paper (Yao et al., 2023), with the observations shortened. The model was PaLM-540B with a few example traces in its prompt. One question is an example, not a benchmark: Chapter 4 has the paper’s averages.
Chapter 0
Sort six requests by what each one needs beyond the model’s weights, and count how few it can answer alone
A language model answers from its weights. Everything it knows was fixed when training stopped. It cannot read today’s news, open your files or run a program. When it does not know, it still writes a fluent answer.
Each yellow line is a request. The mark says whether the model can answer it. Switch tools on, one at a time.
Illustrative. The six requests are ours. Which tool each request needs is the point, not the exact list.
How much does missing knowledge cost? Liu et al. (2023) asked GPT-3.5-Turbo 2,655 questions from Natural Questions. With no documents, a setting called closed book, it answered 56.1% right. Given the one Wikipedia passage that holds the answer, it answered 88.3% right. One right page is worth 32.2 points.
Arithmetic is a second wall. 4,738,291 × 8,234,107 = 39,015,595,091,137. A calculator gets all 14 digits every time. A model writes the digits one token at a time and must get every carry right, so long products often go wrong.
The lecture’s answer has two parts. Let the model look things up, which is retrieval. Then let it act: call tools, read the results, and go again. A system that takes observations from an environment and chooses actions in it is a language agent.
Symptom: confident, fluent answers about events after training or about documents the model never saw.
Measure: closed-book accuracy against accuracy with the right page: 56.1% against 88.3%.
Fix: retrieve the page and put it in the prompt (Chapter 1).
Chapter 1
Score every passage against the question, by shared words or by meaning, and keep the top few
Open-domain question answering gives you a question and a huge collection, such as all of Wikipedia, with no hint where the answer is. The classic system has two parts (Chen et al., 2017). A retriever picks K passages. A reader reads them and writes the answer.
The oldest retrievers count shared words. BM25 scores a passage higher when it holds the question’s words, and rare words count more. It is fast. It fails when the passage uses different words for the same thing: "largest skyscraper" against "the tallest structure ever built".
A dense retriever maps text to vectors. One encoder turns the question into a vector; another turns each passage into one. Texts that mean the same land close together, even with no word in common.
Purple dots are passage vectors; the yellow arrow is the question’s vector. Pick a question, then switch between shared words and meaning. The tick marks the passage that holds the answer.
Illustrative toy. Real dense vectors have hundreds of dimensions (DPR uses 768); we draw 2. The word score adds a rarity weight for each shared word, a simplified BM25 with no length term.
Call the question x and a passage z. The question encoder gives a vector q(x); the passage encoder gives d(z). The score is their dot product:
s of x and z equals q of x dot d of z.
Multiply the question vector q(x) and a passage vector d(z) coordinate by coordinate, and add. That sum is s(x, z). Score every passage this way and keep the K highest.
From the toy: q(x) = (0.8, 0.6) for "largest skyscraper". The Burj Khalifa passage has d(z) = (0.9, 0.3): s = 0.72 + 0.18 = 0.90. A weather passage has (−0.2, 0.9): s = −0.16 + 0.54 = 0.38. The Burj passage ranks first, with no word in common with the question.
DPR (Karpukhin et al., 2020) trains two BERT encoders on question and passage pairs. The other questions’ passages in the batch serve as free wrong answers. On Natural Questions, the right passage was in DPR’s top 20 for 78.4% of questions, against 59.1% for BM25. The passage encoder runs once, ahead of time, so a search over 21 million passages is a fast nearest-neighbour lookup.
Symptom: the answer is in the collection, but the system says it cannot find it.
Measure: recall at K, the share of questions whose right passage is in the top K: 59.1% against 78.4% at K = 20.
Fix: a dense or a hybrid retriever, and check recall before you blame the reader.
Chapter 2
Turn retrieval scores into weights, let each passage vote on the answer, and swap the index to update the facts
The reader could take only the top passage. If the retriever ranks it wrong, the answer is wrong. RAG, retrieval-augmented generation (Lewis et al., 2020), hedges. It reads the top K passages and mixes their answers, each weighted by how much the retriever trusts that passage.
Each teal passage gets a blue weight from its score. Below it, the answer the model gives after reading that passage. Drag the top passage’s score, then swap in a newer index.
Illustrative toy: we made up the council, the names and the probabilities. The other two scores stay at 1.0 and 0.5.
Name the parts. Call the question x, a retrieved passage z and the answer y. The retriever gives each passage a probability pη(z | x): a softmax of the scores from Chapter 1. The generator gives the answer a probability pθ(y | x, z) after reading that one passage.
p of y given x is about the sum, over z in the top K, of p-eta of z given x, times p-theta of y given x and z.
For each retrieved passage z, take the generator’s probability of the answer y and multiply it by the passage’s weight pη(z | x). Add the K products. That total is p(y | x).
From the toy: scores 2.0, 1.0 and 0.5 give weights 0.629, 0.231 and 0.140. The passages give "Ana Ruiz" probabilities 0.9, 0.2 and 0.5. So p(Ana Ruiz | x) = 0.566 + 0.046 + 0.070 = 0.682. The top passage carries most of it.
Lewis et al. pair a DPR retriever over 21 million Wikipedia passages with a BART-large generator (400M parameters), and K of 5 or 10. They train both on question and answer pairs alone. One passage per whole answer is RAG-Sequence; RAG-Token lets each token draw on a different passage. On Natural Questions, RAG-Sequence scored 44.5 exact match, against 34.5 for T5-11B answering closed book.
The second gain is freshness. The authors swapped the December 2018 Wikipedia index for a December 2016 one, with no retraining. They asked about 82 world leaders who changed in between. With the matching index, RAG answered 70% right for 2016 leaders and 68% for 2018 leaders. With the wrong index, it scored 12% and 4%.
Symptom: the system gives last year’s answer.
Measure: accuracy on facts that changed: 4% when the index is older than the question.
Fix: rebuild or swap the index. The model needs no retraining.
Chapter 3
Move the right passage through twenty retrieved ones, and watch accuracy sag in the middle
If the right passage might rank fifth, why not give the model 20 passages, or 50? Liu et al. (2023) tested this. Each question came with 20 Wikipedia passages: one holds the answer, and 19 retrieved ones do not. They moved the right one from first place to last.
Teal blocks are the 20 passages in the prompt; the ticked one holds the answer. Drag it, and read the pink accuracy. The dashed lines are no passages at all and the right passage alone.
Real numbers: Liu et al. (2023), Tables 1 and 6, 20 passages, 2,655 Natural Questions queries. They measured positions 1, 5, 10, 15 and 20 only, so the slider stops there.
GPT-3.5-Turbo answered 75.8% right with the passage first and 63.2% with it last. At position 10 it scored 53.8%: 2.3 points below its closed-book score of 56.1%, as if the passages were not there. With the right passage alone, a setting called oracle, it scored 88.3%. The curve is a U: models use the start and the end of their context best.
More passages also stop paying early. The retriever’s recall keeps rising as K grows, but the reader’s accuracy levels off. For GPT-3.5-Turbo, 50 passages instead of 20 added only about 1.5 points.
RAG promises one more thing: citations. Search engines that answer with generated text add links to sources. Liu, Zhang and Liang (2023) audited four of them. On average, their citations fully supported only 51.5% of generated sentences, and only 74.5% of citations supported their sentence. The model writes the citations too.
Symptom: adding passages makes the answers worse.
Measure: accuracy by the position of the right passage: 75.8% first, 53.8% at position 10.
Fix: retrieve fewer, better passages; rerank so the best one comes first; check each claim against its citation.
Chapter 4
Be the policy: choose each next step, and see which steps change the world and which only add to the model’s notes
An agent works in a loop. At each step it gets an observation from its environment and chooses an action. In ReAct’s question answering setup, the environment is a small Wikipedia API with three actions. Search[entity] returns a page’s first sentences. Lookup[string] finds the next sentence with that string. Finish[answer] ends the task.
Before ReAct, a model could reason in words (chain of thought, Lecture 9) or act, but not both. ReAct (Yao et al., 2023) adds a thought: an action written in plain language. A thought changes nothing outside. It only adds to the model’s context: a plan, a fact pulled from an observation, or a fix for a failed search.
You play the model on the hero’s question. Each button adds one step; only searches get a reply from Wikipedia. Finish right in as few steps as you can.
Illustrative toy on the hero’s trace. Think writes the next useful thought from what you have seen; Finish answers from your notes.
Write the loop down. Call the action at step t at and the observation ot; the question is the first observation. The context ct is everything so far. The policy π, here a frozen language model, reads the context and writes the next action:
a-t is drawn from pi of a-t given c-t, where c-t is o-one, a-one, and so on, up to a-t-minus-one and o-t.
Put the question and every past action a and observation o into the prompt: that is ct. Let the model write the next action at. If it is a search, run it and append the result as the next observation. If it is a thought, append it, with no result.
In the hero’s trace, after the second search the context holds the question, 2 thoughts, 2 searches and 2 observations: 7 items. Thought 3 adds an 8th item and calls nothing. The trace ends with 12 items.
On HotpotQA, multi-hop questions, ReAct alone scored 27.4 exact match against chain of thought’s 29.4. On FEVER, fact checking, it scored 60.9 against 56.3. The best HotpotQA score, 35.1, combined them: ReAct first, then a vote over chains of thought if ReAct got stuck. In the ALFWorld household game, ReAct’s best run succeeded 71% of the time, against 45% with no thoughts.
The authors read sampled failures by hand. Hallucinated facts caused 56% of chain of thought’s HotpotQA failures and none of ReAct’s. But 47% of ReAct’s came from reasoning errors such as repeating a step, and 23% from searches that returned nothing useful.
Symptom: the agent repeats the same search, or stops with a guess.
Measure: the cause of each failure, read from the traces by hand.
Fix: a step limit, a fallback to chain of thought, and a better search tool.
Chapter 5
Sample many reasoning paths and take the most common answer, then see when the vote backfires
A thought can still be wrong. The lecture shows fixes that spend more samples or more tries, with no new training.
Self-consistency (Wang et al., 2023) samples n chains of thought at a temperature above zero. It reads off each final answer and returns the most common one. Wrong paths tend to go wrong in different ways. Right paths tend to agree.
The blue bars are how often one path ends in each answer; 18 is right. Set the number of paths and sample. The pink curve is the chance the majority is right.
Illustrative toy: a word problem whose answer is 18, with made-up answer chances. We compute the curve exactly over all outcomes, with ties split evenly.
Call the answer of path i ai. The vote picks the answer that the most paths reach:
a-hat equals the argmax over a of the sum over i from one to n of one-if a-i equals a.
Sample n paths. For each candidate a, count the paths whose answer ai equals it. Return the candidate with the biggest count as â.
With made-up numbers: one path ends in 18 (right) with chance 0.5, and in 17 or 21 with chances 0.3 and 0.2. One path is right half the time. The majority of 3 is right with chance 0.56, of 9 with 0.70, and of 41 with 0.92.
On GSM8K maths word problems, PaLM-540B rose from 56.5% with one greedy chain of thought to 74.4% with a vote over 40 paths.
Reflexion (Shinn et al., 2023) learns from failure in words. After a failed try, the agent writes a short note on what went wrong, and reads it on the next try. ReAct with Reflexion completed 130 of 134 ALFWorld tasks. On HumanEval coding problems it reached 91% pass@1, against the 80% reported for GPT-4. The lecture also shows agents that debate to agree (Du et al., 2023) and an orchestrator that hands subtasks to specialist agents (Magentic-One).
Symptom: more samples, the same wrong answer.
Measure: majority accuracy as n grows. With one tempting error (0.45 against the right 0.40), it falls from 0.40 at n = 1 to 0.36 at n = 41.
Fix: a vote helps only when the right answer is the single most likely one. Otherwise add a check: a tool, a test or a verifier.
Chapter 6
Score each memory for recency, importance and relevance, and pull the top few into the prompt
The context window is an agent’s working memory, and it is small. The lecture sorts long-term memory by what it holds. Episodic memory stores experiences. Semantic memory stores knowledge. Procedural memory stores skills; Voyager, a Minecraft agent, stores its skills as code.
Generative agents (Park et al., 2023) put 25 characters in a small town called Smallville. Each agent writes every event it perceives to a memory stream. No context holds a whole day of events, so before each step the agent retrieves the few that matter.
Each memory gets three scores, each scaled to the range 0 to 1 across the memories. Recency shrinks by a factor of 0.995 for every game hour since the memory was last retrieved. Importance is a rating from 1 to 10 that the language model gives when it writes the memory: "cleaning up the room" got 2. Relevance is the cosine similarity between the memory’s embedding and the current question’s.
Each teal line is a memory; its blue bar stacks recency, importance and relevance, each times its weight. The top three go into the prompt. Change the question, then the weights.
Illustrative toy in the style of Park et al. (2023): the memories, hours and ratings are ours. The decay factor 0.995, the min-max scaling and the weights of 1 are the paper’s.
Call the three scaled scores rec, imp and rel, and give each a weight α:
Score equals alpha-rec times rec, plus alpha-imp times imp, plus alpha-rel times rel.
For each memory, multiply rec, imp and rel by their weights α and add. Sort the memories by score. Put the top ones that fit into the prompt.
From the toy, for the party question: Isabella’s invitation was last retrieved 20 hours ago, so its raw recency is 0.99520 = 0.905. The oldest memory has 0.835 and the newest 0.995, so rec = (0.905 − 0.835) / (0.995 − 0.835) = 0.435. It has the top rating and the top cosine, so imp = 1 and rel = 1. Score = 0.435 + 1 + 1 = 2.435, the highest.
The agents also write reflections, higher-level notes, once the summed importance of recent events passes 150. MemGPT (Packer et al., 2024) borrows from operating systems. With function calls, the agent moves text between its context and outside storage, as an OS moves pages between memory and disk.
Symptom: the agent forgets a promise, or keeps bringing up breakfast.
Measure: whether the memory the question needs ranks in the top K. With recency alone, the top three for the party question are breakfast, a tidy room and chocolates.
Fix: weigh relevance and importance with recency, and write reflections that summarize.
Chapter 7
Insert a candidate tool call, measure whether its result makes the next words easier to predict, and keep only the calls that pay
A tool call is text the model writes in a fixed format: a tool name and its arguments. A program outside the model spots the call, runs the tool and pastes the result into the context. Today’s APIs describe each tool by a name, a description and a JSON schema for its arguments. The lecture also shows ToolkenGPT, which gives each tool its own learned token.
Where should calls go? Toolformer (Schick et al., 2023) lets the model label its own training text. It samples candidate calls where it would likely start one and runs them. It keeps a call only if the result makes the following tokens easier to predict.
Measure "easier" with a loss. Take a text x1 to xn, a candidate position i, and a prefix z for the model: the call with its result, or nothing. Score the tokens from i on, with weights w that fade by 0.2 per token:
L-i of z equals minus the sum over j from i to n of w sub j-minus-i times log p-M of x-j given z and x-one-to-j-minus-one.
Give the model prefix z. For each token xj after position i, take minus the log of its probability and multiply by its weight w. Add them: that is Li(z).
From the toy, with no call, the next five tokens get probabilities 0.05, 0.30, 0.70, 0.60 and 0.50. L = 0.333 × 3.00 + 0.267 × 1.20 + 0.200 × 0.36 + 0.133 × 0.51 + 0.067 × 0.69 = 1.505.
Pick a candidate call. Blue bars are the next tokens’ probabilities with the call and its result; grey outlines are the best without the result. Then move τ.
Illustrative toy probabilities. The sentence and the QA call are from the Toolformer paper’s examples; the weights and the default τf = 1.0 are the paper’s.
Now compare. Call the loss with the call and its result Li+. Call the smaller of two other losses Li−: no call at all, or the call with its result left out. Keep the call if it lowers the loss by a threshold τf:
L-i-minus minus L-i-plus is at least tau-f.
Work out the loss three ways: with no call, with the call alone, and with the call and its result. Take L− as the better of the first two. If L− minus L+ is at least τf, keep the call in the training text.
From the toy: the QA call gives L+ = 0.208. Without the result, the best is min(1.505, 1.445) = 1.445. The gap 1.237 is at least 1.0: keep. The calculator call Calculator(6853 / 2) has a gap of −0.074: discard.
The authors fine-tuned GPT-J (6.7B parameters) on text labelled this way, with five tools: QA, Wikipedia search, a calculator, a calendar and a translator. On ASDiv maths word problems, accuracy rose from 7.5% to 40.4%, above GPT-3 (175B) at 14.0%. On date questions it rose from 3.9% to 27.3%. It cannot chain tools, and over a million documents gave only a few thousand useful calculator calls.
Symptom: the model calls tools everywhere, or never.
Measure: the gap L− − L+ for each candidate call.
Fix: tune τf: lower keeps weak calls, higher keeps only clear wins.
Chapter 8
Run a hundred agents on a task of many steps, and see small step errors compound, and checks win them back
The lecture ends by building a coding agent. At its simplest it is a loop. The model proposes an action. You run it in an environment, such as a bash shell. You show the model the output. Repeat. Three functions do the work: query_lm, parse_action and execute_action (the Field Guide has the code).
Long loops have a cost. Call the chance that one step succeeds p and the number of steps n. If steps fail independently, the whole task succeeds only if every step does:
P of success equals p to the n.
Multiply the step success chance p by itself n times. Every extra step multiplies in another p, so P(success) shrinks with every step.
With made-up numbers: p = 0.9 and n = 10 give 0.910 = 0.349. An agent right on 9 of 10 steps finishes about a third of 10-step tasks. At p = 0.99 it finishes 0.904.
Each tile is one agent working through the steps. Green tiles finished; red tiles failed a step. Set the step success and the task length, press Run, then turn on checks.
Illustrative simulation with independent steps. Real errors cluster, and a retry is not always independent of the first try. The formulas are exact for this simulation.
Feedback changes the arithmetic. A coding agent sees test output and error messages. Suppose it notices a failed step with chance d and retries once. A step now succeeds if it works the first time, or if it fails, the failure is caught, and the retry works:
p′ = p + (1 − p) × d × p = 0.9 + 0.1 × 0.8 × 0.9 = 0.972, and 0.97210 = 0.753
With p = 0.9 and d = 0.8, ten steps finish 75% of the time instead of 35%. The price is 1 + (1 − p) × d = 1.08 model calls per step, 8% more. That is why agent benchmarks give agents a real environment to observe: tests, errors and pages are the feedback that catches a bad step.
Symptom: an agent that gets most single steps right rarely finishes long tasks.
Measure: step success and task length together: at p = 0.9, 20 steps finish 12% of the time.
Fix: shorter plans, a check after each step (tests, error messages), retries and a step limit.
Chapter 9
Grade four patches for one bug by matching a reference and by running the tests, and see where each grader goes wrong
Agents act in many environments. The lecture lists coding agents (files and a terminal), web agents (a browser), computer-use agents (screenshots, keyboard and mouse) and robots. Each environment fixes what the agent can observe and what it can do.
Grading is hard. Tasks are open-ended, many paths are valid, and success is hard to script. So the strongest benchmarks grade the outcome. SWE-bench (Jimenez et al., 2024) takes 2,294 real GitHub issues from 12 Python repositories. The agent edits the code; the grader runs tests. The issue’s fail-to-pass tests must now pass, and the tests that passed before must still pass.
The bug: slugify("Hello World") returns "Hello-World", not "hello-world". The agent wrote four warm patches. Switch the grader and compare its marks with a person’s.
Illustrative toy bug and patches. The grading rule, fail-to-pass tests plus the tests that passed before, is SWE-bench’s.
At release, the best model on SWE-bench, Claude 2 with BM25 retrieval of files, resolved 1.96% of issues: about 45 of 2,294. Given the right files instead, it resolved 4.8%. WebArena (Zhou et al., 2024) has 812 tasks on four self-hosted websites; its best GPT-4 agent succeeded 14.41% of the time, against 78.24% for people. OSWorld (Xie et al., 2024) has 369 tasks on real desktops; the best model succeeded 12.24% of the time, against people’s 72.36%. These are release-time numbers. Agents have improved fast since, so check the current leaderboards.
Training data is the other bottleneck. Human demonstrations are slow and costly, so the lecture shows synthesis. SWE-smith (Yang et al., 2025) builds runnable environments and task instances for Python repositories: 50k instances from 128 repositories. Fine-tuned on traces from strong models that solved them, the open SWE-agent-LM-32B resolved 40.2% of SWE-bench Verified in one try.
Symptom: a patch passes every test but does not fix the bug, because it hard-codes the test’s input.
Measure: the share of passing patches that a person rejects on review.
Fix: more and hidden tests, and a person who reads a sample of passing patches.
Chapter 10
Keep the parts, the numbers and the code, and see where to go next
A model alone answers from frozen weights and cannot act. Retrieval gives it pages: a retriever scores passages, and RAG mixes the answers of the top few, weighted by trust. More pages stop helping past a point, and models use the middle of a long context worst. An agent adds a loop: think, act, observe, repeat, with memory outside the context and tools it learns to call. Long loops compound errors, so agents need feedback, and we grade them by running their work.
| Part | What it adds | Key idea | Watch for |
|---|---|---|---|
| Retriever | the right page from a big collection | score = question vector · passage vector | low recall; questions in different words |
| RAG | answers grounded in several pages; fresh facts | mix answers, weighted by retrieval probability | stale index; unsupported citations |
| ReAct loop | look-ups and actions between thoughts | thoughts are actions that only change the context | repeated steps; empty searches |
| Self-consistency, Reflexion | better reasoning with no training | vote over paths; notes from failed tries | a tempting wrong answer wins the vote |
| Memory | a past larger than the context | recency + importance + relevance | trivial recent memories crowd out key ones |
| Tools | exact answers and real actions | keep a call if its result lowers the loss | calls everywhere; unsafe actions |
| Number | Value | Where |
|---|---|---|
| GPT-3.5-Turbo closed book, right passage alone | 56.1%, 88.3% | Chapter 0 |
| Right passage in the top 20, BM25 against DPR (Natural Questions) | 59.1%, 78.4% | Chapter 1 |
| RAG-Sequence against closed-book T5-11B (Natural Questions, exact match) | 44.5, 34.5 | Chapter 2 |
| RAG with a matching index, with the wrong index | 70% and 68%; 12% and 4% | Chapter 2 |
| Right passage first, tenth, last of 20 (GPT-3.5-Turbo) | 75.8%, 53.8%, 63.2% | Chapter 3 |
| Sentences fully supported by citations; citations that support | 51.5%; 74.5% | Chapter 3 |
| HotpotQA exact match: chain of thought, ReAct, combined | 29.4, 27.4, 35.1 | Chapter 4 |
| ALFWorld success: no thoughts, ReAct (best of 6 runs) | 45%, 71% | Chapter 4 |
| GSM8K: one chain of thought, vote over 40 paths (PaLM-540B) | 56.5%, 74.4% | Chapter 5 |
| Toolformer on ASDiv: GPT-J, Toolformer, GPT-3 | 7.5%, 40.4%, 14.0% | Chapter 7 |
| Toy: 10 steps at p = 0.9, without and with checks | 0.349, 0.753 | Chapter 8 |
| At release: SWE-bench, WebArena, OSWorld (people) | 1.96%; 14.41% (78.24%); 12.24% (72.36%) | Chapter 9 |
The core as code: dense retrieval, the RAG mix, and the slides’ minimal coding agent loop.
python import numpy as np, re, subprocess def retrieve(q_vec, passage_vecs, k=5): scores = passage_vecs @ q_vec # s(x, z) = q(x) . d(z) for every passage top = np.argsort(-scores)[:k] w = np.exp(scores[top] - scores[top].max()); w /= w.sum() # p_eta(z | x): softmax over the top k return top, w def rag_answer_prob(w, p_answer_given_passage): # p(y | x) = sum_z p(z | x) p(y | x, z) return float(np.dot(w, p_answer_given_passage)) print(rag_answer_prob(np.array([.629, .231, .140]), np.array([.9, .2, .5]))) # 0.682 # The minimal coding agent: a big loop (query_lm is your model call) def parse_action(reply): # the command inside the reply's ```bash block m = re.search(r"```bash\n(.*?)\n```", reply, re.S) return m.group(1) if m else None def execute_action(cmd): # run it; the output is the next observation r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=60) return r.stdout + r.stderr def agent(task, query_lm, max_steps=30): messages = [{"role": "user", "content": task}] for _ in range(max_steps): # a step limit stops loops that never end reply = query_lm(messages) messages.append({"role": "assistant", "content": reply}) cmd = parse_action(reply) if cmd is None or cmd.strip() == "submit": return reply messages.append({"role": "user", "content": execute_action(cmd)})
Run agents that execute commands in a sandbox, never on a machine with data you cannot lose.
The lecture closes on what is still open: agents that need human judgment to grade, tasks with many valid paths, and evaluation beyond task success. Lecture 11 takes up benchmarking. On the data side, synthesized environments such as SWE-smith and training on agents’ own traces are how open models now learn to act.
Now teach it: press Present or Teach. Explain how RAG weighs passages, why a ReAct thought brings back no observation, and why 0.9 per step is not enough. Then go back to the hero, choose Act only, and say which step it needed a thought for.