Module 23

Reasoning, Agents and Tool-Augmented Systems

How can learned models, search, tools, and memory be combined to solve complex multistep problems?

lessons
31
duration
54 h 35 min
concepts
169
available in English
31 / 31
completed by you
0 of 31

Where it fits

Overview

Treat the LLM as a component within a system and study four levers that turn it into a multistep problem solver: inference-time compute (chain of thought, repeated sampling, outcome and process verifiers, tree search, and reasoning models), tools (function calling, sandboxed code execution, and learning to use tools), retrieval (BM25, search embeddings, exact and approximate vector search using LSH, IVF, PQ, and HNSW built from scratch, reranking, and RAG), and memory and control (context management, planning, workflows, and multi-agent systems). The module concludes with statistically rigorous agent evaluation, prompt-injection security, and learning from environmental feedback. Everything runs locally without paid APIs, using open 0.5B to 8B models served by llama.cpp or Transformers on 8 GB of VRAM.

Why it matters

This module turns the models from m20 and m21 into systems that act: agents that read a repository, execute code, consult a document collection, and verify their proposals. It provides criteria for choosing when to spend inference compute instead of using a larger model, building retrieval rather than relying on an opaque vector database, and evaluating agents with error bars rather than demonstrations. It connects to AlphaZero through value-guided search, new algorithm research through LLM-guided evolutionary search, and AI security in m30.

Lessons 31

  1. 01Operational review: the language model as a policy and local inferenceReview decoder-only LLMs as stochastic policies over continuations. Build a local Transformers and quantized GGUF inference stack, budget VRAM, and construct a reproducible call harness with caching, logging, and token accounting. GPUReview90 min
  2. 02Chain of thought: reasoning by generating intermediate stepsFormalize chain of thought as a latent variable to marginalize, study when intermediate reasoning helps, build an audited answer extractor, and use interventions to measure whether written steps faithfully reflect model computation. GPUCore90 min
  3. 03Repeated sampling and aggregation: self-consistency, voting and coverageStudy repeated inference sampling and aggregation: best-of-N, self-consistency, weighted and universal voting, pass@k coverage and selection. Derive when voting converges, why aggregate accuracy can be nonmonotonic and how task difficulty affects coverage. GPUCore100 min
  4. 04Rigorous measurement of stochastic systems: variance, reliability and costMeasure stochastic reasoning and agent systems by separating task and run variation, clustering uncertainty by task, comparing paired systems, planning sample sizes, and reporting reliability alongside cost-accuracy frontiers. GPUCore110 min
  5. 05Verifiers: checking is easier than solvingStudy the gap between generating and verifying, exact verifiers, outcome reward models trained on sampled solutions, and generative verifiers. Quantify how imperfect verification caps best-of-N accuracy and proxy overoptimization can make extra samples hurt true outcomes. GPUCore110 min
  6. 06Step-by-step verification: process reward modelsCompare process and outcome supervision: stepwise reward models can prune incorrect paths before the final answer. Generate step labels with Monte Carlo rollouts, interpret them as completion-policy values, and compare ways to aggregate step scores. GPUAdvanced100 min
  7. 07Inference-time search: step-level beam search, tree of thoughts and MCTSFormulate reasoning as search over partial solutions. Implement PRM-guided stepwise beam search, Tree of Thoughts with BFS and DFS, and MCTS with PUCT, then compare them with best-of-N at equal compute on exactly verifiable tasks such as Countdown and the game of 24. GPUAdvanced120 min
  8. 08Inference scaling laws and compute-optimal test-time allocationFit empirical inference-time scaling laws, account for training and inference FLOPs together, optimize compute allocation across task difficulty, and experiment with explicit reasoning-length control through budget forcing in a small reasoning model. GPUAdvanced100 min
  9. 09Self-training for reasoning: STaR, expert iteration and ReST-EMStudy STaR rationalization, expert iteration, rejection sampling, and ReST-EM on reasoning traces. Implement the LoRA loop, compare teacher trace distillation, and measure filtering bias, lucky answers, and diversity. GPUAdvanced100 min
  10. 10Reasoning models: training recipe and reinforcement learning dynamicsStudy reasoning-model training recipes and dynamics: cold starts, reinforcement learning, rejection sampling, distillation, difficulty-based problem selection, and switchable thinking modes. Reproduce a small R1-Zero-style Countdown training run and analyze its behavior. GPUAdvanced110 min
  11. 11Frontier: what reasoning models learn and how to think betterInvestigate open questions about reasoning models: behaviors in long chains, whether reinforcement creates new capabilities or concentrates existing ones, overthinking, continuous latent reasoning and chain monitorability. Reproduce two small-scale analyses and practice critical reading. GPUResearch90 min
  12. 12Tool calling and structured outputsStudy structured tool calls as a software interface: JSON schemas, chat tool messages, execution and observation, interface design, validation and repair, selection among tools, constrained-decoding distortion, and protocols such as MCP. Build a local tool-calling benchmark and MCP server. GPUCore110 min
  13. 13The agent loop: ReAct, trajectories and controlFormalize an agent as a policy over text observations in a POMDP, implement ReAct without frameworks, analyze error composition and recovery over long horizons, and design step and token limits, stopping criteria, tool-error handling, and trajectory logging. GPUCore100 min
  14. 14Code execution: the interpreter as a universal toolWriting and executing code lets a model delegate exact calculations, manipulate data, and check its solutions. Study program-aided reasoning (PAL), code as an agent's action space (CodeAct), isolated execution with time, memory, file, and network limits, and feedback-guided repair compared with resampling under comparable computational budgets. GPUCore100 min
  15. 15Planning and problem decomposition with language modelsStudy decomposition from least to most, plan-then-execute with replanning, on-demand decomposition, and dependency graphs with parallel execution. Compare direct language-model planning with classical planning and generate-and-validate approaches, and measure when planning helps. GPUAdvanced100 min
  16. 16Lexical retrieval: inverted indexes, TF-IDF and BM25Build an inverted index, derive BM25 from probability ranking and probabilistic relevance, study frequency saturation and length normalization, and implement ranking metrics using relevance judgments. GPUCore90 min
  17. 17Embeddings for search: dense retrieval and bi-encoder trainingStudy dense retrieval with bi-encoders, pooling and normalization, asymmetric query/document encoding, contrastive training with in-batch and mined hard negatives, and Matryoshka embeddings. Evaluate a small embedding model against BM25. GPUCore110 min
  18. 18Exact vector search and locality-sensitive hashingImplement exact blocked nearest-neighbor search, reduce maximum inner product to nearest-neighbor search, and study locality-sensitive hashing, SimHash collision probability, band amplification, and approximate-neighbor guarantees. GPUAdvanced100 min
  19. 19Compressed vector search: IVF and product quantizationBuild compressed vector search with an IVF coarse quantizer, product quantization and asymmetric distance tables, then combine residual IVF-PQ with exact reranking. Study score-aware anisotropic quantization and measure configurations against exact FAISS search. GPUAdvanced110 min
  20. 20Proximity graphs: NSW, HNSW and production vector searchStudy greedy proximity-graph search, HNSW hierarchy and diversity pruning, DiskANN, filters, deletions and updates. Implement HNSW, compare with exact search and libraries, and apply ANN benchmarking with recall, memory and latency tradeoffs. GPUAdvanced115 min
  21. 21Reranking and hybrid retrievalFirst-stage retrieval is cheap and approximate; the final quality is decided by a second stage that is more expensive and only sees a few hundred candidates. Cross-encoders that read query and document together are studied, the late interaction of ColBERT, the learned sparse retrieval of SPLADE, the fusion of lexical and dense rankings, and listwise reranking with LLMs. A small cross-encoder is trained on the local GPU, and a hybrid cascade is built and evaluated rigorously. GPUCore110 min
  22. 22Retrieval-augmented generation end to endDevelop retrieval-augmented generation from probabilistic document marginalization through chunking, hybrid retrieval, reranking, query transformation, citation checks and context-position effects, with a measured local pipeline. GPUCore115 min
  23. 23Evaluating and improving RAG: faithfulness, adaptive retrieval, GraphRAG and long contextEvaluate RAG by separating retrieval, context use, generation and claim-level faithfulness. Study verifier calibration, adaptive and iterative retrieval, GraphRAG and long-context comparison using measured local experiments. GPUAdvanced115 min
  24. 24External memory and context managementStudy an agent's finite context as working memory: context budgeting and ordering, trajectory compaction and prefix caching, and external long-term memory with scoring, virtual context management, writing, and consolidation. Compare policies with a local agent and long-conversation benchmarks. GPUCore110 min
  25. 25Orchestration and workflows: patterns, state and reliabilityStudy workflow patterns, durable execution, retries, idempotency, cascades, observability, and LLM program optimization. Build a state-graph engine and evaluate a DSPy program against a manual prompt. GPUCore105 min
  26. 26Multi-agent architecturesStudy multi-agent topologies, debate and voting, specialized roles, context isolation and empirical failure taxonomies. Compare multi-agent systems with single agents and self-consistency at equal budgets, accounting for coordination cost and correlated errors. GPUAdvanced110 min
  27. 27Agent evaluation I: environments, tasks and state-based checkingConstruct agent evaluations with stateful environments, actions and long trajectories. Study benchmark anatomy, reproducible environments, state-based and trajectory checking, simulated users and function-call evaluation, survey established benchmarks and build a 40-task benchmark. GPUCore110 min
  28. 28Agent evaluation II: trajectories, benchmark validity and time horizonsExamine trajectory evaluation, agent judges, task and outcome validity, shortcuts and broken checkers, harness sensitivity, agent-specific variance, and time horizon. Audit a benchmark and estimate local agents' horizons. GPUAdvanced110 min
  29. 29Security of tool-using agents: prompt injection and secure designWhen an agent reads third-party content and can act, any document, web page, or tool result is a way to give it instructions. The threat model of agents (indirect injection, confused deputy, exfiltration, malicious MCP tools and servers, lethal trifecta of private data, untrusted content, and output channel) is studied. It is noted that defenses by detection or by instructions are incomplete, and what design patterns offer guarantees: separating plans from data, dual LLM, information flow control with capabilities as in CaMeL, minimum privilege, and human confirmation. The agent module itself is attacked and defended, and utility under attack is measured. GPUAdvanced115 min
  30. 30Learning from environment feedback: reflection, skills and multi-turn RLStudy verbal reinforcement, reusable skills, supervised fine-tuning on successful trajectories, and multi-turn reinforcement learning with turn and token credit. Compare recorded experiments against retries at explicit budgets. GPUAdvanced115 min
  31. 31Frontier: software agents, evolutionary search and self-improvementSurvey frontier systems combining software and security agents, evaluator-guided evolutionary search for algorithms, self-improving code, and automated research agents. Reproduce a miniature evolutionary search and staged repair agent and critically read frontier claims. GPUResearch105 min

Module capstone

A local coding agent with custom retrieval and rigorous evaluation

Build, without agent frameworks and with an open model served by llama.cpp in 8 GB, for example a 4-bit Qwen2.5-Coder-7B-Instruct, an agent that answers questions and fixes bugs in small Python repositories. Integrate custom hybrid retrieval over code and documentation using the module’s BM25 and HNSW indexes, reciprocal rank fusion, and a cross-encoder; JSON-schema-defined tools served through MCP; sandboxed code execution with time, memory, and network limits; context compaction; and a test-execution verifier. Evaluate using a custom benchmark of at least 40 tasks with deterministic environment reset and final-state checking. Report pass@1 and pass^k with hierarchical bootstrap intervals, an accuracy-cost frontier against simple baselines such as one call, retries, and self-consistency, a validity audit with null agents, and an indirect-injection suite measuring utility under attack with and without a secure design pattern. Deliver code, trajectory logs, and a reproducible report with ablations.

Check what you already know

  • Budget weights and KV cache for a quantized model in 8 GB and build a reproducible call harness with caching and token accounting.
  • Formulate chain of thought as a latent variable and design an early-answer faithfulness test.
  • Calculate majority-vote success probability with N samples and explain why it plateaus while coverage continues growing.
  • Build task-clustered intervals, compare two systems with pairing, and distinguish pass@k from pass^k.
  • Use Bayes’ rule to derive when an imperfect verifier makes best-of-N degrade as N grows.
  • Generate step labels with Monte Carlo rollouts and choose a PRM aggregation.
  • Implement stepwise PRM-guided beam search and compare it with best-of-N at equal compute.
  • Allocate inference compute according to each problem’s estimated difficulty.
  • Derive ReST-EM as an EM algorithm and identify filtering bias in self-training.
  • Explain an R1-style training recipe and calculate the fraction of useful groups from the success rate.
  • Interpret pass@k curve crossings between a base model and its reinforcement-trained version.
  • Define tools with JSON Schema, validate calls, and explain why token masking is not conditioning.
  • Implement a ReAct loop without frameworks using budgets, stopping criteria, and trajectory logs.
  • Design an isolated code execution environment with time, memory, file, and network limits.
  • Compare planning and execution with a reactive agent and execute a plan as a dependency graph.
  • Derive BM25 IDF and calculate nDCG@k from relevance judgments.
  • Fine-tune a bi-encoder with in-batch and hard negatives and evaluate it with nDCG.
  • Derive SimHash collision probability and reduce MIPS to nearest-neighbor search.
  • Calculate memory for an IVF-PQ index and bound asymmetric distance error by quantization error.
  • Implement HNSW layered search using a candidate list of size ef and explain diversity-based neighbor pruning.
  • Calculate reciprocal rank fusion and design a retrieval and reranking cascade under a latency budget.
  • Write RAG-sequence and RAG-token marginalizations and build RAG with chunking, hybrid retrieval, and verifiable citations.
  • Attribute RAG errors to retrieval, context use, or generation and measure faithfulness by atomic claims.
  • Design an agent context-compaction policy and episodic memory scored by recency, importance, and relevance.
  • Select and compose workflow patterns, calculate expected model-cascade cost, and ensure safe retries with idempotency keys.
  • Compare a multi-agent system with a single agent and self-consistency at equal token budget, and classify failures.
  • Design an agent task with deterministic environment reset, final-state checker, and simulated user.
  • Audit agent-benchmark validity with null agents and estimate the 50% time horizon and its interval.
  • Model threats to a tool-using agent and implement a design pattern that keeps untrusted data from determining actions
  • Compare Reflexion with independent retries at the same budget and build the loss mask for a multi-turn trajectory with tools
  • Explain an LLM-guided evolutionary search loop with an automatic evaluator and design a staged repair agent

References