Leanpub Header

Skip to main content

Building AI Agents with Ollama

Design, Deploy, and Scale Reliable Local AI Systems

Building AI Agents with Ollama
This book is 100% completeLast updated on 2026-11-18

Build powerful AI agents that run entirely on your own hardware with Ollama. Learn practical patterns for RAG, multi-agent systems, security and deployment through clear explanations and production-ready code you can use right away. From first setup to reliable real-world applications, this book helps you build with confidence.

Minimum price

$29.00

$39.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
WEB
APP
421
Pages
About

About

About the Book

This book teaches you how to design, build, deploy, and maintain production-grade AI agents that run entirely on your own hardware using Ollama as the inference engine. You will learn everything from installation and model selection through advanced multi-agent architectures, RAG pipelines, security hardening, and observability. Every chapter includes complete, working code examples that you can copy, build, and run without modification. Whether you are building personal assistants, coding agents, document analysis tools, or autonomous workflow systems, this book provides the patterns, implementations, and engineering practices needed to make them work reliably in the real world.

Author

About the Author

Steve Publications

Steve is a technology professional with more than 20 years of experience spanning software development, server infrastructure, cybersecurity, vulnerability research and reverse engineering. His work focuses on understanding complex systems, uncovering security weaknesses and developing practical solutions that make technology more secure, reliable and effective.

Through Steve Publications, he collaborates with experienced researchers, engineers and industry experts to create practical, technically rigorous books on various topics not limited to self-improvement, software development, cybersecurity, cloud computing, DevOps, artificial intelligence and enterprise technologies. His mission is to make complex technical subjects accessible through clear explanations, real-world examples and hands-on exercises that help IT professionals, students and technology enthusiasts build valuable, practical skills.

Steve Publications embraces AI as a supporting tool for translation, proofreading and editorial refinement, not as a substitute for original research, technical expertise, or hands-on experience. Some contributors choose to publish under pseudonyms to protect their privacy or maintain professional boundaries.

Behind every book is a commitment to technical accuracy, practical relevance and continuous improvement. Our publications are written, reviewed and maintained by experienced professionals, with support from a private community of more than 420 engineers and researchers. Rather than prioritizing volume or mass-produced AI-generated content, we focus on delivering reliable, useful resources that readers can apply in real-world environments.

We also welcome experienced professionals who want to share their knowledge by writing or reviewing books, particularly in specialized and emerging technology fields. If you have expertise to contribute, we invite you to get in touch and explore opportunities to collaborate.

Our commitment is simple: To deliver books that respect our readers' time, support their professional growth and provide lasting practical value. If a book does not meet your expectations, Leanpub offers a 60-day money-back guarantee.

Contents

Table of Contents

Design, Deploy and Scale Reliable Local AI Systems

Introduction: The Case for Local Agents

  1. Why Local Matters Now
  2. What Is an AI Agent
  3. The Reliability Gap
  4. How This Book Is Structured
  5. Key Takeaways

Chapter 1: Foundations of Local LLMs and Ollama

  1. How Local Inference Works
  2. Installing and Configuring Ollama
  3. Basic Installation
  4. GPU Configuration
  5. Production Configuration
  6. Docker Deployment
  7. Understanding the Ollama API
  8. Core Endpoints
  9. Streaming Responses
  10. OpenAI-Compatible Endpoint
  11. Model Formats and GGUF
  12. Structure of a GGUF File
  13. Quantization Types
  14. Custom Models with Modelfile
  15. First Agent: A Minimal Example
  16. Project Structure
  17. The Minimal Agent
  18. How It Works, Line by Line
  19. Running and Testing
  20. Common Pitfalls
  21. Key Takeaways

Chapter 2: Choosing and Managing Models

  1. The Local Model Landscape
  2. Model Families and Their Strengths
  3. Benchmark Interpretation
  4. Hardware Requirements by Model Size
  5. Performance vs Size Tradeoffs
  6. Speed Considerations
  7. Capability vs Task Complexity
  8. Cost Analysis
  9. Quantization Explained
  10. How Quantization Works
  11. Quantization Quality Comparison
  12. When to Use Higher Quantization
  13. Multi-Model Strategies
  14. Task-Based Model Selection
  15. Model Registry Implementation
  16. Model Routing in Agents
  17. Key Takeaways

Chapter 3: Prompt Engineering for Agents

  1. From Prompts to Specifications
  2. The Specification Mindset
  3. System Prompt Architecture
  4. Structured Prompt Design Patterns
  5. Role-Based Prompting
  6. Constraint-Based Prompting
  7. Step-by-Step Decomposition
  8. Guardrails and Safety Instructions
  9. System Prompts and Role Definitions
  10. The Layered System Prompt
  11. Dynamic System Prompts
  12. Few-Shot and Example-Based Prompting
  13. When to Use Few-Shot Prompting
  14. Example Implementation
  15. Best Practices for Few-Shot Examples
  16. Testing and Iterating Prompts
  17. Prompt Versioning
  18. Prompt Evaluation Framework
  19. Iteration Workflow
  20. Key Takeaways

Chapter 4: Structured Outputs and Tool Calling

  1. JSON Mode and Schema Enforcement
  2. Ollama’s Format Parameter
  3. Pydantic Models for Type Safety
  4. Basic Structured Output with Pydantic
  5. How It Works
  6. Function Calling Patterns
  7. Ollama’s Native Tool Calling
  8. How ToolCallingAgent Works
  9. Python SDK Function-as-Tool Shortcut
  10. Multi-Tool Selection and Parallel Calls
  11. Error Recovery for Bad Outputs
  12. Structured Output Recovery Strategies
  13. Tool Calling Error Handling
  14. How RobustToolAgent Works
  15. Building a Tool Registry
  16. Browser Automation Tools
  17. Why Playwright Over Selenium
  18. Installation
  19. Basic Browser Control Tool
  20. How It Works
  21. Integrating Browser Tools with an Agent
  22. Security Considerations for Browser Automation
  23. Common Pitfalls
  24. Key Takeaways

Chapter 5: Memory Systems and Context Management

  1. Chapter Dependencies and Project Structure
  2. The Memory Problem
  3. Short-Term Conversation Memory
  4. Basic Message History
  5. Sliding Window Memory
  6. Summarization-Based Memory
  7. How SummarizingMemory Works
  8. Tradeoffs to understand:
  9. Long-Term Memory Architectures
  10. Types of Long-Term Memory
  11. Vector-Based Long-Term Memory
  12. How LongTermMemory Works
  13. Key design decisions:
  14. Context Window Optimization
  15. Token Budgeting
  16. Selective Context Inclusion
  17. Context Compression
  18. Implementing a Memory Manager
  19. Key Takeaways

Chapter 6: Retrieval-Augmented Generation and Vector Search

  1. Chapter Dependencies and Project Structure
  2. Why RAG Is Essential for Agents
  3. Embeddings and Vector Spaces
  4. How Embeddings Work
  5. Choosing an Embedding Model
  6. Generating Embeddings with Ollama
  7. Vector Database Options
  8. Lightweight (Development and Small Scale)
  9. Production-Grade (Self-Hosted)
  10. Database Extensions
  11. Recommendation Matrix
  12. Document Ingestion Pipelines
  13. Pipeline Architecture
  14. Complete Ingestion Implementation
  15. How RAGIngestionPipeline Works
  16. Performance considerations:
  17. Chunking Strategy
  18. Hybrid Search and Re-Ranking
  19. Why Hybrid Search Matters
  20. Re-Ranking for Quality
  21. Complete RAG Query Implementation
  22. How RAGQueryEngine Works
  23. Key design decisions:
  24. RAG Failure Modes: Retrieval Drift and Degradation
  25. Key Takeaways

Chapter 7: Planning, Reasoning and Complex Tasks

  1. Beyond Single-Turn Responses
  2. Chain of Thought and Reasoning
  3. How Chain of Thought Works
  4. Implementing Reasoning Agents
  5. When Chain of Thought Matters Most
  6. The ReAct Pattern
  7. ReAct Loop Mechanics
  8. Implementing a ReAct Agent
  9. ReAct vs Direct Tool Calling
  10. Task Decomposition Strategies
  11. Hierarchical Decomposition
  12. When to Use Decomposition
  13. Key Takeaways

Chapter 8: Multi-Agent Architectures

  1. Why Multiple Agents
  2. Specialization and Roles
  3. Separation of Concerns
  4. Debate and Quality Improvement
  5. Specialization and Roles
  6. Common Agent Roles
  7. Communication Patterns
  8. Sequential Chain
  9. Parallel Fan-Out
  10. Hierarchical (Supervisor)
  11. Debate Pattern
  12. Orchestration Strategies
  13. Centralized Orchestration
  14. Event-Driven Orchestration
  15. Graph-Based Orchestration
  16. Building an Agent Team
  17. Key Takeaways

Chapter 9: Workflows, State Machines and Orchestration

  1. Agents as Workflow Nodes
  2. Workflow Components
  3. Simple Workflow Engine
  4. How WorkflowEngine Works
  5. State Machine Design
  6. State Machine Pattern
  7. How AgentStateMachine Works
  8. Async Processing and Concurrency
  9. Python asyncio for Agent Workflows
  10. Retries, Timeouts and Circuit Breakers
  11. Retry with Exponential Backoff
  12. Timeouts
  13. Circuit Breaker Pattern
  14. Key Takeaways

Chapter 10: Testing, Debugging and Observability

  1. Chapter Dependencies and Project Structure
  2. The Testing Challenge
  3. Unit Testing Agents and Tools
  4. Testing Prompt Templates
  5. Testing Tool Functions
  6. Testing Output Parsers
  7. Integration and End-to-End Tests
  8. Golden Dataset Testing
  9. LLM-as-Judge Evaluation
  10. Logging and Tracing
  11. Structured Logging
  12. Execution Tracing
  13. Monitoring and Alerting
  14. Core Metrics to Monitor
  15. Implementation with Prometheus (Example)
  16. Key Takeaways

Chapter 11: Performance, Resources and Optimization

  1. Understanding Resource Consumption
  2. Model Weights
  3. KV Cache
  4. Compute
  5. GPU Acceleration and Configuration
  6. Verifying GPU Usage
  7. NVIDIA CUDA Configuration
  8. AMD ROCm Configuration
  9. Apple Metal Configuration
  10. GPU Memory Management
  11. Caching Strategies
  12. Prompt-Response Caching
  13. Semantic Caching
  14. Batch Processing and Throughput
  15. Request Batching
  16. Async Batch Processing
  17. Scaling Local Inference
  18. Horizontal Scaling with Load Balancing
  19. Kubernetes Deployment
  20. Model-Level Scaling
  21. GPU Fragmentation and Memory Pressure Scenarios
  22. Key Takeaways

Chapter 12: Security, Privacy and Sandboxing

  1. The Threat Model for Local Agents
  2. Attack Surface Analysis
  3. OWASP Top Risks for LLM Applications
  4. Prompt Injection Attacks
  5. Direct Prompt Injection
  6. Indirect Prompt Injection
  7. Defense Strategies
  8. Tool Sandboxing
  9. Principle of Least Privilege
  10. Sandboxing Code Execution
  11. Network Access Control
  12. Data Privacy and Compliance
  13. Data Minimization
  14. Access Control
  15. Compliance Considerations
  16. Hardening Your Deployment
  17. Network Security
  18. Container Security
  19. API Security
  20. Model Security
  21. Key Takeaways

Chapter 13: Deployment, APIs and Real-World Integration

  1. Chapter Dependencies and Project Structure
  2. Packaging Agents as Services
  3. FastAPI Agent Service
  4. RESTful Agent APIs
  5. API Design Principles
  6. Conversation Management
  7. Web Interfaces and Dashboards
  8. Simple Chat Interface with HTML/JS
  9. Desktop and System Integration
  10. File System Agent
  11. Automation Integration
  12. Production Deployment Patterns
  13. Complete Docker Stack
  14. Deployment Checklist
  15. Key Takeaways

Chapter 14: Capstone Project - Building a Production Coding Agent

  1. Project Overview: The CodePilot Agent
  2. Project Structure
  3. Step 1: Configuration and Dependencies
  4. Step 2: Tool Registry and Implementation
  5. Step 3: Memory System Integration
  6. Step 4: RAG Pipeline for Codebase Indexing
  7. Step 5: Agent Core with Prompts and Reasoning
  8. How CodePilotAgent Works
  9. Step 6: Security Layer
  10. Step 7: Observability Setup
  11. Step 8: FastAPI Service Layer
  12. Step 9: Docker Deployment
  13. Step 10: Web Interface
  14. Step 11: Testing
  15. Running the Complete System
  16. Architecture Summary
  17. Key Takeaways

Conclusion: The Future of Local Agents

  1. What We Have Built
  2. The Trajectory Ahead
  3. Principles That Will Endure
  4. Key Takeaways

References

Appendix A: Ollama Environment Variables and Configuration Reference

  1. Network and Binding Variables
  2. Model Storage Variables
  3. Concurrency and Queue Variables
  4. GPU and Hardware Variables
  5. Context and Inference Variables
  6. Setting Environment Variables by Platform
  7. Recommended Production Configurations

Appendix B: Troubleshooting Common GPU, Driver and OOM Errors

  1. Enabling Debug Logging
  2. NVIDIA GPU Not Detected
  3. AMD GPU Not Detected
  4. CUDA Out of Memory (OOM) Errors
  5. CPU Fallback (Silent or Explicit)
  6. Model Loading Fails or Hangs
  7. Connection Refused Errors
  8. Apple Silicon Specific Issues
  9. Diagnostic Checklist

Appendix C: Model Quantization Cheat Sheet

  1. Quick Decision Guide
  2. Quantization Level Comparison
  3. Key Principles
  4. VRAM Estimation Formula
  5. Model Tag Naming Convention
  6. Speed vs Quantization

Appendix D: Reusable Code Patterns

  1. Pattern 1: Retry with Exponential Backoff and Jitter
  2. Pattern 2: Circuit Breaker for External Services
  3. Pattern 3: Structured JSON Logger
  4. Pattern 4: Token Counter Utility
  5. Pattern 5: Rate Limiter for API Calls
  6. Pattern 6: Context Window Manager

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub