Design, Deploy and Scale Reliable Local AI Systems
Introduction: The Case for Local Agents
- Why Local Matters Now
- What Is an AI Agent
- The Reliability Gap
- How This Book Is Structured
- Key Takeaways
Chapter 1: Foundations of Local LLMs and Ollama
- How Local Inference Works
- Installing and Configuring Ollama
- Basic Installation
- GPU Configuration
- Production Configuration
- Docker Deployment
- Understanding the Ollama API
- Core Endpoints
- Streaming Responses
- OpenAI-Compatible Endpoint
- Model Formats and GGUF
- Structure of a GGUF File
- Quantization Types
- Custom Models with Modelfile
- First Agent: A Minimal Example
- Project Structure
- The Minimal Agent
- How It Works, Line by Line
- Running and Testing
- Common Pitfalls
- Key Takeaways
Chapter 2: Choosing and Managing Models
- The Local Model Landscape
- Model Families and Their Strengths
- Benchmark Interpretation
- Hardware Requirements by Model Size
- Performance vs Size Tradeoffs
- Speed Considerations
- Capability vs Task Complexity
- Cost Analysis
- Quantization Explained
- How Quantization Works
- Quantization Quality Comparison
- When to Use Higher Quantization
- Multi-Model Strategies
- Task-Based Model Selection
- Model Registry Implementation
- Model Routing in Agents
- Key Takeaways
Chapter 3: Prompt Engineering for Agents
- From Prompts to Specifications
- The Specification Mindset
- System Prompt Architecture
- Structured Prompt Design Patterns
- Role-Based Prompting
- Constraint-Based Prompting
- Step-by-Step Decomposition
- Guardrails and Safety Instructions
- System Prompts and Role Definitions
- The Layered System Prompt
- Dynamic System Prompts
- Few-Shot and Example-Based Prompting
- When to Use Few-Shot Prompting
- Example Implementation
- Best Practices for Few-Shot Examples
- Testing and Iterating Prompts
- Prompt Versioning
- Prompt Evaluation Framework
- Iteration Workflow
- Key Takeaways
Chapter 4: Structured Outputs and Tool Calling
- JSON Mode and Schema Enforcement
- Ollama’s Format Parameter
- Pydantic Models for Type Safety
- Basic Structured Output with Pydantic
- How It Works
- Function Calling Patterns
- Ollama’s Native Tool Calling
- How ToolCallingAgent Works
- Python SDK Function-as-Tool Shortcut
- Multi-Tool Selection and Parallel Calls
- Error Recovery for Bad Outputs
- Structured Output Recovery Strategies
- Tool Calling Error Handling
- How RobustToolAgent Works
- Building a Tool Registry
- Browser Automation Tools
- Why Playwright Over Selenium
- Installation
- Basic Browser Control Tool
- How It Works
- Integrating Browser Tools with an Agent
- Security Considerations for Browser Automation
- Common Pitfalls
- Key Takeaways
Chapter 5: Memory Systems and Context Management
- Chapter Dependencies and Project Structure
- The Memory Problem
- Short-Term Conversation Memory
- Basic Message History
- Sliding Window Memory
- Summarization-Based Memory
- How SummarizingMemory Works
- Tradeoffs to understand:
- Long-Term Memory Architectures
- Types of Long-Term Memory
- Vector-Based Long-Term Memory
- How LongTermMemory Works
- Key design decisions:
- Context Window Optimization
- Token Budgeting
- Selective Context Inclusion
- Context Compression
- Implementing a Memory Manager
- Key Takeaways
Chapter 6: Retrieval-Augmented Generation and Vector Search
- Chapter Dependencies and Project Structure
- Why RAG Is Essential for Agents
- Embeddings and Vector Spaces
- How Embeddings Work
- Choosing an Embedding Model
- Generating Embeddings with Ollama
- Vector Database Options
- Lightweight (Development and Small Scale)
- Production-Grade (Self-Hosted)
- Database Extensions
- Recommendation Matrix
- Document Ingestion Pipelines
- Pipeline Architecture
- Complete Ingestion Implementation
- How RAGIngestionPipeline Works
- Performance considerations:
- Chunking Strategy
- Hybrid Search and Re-Ranking
- Why Hybrid Search Matters
- Re-Ranking for Quality
- Complete RAG Query Implementation
- How RAGQueryEngine Works
- Key design decisions:
- RAG Failure Modes: Retrieval Drift and Degradation
- Key Takeaways
Chapter 7: Planning, Reasoning and Complex Tasks
- Beyond Single-Turn Responses
- Chain of Thought and Reasoning
- How Chain of Thought Works
- Implementing Reasoning Agents
- When Chain of Thought Matters Most
- The ReAct Pattern
- ReAct Loop Mechanics
- Implementing a ReAct Agent
- ReAct vs Direct Tool Calling
- Task Decomposition Strategies
- Hierarchical Decomposition
- When to Use Decomposition
- Key Takeaways
Chapter 8: Multi-Agent Architectures
- Why Multiple Agents
- Specialization and Roles
- Separation of Concerns
- Debate and Quality Improvement
- Specialization and Roles
- Common Agent Roles
- Communication Patterns
- Sequential Chain
- Parallel Fan-Out
- Hierarchical (Supervisor)
- Debate Pattern
- Orchestration Strategies
- Centralized Orchestration
- Event-Driven Orchestration
- Graph-Based Orchestration
- Building an Agent Team
- Key Takeaways
Chapter 9: Workflows, State Machines and Orchestration
- Agents as Workflow Nodes
- Workflow Components
- Simple Workflow Engine
- How WorkflowEngine Works
- State Machine Design
- State Machine Pattern
- How AgentStateMachine Works
- Async Processing and Concurrency
- Python asyncio for Agent Workflows
- Retries, Timeouts and Circuit Breakers
- Retry with Exponential Backoff
- Timeouts
- Circuit Breaker Pattern
- Key Takeaways
Chapter 10: Testing, Debugging and Observability
- Chapter Dependencies and Project Structure
- The Testing Challenge
- Unit Testing Agents and Tools
- Testing Prompt Templates
- Testing Tool Functions
- Testing Output Parsers
- Integration and End-to-End Tests
- Golden Dataset Testing
- LLM-as-Judge Evaluation
- Logging and Tracing
- Structured Logging
- Execution Tracing
- Monitoring and Alerting
- Core Metrics to Monitor
- Implementation with Prometheus (Example)
- Key Takeaways
Chapter 11: Performance, Resources and Optimization
- Understanding Resource Consumption
- Model Weights
- KV Cache
- Compute
- GPU Acceleration and Configuration
- Verifying GPU Usage
- NVIDIA CUDA Configuration
- AMD ROCm Configuration
- Apple Metal Configuration
- GPU Memory Management
- Caching Strategies
- Prompt-Response Caching
- Semantic Caching
- Batch Processing and Throughput
- Request Batching
- Async Batch Processing
- Scaling Local Inference
- Horizontal Scaling with Load Balancing
- Kubernetes Deployment
- Model-Level Scaling
- GPU Fragmentation and Memory Pressure Scenarios
- Key Takeaways
Chapter 12: Security, Privacy and Sandboxing
- The Threat Model for Local Agents
- Attack Surface Analysis
- OWASP Top Risks for LLM Applications
- Prompt Injection Attacks
- Direct Prompt Injection
- Indirect Prompt Injection
- Defense Strategies
- Tool Sandboxing
- Principle of Least Privilege
- Sandboxing Code Execution
- Network Access Control
- Data Privacy and Compliance
- Data Minimization
- Access Control
- Compliance Considerations
- Hardening Your Deployment
- Network Security
- Container Security
- API Security
- Model Security
- Key Takeaways
Chapter 13: Deployment, APIs and Real-World Integration
- Chapter Dependencies and Project Structure
- Packaging Agents as Services
- FastAPI Agent Service
- RESTful Agent APIs
- API Design Principles
- Conversation Management
- Web Interfaces and Dashboards
- Simple Chat Interface with HTML/JS
- Desktop and System Integration
- File System Agent
- Automation Integration
- Production Deployment Patterns
- Complete Docker Stack
- Deployment Checklist
- Key Takeaways
Chapter 14: Capstone Project - Building a Production Coding Agent
- Project Overview: The CodePilot Agent
- Project Structure
- Step 1: Configuration and Dependencies
- Step 2: Tool Registry and Implementation
- Step 3: Memory System Integration
- Step 4: RAG Pipeline for Codebase Indexing
- Step 5: Agent Core with Prompts and Reasoning
- How CodePilotAgent Works
- Step 6: Security Layer
- Step 7: Observability Setup
- Step 8: FastAPI Service Layer
- Step 9: Docker Deployment
- Step 10: Web Interface
- Step 11: Testing
- Running the Complete System
- Architecture Summary
- Key Takeaways
Conclusion: The Future of Local Agents
- What We Have Built
- The Trajectory Ahead
- Principles That Will Endure
- Key Takeaways
References
Appendix A: Ollama Environment Variables and Configuration Reference
- Network and Binding Variables
- Model Storage Variables
- Concurrency and Queue Variables
- GPU and Hardware Variables
- Context and Inference Variables
- Setting Environment Variables by Platform
- Recommended Production Configurations
Appendix B: Troubleshooting Common GPU, Driver and OOM Errors
- Enabling Debug Logging
- NVIDIA GPU Not Detected
- AMD GPU Not Detected
- CUDA Out of Memory (OOM) Errors
- CPU Fallback (Silent or Explicit)
- Model Loading Fails or Hangs
- Connection Refused Errors
- Apple Silicon Specific Issues
- Diagnostic Checklist
Appendix C: Model Quantization Cheat Sheet
- Quick Decision Guide
- Quantization Level Comparison
- Key Principles
- VRAM Estimation Formula
- Model Tag Naming Convention
- Speed vs Quantization
Appendix D: Reusable Code Patterns
- Pattern 1: Retry with Exponential Backoff and Jitter
- Pattern 2: Circuit Breaker for External Services
- Pattern 3: Structured JSON Logger
- Pattern 4: Token Counter Utility
- Pattern 5: Rate Limiter for API Calls
- Pattern 6: Context Window Manager