Agents and Safety
A language model maps text to text: it has no memory beyond its context, no environment, and no actions. An agent puts the model in a loop with the world: it observes, reasons, acts through tools, remembers, and improves. This chapter follows that progression (structure, reasoning, tools, learning from experience, many agents) and ends with what it takes to make autonomous agents safe.
14.1 From Language Models to Agents
There are three stages in how LLMs are used:
- language model: text in, text out;
- language agent: the LLM sits in a feedback loop with an external environment (e.g. SayCan, Inner Monologue);
- cognitive language agent: the LLM also manages internal state through reasoning, retrieval, and learning (e.g. ReAct, Reflexion, Voyager).
A classical ancestor. A production system is a set of condition → action rules that repeatedly rewrite a string or a world state (Post, 1943; Newell and Simon, 1972). Cognitive architectures such as Soar (1987) wrap one with sensors, control flow, a working memory, and long-term procedural, semantic, and episodic memories, and run a decision cycle: propose, evaluate, select, apply. They needed hand-written rules and worked only in logical domains.
An LLM lifts both limits. A production rewrites \(X\to X\,Y\); an LLM samples a continuation \(Y\sim P(Y\mid X)\). Each LLM call is a stochastic production, and prompting methods (few-shot prompting, retrieval augmentation, self-critique) are fixed sequences of productions. An agent chooses the sequence on the fly, in interaction with an environment.
Definition 14.1 (Cognitive Architecture for Language Agents) The CoALA framework (Sumers, Yao, Narasimhan, and Griffiths, 2024) describes a language agent by three components:
- memory: a working memory for the current cycle, plus long-term procedural memory (the LLM weights and the agent’s code), semantic memory (facts about the world and itself), and episodic memory (past experiences);
- action space: external grounding actions that affect the world (robot control, dialogue, digital APIs) and internal actions: reasoning (read and write working memory with the LLM), retrieval (bring long-term memory into working memory), and learning (write to long-term memory: store episodes, distill knowledge, update code or weights);
- decision making: a repeated cycle in which reasoning and retrieval propose and evaluate candidate actions, one is selected and executed, and the loop begins again.
The framework gives a shared vocabulary for very different agents, and a checklist for building new ones:
| agent | grounding | internal actions |
|---|---|---|
| SayCan | physical (robot) | none: the LLM scores a fixed set of skills |
| ReAct | digital (search, web) | reasoning |
| Voyager | Minecraft | reasoning, retrieval, learning (a growing skill library) |
| Generative Agents | social sandbox | episodic and semantic memory, reflection |
| Tree of Thoughts | none | deliberate propose / evaluate / select by search |
14.1.1 The Agent Control Loop
A single prompt cannot hold an agent’s whole history, which grows past any context window, yet believable behavior needs long-term coherence: remembering, generalizing, and re-planning as the world changes. The control loop bridges a stateless model and a continuously acting agent by deciding what to remember, what to retrieve, and what to do next.
Generative agents (Park et al., 2023) simulate a small town of characters with the loop perceive → memory stream → retrieve → reflect → plan → act, all in natural language.
- Memory stream. Every observation is stored with a natural-language description, a creation time, and a last-access time.
- Retrieval. Memories are ranked by a weighted sum of three scores, each scaled to \([0,1]\): recency (exponential decay \(0.995^{h}\) over the game hours \(h\) since last access), importance (rated \(1\)–\(10\) by the LLM when stored: cleaning the room \(2\), asking someone out \(8\)), and relevance (cosine similarity between the memory’s and the query’s embeddings). Naive summaries of the stream give vague answers; selective retrieval gives specific, in-character ones.
- Reflection. When the importance of recent events sums past a threshold (about \(150\), two or three times a game day), the agent asks the LLM for salient questions about its \(100\) most recent memories, retrieves evidence for each, and writes higher-level insights with citations. Reflections go back into the stream, forming a tree of increasingly abstract thoughts. Without reflection, an agent asked whom to spend time with picks the person it meets most often rather than a true intellectual peer.
- Planning and reacting. Plans are generated top-down (a daily agenda, then hour-long chunks, then 5–15 minute actions) and stored as memories. At each step the agent continues, re-plans, or reacts to a new observation. Without plans, a character eats lunch at 12:00, 12:30, and again at 1:00.
The query is “What are you looking forward to this week?”. Take equal weights and three memories:
| memory | hours since access | recency \(0.995^h\) | importance | relevance | score |
|---|---|---|---|---|---|
| cleaned the room | 1 | 0.995 | 0.2 | 0.1 | 1.30 |
| asked a neighbor about a trip | 100 | 0.606 | 0.8 | 0.2 | 1.61 |
| planned a party with a colleague | 24 | 0.887 | 0.4 | 0.9 | 2.19 |
The most recent memory ranks last: it is trivial and irrelevant. The party memory wins on relevance, though it is a day old. Because retrieval refreshes the last-access time, frequently useful memories stay recent, while unused ones fade unless they are important.
14.2 Reasoning and Acting
LLMs go beyond answering directly by producing intermediate thoughts (chain of thought), searching over alternative thoughts (tree of thoughts), and interleaving thoughts with actions in an environment (ReAct).
14.2.1 Chain of Thought
Scaling alone did not solve arithmetic, commonsense, and symbolic reasoning: few-shot prompting barely improved with size on these tasks, and fine-tuning on written rationales required costly annotations. Chain-of-thought prompting (Wei et al., 2022) combines the two ideas: the few-shot examples are \(\langle\)input, chain of thought, output\(\rangle\) triples, where a chain of thought is a series of intermediate natural-language reasoning steps. No fine-tuning is needed.
- An emergent ability of scale: it does not help, and often hurts, small models; gains appear at about \(10^{11}\) parameters. PaLM 540B went from 18% to 57% on the GSM8K grade-school math benchmark with 8 exemplars, a new state of the art without task-specific training. Gains are largest on the hardest problems.
- It also helped commonsense tasks (75.6% versus a prior best of 69.4% on StrategyQA) and enabled length generalization on symbolic tasks such as concatenating last letters, solving longer instances than in the examples.
- Ablations: an equation alone, the same number of extra tokens without meaning (dots), or reasoning placed after the answer does not help: the sequential reasoning itself matters.
- Limits: a chain can be wrong yet reach a right answer; the benefit requires very large models; whether the model “really reasons” remains open.
Definition 14.2 (Self-Consistency) Self-consistency (CoT-SC) samples \(k\) independent chains of thought at nonzero temperature and returns the majority vote over their final answers.
Different reasoning paths that agree on an answer make it more reliable; self-consistency trades extra samples for accuracy.
14.2.2 Tree of Thoughts
Within one chain, the model still makes token-level, left-to-right decisions: no exploration, no lookahead, no backtracking. In dual-process terms, plain generation is a fast “System 1”; deliberate problem solving needs a “System 2” that keeps alternatives and searches, as in Newell and Simon’s view of problem solving as search through a tree. Tree of Thoughts (ToT, Yao et al., 2023) frames a problem as search over a tree of thoughts (coherent intermediate steps), with the LM both generating and evaluating branches. Four design choices define it:
- thought decomposition: steps small enough to sample diversely, big enough to evaluate;
- thought generator: sample i.i.d. thoughts from a CoT prompt (rich spaces such as paragraphs), or propose several in sequence with a “propose” prompt (constrained spaces such as words or equations);
- state evaluator: have the LM rate each state independently (a value, or sure / maybe / impossible), or vote among states;
- search algorithm: breadth-first search keeping the best \(b\) states per level, or depth-first search with pruning and backtracking.
Make \(24\) from \(4,9,10,13\) with \(+,-,\times,\div\). Each thought is one equation on the remaining numbers:
- step 1: \(13-9=4\), leaving \(\{4,4,10\}\);
- step 2: \(10-4=6\), leaving \(\{4,6\}\);
- step 3: \(4\times6=24\). ✓
At each level the LM proposes candidate equations and evaluates whether the remaining numbers can still reach \(24\) (“sure”, “maybe”, “impossible”); BFS keeps the best \(b=5\) states. On 100 hard games with GPT-4:
| method | success |
|---|---|
| input–output prompting | 7.3% |
| chain of thought | 4.0% |
| CoT-SC (\(k=100\)) | 9.0% |
| ToT (\(b=1\)) | 45% |
| ToT (\(b=5\)) | 74% |
About 60% of failed chains of thought already went wrong at the first step: left-to-right decoding commits early and cannot recover.
- ToT also improved creative writing (plan, vote, write, vote; humans preferred it over CoT 41 to 21) and \(5\times5\) mini crosswords (word-level success from 15.6% with CoT to 60%, using DFS with pruning and backtracking, both of which proved essential).
- Generality: input–output prompting, CoT, CoT-SC, and self-refinement are special cases of ToT, and every component can be swapped. Cost: about \(5\)–\(100\times\) more tokens than CoT.
14.2.3 ReAct
Reasoning alone (CoT) is a closed box: it cannot check facts, so it hallucinates and propagates errors. Acting alone (WebGPT, SayCan) predicts actions without reasoning abstractly about goals. People interleave the two all the time: while cooking, we track progress, handle surprises, and decide when to look something up.
Definition 14.3 (ReAct) ReAct (Yao et al., 2023) augments the agent’s action space \(\mathcal A\) with the space of language, \(\hat{\mathcal A}=\mathcal A\cup\mathcal L\). An action in \(\mathcal L\) is a thought: it changes the context but produces no observation from the environment. The model, prompted with a few example trajectories, interleaves thoughts, actions, and observations.
- Useful thoughts decompose goals and make plans, inject commonsense (“a knife is probably in a drawer”), extract information from observations, track subgoals, and handle exceptions. Reasoning decides what to do; acting retrieves information that updates the reasoning.
- Knowledge tasks (a Wikipedia API with
search,lookup,finish): CoT failures were mostly hallucinations (56%), while ReAct stayed grounded but sometimes searched uninformatively. Switching between ReAct and CoT-SC by confidence was best (HotpotQA exact match \(29.4\to35.1\); FEVER accuracy \(56.3\to64.6\)). - Decision making: 71% success on the ALFWorld household tasks versus 45% for acting without thoughts and 37% for an imitation-learning agent trained on \(10^5\) trajectories; on WebShop, \(+10\) points over the previous best.
- Trajectories are interpretable, and a human can edit a single wrong thought mid-trajectory to steer the agent back on track.
14.3 Tool Use
LLMs struggle with up-to-date facts, exact computation, and reliable API execution. Tool use lets them call external functions, observe the results, and continue.
Definition 14.4 (Toolformer Filtering Criterion) Toolformer (Schick et al., 2023) teaches a model to use tools by self-supervision. It samples candidate API calls \(c_i\) at positions \(i\) of ordinary text, executes them to get results \(r_i\), and keeps a call only if it makes the following tokens easier to predict. With \(L_i(z)\) the weighted loss on the tokens after position \(i\) when \(z\) is inserted before them,
\[ L_i^+=L_i\bigl(c_i\to r_i\bigr),\qquad L_i^-=\min\bigl(L_i(\varnothing),\;L_i(c_i\to\varnothing)\bigr),\qquad \text{keep iff}\quad L_i^--L_i^+\ge\tau_f. \]
The model is then fine-tuned on the text with the useful calls inserted inline as <API> call → result </API>.
Text: “Of the 1400 participants, 400 passed the test, i.e. 29%.” Insert <API> Calculator(400/1400) → 0.29 </API> before “29%”. Suppose (illustrative numbers) the loss on “29%” is \(2.3\) with no call, \(2.2\) with the call but no result, and \(0.4\) with call and result. Then \(L^-=\min(2.3,2.2)=2.2\) and \(L^--L^+=1.8\ge\tau_f=1\): the call is kept. The second term in \(L^-\) ensures that the result, not merely the act of writing a call, is what helps.
- Results: GPT-J (6.7B) with five tools (question answering, calculator, Wikipedia search, translation, calendar) beat the 25× larger GPT-3 on factual and math benchmarks, with no loss in plain language modeling. Tool use is emergent: models below about 775M parameters cannot exploit the tools.
- Limits: no chained or interactive tool use, sensitivity to prompt wording, poor sample efficiency, and no notion of a tool’s cost.
Gorilla (Patil et al., 2023). Even the strongest LLMs hallucinate API calls: invented models, wrong libraries, fabricated argument names. Gorilla fine-tunes LLaMA-7B on 16,450 instruction–API pairs covering 1,645 machine-learning APIs (generated with GPT-4 from documentation, with only 18 hand-written examples).
- Retriever-aware training appends retrieved API documentation to the prompt, so the model learns to read and trust it, and adapts when APIs change after training.
- Evaluation by AST sub-tree matching: many APIs are functionally equivalent, so unit tests are unsuitable; instead, parse the generated call and check whether it matches a database entry on the required arguments. A call matching no API is a hallucination; a real API used wrongly is an error.
- Zero-shot it beat GPT-4 by 20.4 points in API accuracy with the fewest hallucinations, and it respected constraints such as “under 10M parameters and over 70% ImageNet accuracy”.
ToolLLM (Qin et al., 2023) scales to 16,464 real REST APIs in 49 categories, with instructions using one tool, several tools in a category, or several across a collection.
- DFSDT (depth-first search decision tree): ReAct follows one path, and one mistake poisons the whole chain. DFSDT lets the model abandon a node (“finish by giving up”) and expand a sibling, raising ChatGPT’s pass rate from 35.3% to 63.8%, enough to annotate 126k hard training trajectories.
- A contrastively trained API retriever recommends the top 5 of 16k APIs, so the user need not pick them; an LLM-based evaluator (ToolEval) agreed with human judgments 80–87% of the time.
- The resulting 7B model matched ChatGPT, trailing only GPT-4, and generalized to unseen APIs.
14.4 Learning from Experience
Agents tend to forget past interactions and repeat their mistakes. The remedy is to turn experience into reusable memory, without (or in addition to) updating weights.
- Reflexion (Shinn et al., 2023): verbal reinforcement learning. An actor (a ReAct or CoT agent) attempts the task; an evaluator scores the trajectory (exact match, heuristics, unit tests, or an LLM judge); a self-reflection model turns the score and trajectory into a verbal lesson (“I searched for the wrong entity; next time search for the director first”), stored in a small long-term memory (1–3 entries) and placed in the next attempt’s context. A free-form reflection pinpoints which step failed, a finer-grained credit-assignment signal than a scalar reward: a “semantic gradient” that lives in the prompt, not the weights. Results: \(+22\) points on ALFWorld over ReAct (130 of 134 tasks solved), \(+20\%\) on HotpotQA, and 91% pass@1 on HumanEval coding versus 80% for GPT-4. Removing the reflection step while keeping retries loses most of the gain. Limits: it depends on the LLM’s self-evaluation, can stall, and has a tiny memory.
- Voyager (Wang et al., 2023): a lifelong learning agent in Minecraft, using GPT-4 by prompting only, which acts by writing code against a game API.
- An automatic curriculum proposes the next task from the agent’s state and history, favoring novelty.
- A skill library stores each successful program as a function indexed by an embedding of its description; the top-5 most similar skills are retrieved for new tasks, and complex skills call simpler ones (crafting an iron pickaxe reuses mining and smelting iron). Skills stored as code are persistent, interpretable, and transferable, and avoid the catastrophic forgetting of updating weights.
- Iterative prompting refines code using game feedback, execution errors, and a separate GPT-4 self-verification critic; a skill is committed only after verification (removing it cuts discovered items by 73%).
- ReasoningBank (2025) distills generalizable strategies from both successes and failures, judged by the agent itself with an LLM judge (no ground truth). Each memory item has a title, a one-line description, and a few sentences of distilled insight; the loop is retrieve → act → extract → consolidate. Memory-aware test-time scaling spends extra compute on more exploration per task (parallel trajectories contrasted with each other, or sequential self-refinement), and better memory and more exploration reinforce each other. Gains reached \(+20\%\) relative success with 16% fewer steps on web-browsing and software-engineering benchmarks; learning from failures helped, whereas memory built only from successful workflows got worse when failures were added.
14.5 Multi-Agent Systems
Multi-agent systems have moved from emergent coordination, to programmable collaboration, to real workflows.
- Emergent tool use from competition (Baker et al., 2020). In a physics simulator, a team of hiders gets \(+1\) if no hider is seen and \(-1\) otherwise; seekers get the opposite. The agents can move, grab, and lock boxes and ramps, but nothing rewards using objects. Trained with PPO at large scale, they went through six phases, each a new task for the other team: running and chasing; hiders building forts from boxes; seekers using ramps to climb in; hiders locking the ramps away; seekers “surfing” on boxes; hiders locking every box first. Competition creates the curriculum. Scale was essential (batches of 16k never converged; 64k reached ramp defense in about 34 hours), as was a value function that sees the whole state during training.
- AutoGen (Wu et al., 2023) builds LLM applications from conversable agents (backed by an LLM, a human, or tools such as a code executor) that exchange messages, plus conversation programming: what each agent computes and who speaks when, controlled by prompts (“reply TERMINATE when done”) or Python. Assistant + executor pairs solved 69.5% of MATH problems versus 55.2% for GPT-4 alone; adding a grounding agent raised ALFWorld success by about 15 points; a commander–writer–safeguard trio cut application code from 430 to 100 lines.
- A multi-agent research system (Anthropic, 2025): open-ended research is path-dependent and cannot be scripted in advance. An orchestrator (lead agent) plans, saves the plan to memory, and spawns subagents with explicit objectives, output formats, and tool guidance; each searches in parallel in its own context window and returns condensed findings; a citation agent attaches sources. It beat a single agent by 90.2% on an internal research evaluation, at about \(15\times\) the tokens of a chat, so it pays only for valuable, parallelizable tasks. Lessons:
- prompting: teach the lead to delegate and to scale effort to the query; design tools with distinct purposes and clear descriptions; search broad first, then narrow;
- evaluation: start with about 20 representative queries; grade with an LLM judge and a rubric; keep humans in the loop for biases evals miss (such as preferring SEO-optimized sites to authoritative sources); judge end states rather than every step;
- production: agents are stateful and errors compound, so checkpoint and resume rather than restart; trace agent decisions; roll out new versions gradually so running agents are not killed mid-task.
14.6 Safety, Alignment, and Security
Agents act autonomously with tools, so their failures have real consequences. Three related goals:
- safety: will it cause harm? Avoid data loss, financial loss, privacy leaks, and physical danger;
- alignment: is it following the right intent? Pursue human goals and values, not instructions taken blindly;
- security: can it act safely within system boundaries? Protect systems and data from misuse, unauthorized access, unsafe tool calls, and leakage.
14.6.1 Constitutional AI
RLHF (Ch. 10) needs tens of thousands of human harmfulness labels, which are costly, private, and hard to interpret, and harmless models tend to become evasive (“I can’t answer that”). Constitutional AI (Bai et al., 2022) replaces the human harmlessness labels with a short list of natural-language principles, a constitution, and lets AI help supervise AI.
Definition 14.5 (Constitutional AI) Training has two stages.
- Supervised stage (SL-CAI). Sample responses to red-teaming prompts from a helpful-only model; ask the model to critique each response according to a randomly drawn principle, then to revise it, repeating several times; fine-tune on the revised responses (mixed with helpful responses).
- RL stage (RL from AI feedback, RLAIF). For each prompt, sample two responses from the SL-CAI model and ask a feedback model which is less harmful under a sampled principle, using its probabilities as soft labels. Train a preference model on these AI labels plus human helpfulness labels, and run RL against it.
- Harmlessness improves steadily with the number of revisions; averaging over many principles makes the preference model more robust; letting the feedback model reason step by step helps, with its probabilities clamped to 40–60% so the policy cannot exploit overconfident labels.
- Results: a Pareto improvement, more harmless than RLHF at every level of helpfulness, and non-evasive: the model engages with sensitive requests and explains its objections. Overtraining can still produce harsh or boilerplate replies, a form of Goodhart’s law. Natural-language principles make the training objective transparent and editable.
14.6.2 Emulated Red-Teaming
Testing agents for safety by hand means implementing every tool and sandbox, setting up initial states, and reading every trajectory; rare, severe failures are easy to miss, and future tools have no sandbox at all. ToolEmu (Ruan et al., 2024), inspired by simulators for autonomous driving, uses an LM as the sandbox.
- Emulation. GPT-4 emulates tool executions and their state from the tool specifications alone, so testing has no real side effects and covers tools that do not exist yet (traffic control, IoT, robots).
- Adversarial emulation. Most random scenarios are benign, so an adversarial emulator instantiates states that make the listed risks likely (e.g. two similarly named medications when the agent must pick one).
- Threat model: underspecified but benign user instructions (ambiguous or missing details) that the agent must resolve safely.
- Evaluators: an LM-based safety evaluator scores risky actions by likelihood and severity, and a helpfulness evaluator scores task completion.
- Failure modes found: fabrication and unwarranted assumptions (made-up email addresses or account numbers), misreading instructions (granting permanent instead of one-day access), erroneous execution (running
rm -rf /*), and ignoring risks (switching a pedestrian light on while vehicles have green). Six of seven terminal failures reproduced in a real shell; setting up a test took about 15 minutes instead of 8 hours. - Benchmark: 36 toolkits, 311 tools, and 144 test cases over 9 risk types; 68–72% of the flagged failures were judged real by humans. The best agents (GPT-4, Claude 2) still failed in about 39–44% of cases. Explicit safety instructions in the prompt cut GPT-4’s failures to about 24% and improved helpfulness.
- Safety is not inaction: an agent that does nothing is perfectly safe and useless. The goal is agents that are capable and safe.
14.7 Supplementary Notes
14.7.1 Key Results
- Definition 14.1: CoALA: memory (working, procedural, semantic, episodic), actions (reasoning, retrieval, learning, grounding), decision cycle.
- Generative agents: retrieval score = recency \(0.995^h\) + importance + relevance; reflection and hierarchical plans.
- Definition 14.2: self-consistency = majority vote over \(k\) sampled chains of thought.
- Tree of Thoughts: thought decomposition, generator, evaluator, search; Game of 24 from 4% (CoT) to 74% (ToT, \(b=5\)).
- Definition 14.3: ReAct action space \(\hat{\mathcal A}=\mathcal A\cup\mathcal L\).
- Definition 14.4: keep a tool call iff \(L_i^--L_i^+\ge\tau_f\).
- Reflexion, Voyager, ReasoningBank: experience stored as verbal lessons, code skills, or distilled strategies.
- Definition 14.5: Constitutional AI: critique–revision SFT, then RL from AI feedback.