Internals, Architecture, Algorithms and Production Implementation
Introduction
- What You Are Really Building
- Why You Should Not Use a Black Box
- How This Book Is Structured
- What You Need to Know
- What This Book Is Not
- A Note on Examples and Code
- The Central Thesis
Chapter 1: The Agent Mental Model
- What an agent is not: dispelling the illusion of autonomous models
- The harness as execution environment: orchestrating the loop
- Responsibility boundaries: model, inference runtime, harness, tools
- A concrete mental model with a layered diagram
- Why this architecture is necessary: the gap between generation and action
Chapter 2: How Large Language Models Actually Work
- Tokenization: how text becomes numbers the model sees
- The context window: what the model “remembers” and its limits
- Inference: forward passes, attention, sampling strategies
- Temperature, top-p, top-k: controlling randomness
- Structured outputs and why they are difficult
- The model as a stateless function: f(context) → tokens
Chapter 3: The Model API as a Contract
- Chat completions API: the universal interface
- Message roles: system, user, assistant and tool messages
- System instructions and their actual effect on behavior
- The OpenAI-compatible API standard and its spread
- Provider-specific extensions: function calling, tool choice, reasoning models
- Latency, rate limits and operational characteristics
Chapter 4: From Prompt to Action: The Agent Execution Cycle
- A complete execution trace of a simple agent request
- Step one: receiving the request and initializing state
- Step two: assembling context from history, tools and prompt
- Step three: invoking the model and receiving a response
- Step four: parsing the model response for actions
- Step five: executing tools and collecting observations
- Step six: feeding results back and deciding whether to continue
- Step seven: the model generates the final answer
- Termination: when the agent decides it is done
- What happens inside the model vs what happens inside the harness
Chapter 5: Tool Calling - From Model Output to Real Execution
- Tool definitions: schemas, descriptions and parameters
- How models learn to generate tool calls
- The tool call response format: structure and variants
- Parsing model outputs: JSON, function calls and structured formats
- Argument validation and schema enforcement
- The dispatch mechanism: routing a tool name to handler code
- Returning observations to the model: formatting and context cost
Chapter 6: The Prompt and Context Assembly Problem
- The components of agent context: system prompt, history, tools, state
- Prompt templates and dynamic assembly
- Token budgeting: fitting everything into the window
- Truncation strategies: what to keep and what to drop
- Cost of tool schemas and history growth
- When the context window becomes a bottleneck
Chapter 7: State, Memory and Conversation Management
- Ephemeral state: the active execution context
- Conversation history: storing and serializing message sequences
- Message compression and summary strategies
- Working memory: scratchpad and intermediate state
- Long-term memory: vector stores and retrieval
- Memory isolation: per-session vs shared knowledge
Chapter 8: Project Setup and First Contact
- Technology choices: why Python, why an OpenAI-compatible interface
- Project structure: organization for a growing codebase
- Dependency management: pinning versions
- Configuration: environment variables and config objects
- The minimal model invocation: first request and response
- Error handling for model API calls
- Running and testing the initial setup
Chapter 9: The Core Message and State Types
- Message types: SystemMessage, UserMessage, AssistantMessage, ToolMessage
- Tool definitions: schema, parameters, descriptions as data structures
- Agent state: history, active tools, configuration, limits
- Serialization: JSON, persistence and round-tripping
- Type safety: using dataclasses and protocols
- Versioning: handling schema changes over time
Chapter 10: The Tool Registry and Dispatch System
- Tool registration: decorating or registering functions as tools
- Schema generation: extracting JSON Schema from Python types
- Tool description language: what makes a tool callable by a model
- The registry data structure and lookup
- Dispatch: matching tool names and routing to handlers
- Result formatting: converting Python values to model-readable strings
Chapter 11: The Agent Execution Loop
- Loop design: the core while loop with exit conditions
- Iteration limits: preventing infinite execution
- Token budgets: tracking and enforcing limits
- Maximum tool calls per turn and overall
- Response parsing: handling text-only, tool-call and mixed responses
- Error handling within the loop
- Graceful termination and timeout handling
Chapter 12: Streaming, Concurrency and Async Operations
- Streaming model responses: chunked data and incremental parsing
- Building streaming agents: yielding tokens and events as they arrive
- Async tool execution: why some tools need await
- Parallel tool calls: executing multiple tools concurrently
- Race conditions and ordering in parallel execution
- Cancellation: interrupting a running agent
Chapter 13: Persistence, Checkpoints and Durability
- Why persistence matters: crash recovery and resumption
- State serialization: what to save and when
- Checkpointing strategy: periodic vs event-driven
- Database choices: SQLite, Postgres, key-value stores
- Resuming from checkpoints: restoring and continuing execution
Chapter 14: Error Handling, Retries and Fault Tolerance
- Failure taxonomy: network errors, API errors, model errors, tool errors
- Retry policies: exponential backoff, jitter and limits
- Idempotency: safe retries for tool execution
- Handling malformed model outputs
- Fallback strategies and circuit breakers
- Timeout handling at every layer
Chapter 15: Observability, Logging and Tracing
- Logging levels and what to log at each level
- Structured logging: JSON logs for machine readability
- Event streaming: execution events as a first-class concern
- Distributed tracing: tracking requests across services
- Metrics: latency, token usage, error rates
- Debugging real agent runs: reconstructing what happened
Chapter 16: Security, Sandboxing and Trust Boundaries
- The trust model: what is trusted and what is not
- Prompt injection: how it works and defense strategies
- Tool authorization: never trusting the model to respect permissions
- Input validation and sanitization at every boundary
- Sandboxing tool execution: containers, timeouts, resource limits
- Secrets management and credential safety
- Rate limiting and abuse prevention
Chapter 17: Performance, Cost and Resource Optimization
- Latency profiling: where time is spent in the agent loop
- Token cost optimization: concise prompts and selective context
- Model selection strategies: smaller models for simpler tasks
- Caching strategies: prompt caching and response caching
- Batch processing: running multiple agents efficiently
Chapter 18: Planning, Decomposition and Control Strategies
- Simple reactive agents vs planning agents
- Task decomposition: breaking problems into steps
- Plan-and-execute: generating and following a plan
- Self-reflection and self-correction patterns
- Tree-of-thoughts and graph search in agents
Chapter 19: Hierarchical Agents and Multi-Agent Systems
- Why multiple agents: specialization and isolation
- Hierarchical architectures: manager and worker agents
- Agent communication: protocols for inter-agent coordination
- Shared tools and shared context
- Routing: choosing which agent handles which task
- Emergent complexity in multi-agent systems
Chapter 20: Retrieval-Augmented Generation and Knowledge Access
- Why RAG: extending agents beyond training data
- Chunking, embedding and indexing strategies
- Retrieval as a tool vs embedded context
- Reranking and relevance filtering
- Grounded generation: constraining outputs to retrieved content
- Evaluating retrieval quality
Chapter 21: Long-Running Workflows and Human-in-the-Loop
- Long-running agents vs request-response agents
- Workflow orchestration: state machines and DAGs
- Human approval gates: pausing and resuming with human input
- Webhooks and callbacks for asynchronous workflows
- Timeout and staleness handling
- Idempotent workflow execution
Chapter 22: Evaluating Agents - Correctness, Reliability and Safety
- What to measure: correctness, reliability, latency, cost, safety
- Example-based evaluation: test suites for agent behaviors
- Automated evaluation with model-as-judge
- Regression testing: catching breaking changes
- Safety evaluation: stress testing for injection and abuse
- Observability-driven improvement
Chapter 23: From Minimal Loop to Production Harness
- The minimal viable agent: what you can start with
- Capability tiers: what to add and when
- Architecture review: the complete system
- Common pitfalls and how to avoid them
- Making trade-offs: simplicity vs capability
- Maintenance and evolution of agent systems
Chapter 24: Open Problems and the Future of Agent Harnesses
- Unsolved reliability problems
- The role of improved models vs better harnesses
- Standardization efforts and protocols
- Agent-to-agent communication and ecosystems
- Integration with operating systems and infrastructure
- Speculative directions and what to watch