# Tools for Building Modular AI Agents: Inside the AI-Agent-Book Repository

> Discover tools for building modular AI agents in the AI-Agent-Book repository. Explore layered architecture, LLM backends, context management, and pluggable tool execution with ReAct.

- Repository: [Bojie Li/ai-agent-book](https://github.com/bojieli/ai-agent-book)
- Tags: deep-dive
- Published: 2026-07-30

---

**The AI-Agent-Book repository provides production-ready tools for building modular AI agents through a layered architecture that separates LLM backends, context management, and pluggable tool execution using the ReAct reasoning paradigm.**

The `bojieli/ai-agent-book` repository offers a comprehensive educational framework and codebase for developers seeking practical **tools for building modular AI agents**. It treats each agent as a composable system where large language models interact with external capabilities through a consistent interface, organized into progressive chapters that build from basic web search to complex multi-agent systems.

## Core Architecture: Agent = LLM + Context + Tools

Every implementation in the repository follows the central formula defined in [`README.md`](https://github.com/bojieli/ai-agent-book/blob/main/README.md) lines 48‑56: **Agent = LLM + Context + Tools**. This decomposition creates clear boundaries between components:

- **LLM**: The reasoning engine, supporting Moonshot, OpenRouter, and other backends via [`config.py`](https://github.com/bojieli/ai-agent-book/blob/main/config.py) resolution
- **Context**: System prompts, conversation history, and external knowledge (RAG) that guide model behavior  
- **Tools**: Executable functions exposed through the Kimi Formula API or custom Python callables that the agent invokes during task execution

This separation allows developers to swap model providers, update system prompts, or add new capabilities without refactoring the core reasoning logic.

## ReAct Loop Implementation

The repository implements the ReAct (Reason → Action → Observation → Thought) cycle in [`chapter1/web-search-agent/agent.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter1/web-search-agent/agent.py) lines 28‑45. The `search_and_answer` method orchestrates the full reasoning trace:

1. **Reason**: The model emits `reasoning_content` captured via `_emit` (lines 84‑88)
2. **Action**: Parsed `tool_calls` extract function names and arguments (lines 90‑108)  
3. **Observation**: Tools execute via `_execute_formula` and append results to the trace (lines 130‑155)
4. **Thought/Answer**: The model processes observations iteratively until producing final `content` (lines 166‑184)

The complete execution history persists in `self.trace`, accessible via `get_trace()`, with formatting handled by `format_trace_step` (lines 37‑53). This transparency makes debugging agent behavior straightforward.

## Flexible Model Backend Resolution

Multi-provider support lives in [`chapter1/web-search-agent/config.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter1/web-search-agent/config.py) through the `resolve_llm_backend` function (lines 38‑61):

- **Primary**: Moonshot/Kimi API when `MOONSHOT_API_KEY` is present
- **Fallback**: OpenRouter integration with automatic model identifier mapping via `map_model_to_openrouter`

This abstraction enables the same agent code to run across different hosting providers without modification, a pattern repeated in later chapters for vision, speech, and multi-agent configurations.

## Chapter-Based Modularity

The repository organizes **tools for building modular AI agents** into ten progressive chapters, each adding capabilities while reusing foundational components:

| Chapter | Focus | Key Reuse |
|---------|-------|-----------|
| 1 | Web-search agent | Core `WebSearchAgent` class and ReAct loop |
| 2 | Context engineering | `Config.SEARCH_TIMEOUT`, KV-cache optimization |
| 3 | User memory & RAG | Extended `conversation_history`, vector stores |
| 4 | Tool design patterns | MCP protocol, async tool handling |
| 5 | Coding agents | `code_interpreter` integration |

Each chapter folder contains executable experiments, tests (e.g., [`test_agent.py`](https://github.com/bojieli/ai-agent-book/blob/main/test_agent.py)), and narrative documentation in `book/chapter*.md`. Higher-level chapters inherit lower-level utilities, demonstrating how to compose complex behaviors from simple, tested primitives.

## Running the Examples

### Offline Demo Without API Keys

Test the reasoning loop using cached responses:

```python
from chapter1.web-search-agent.agent import run_offline_demo

demo = run_offline_demo(
    question="什么是 Moonshot AI 的 Context Caching？",
    verbose=True,
)
print("\n答案:", demo["answer"])

```

*Source*: `run_offline_demo` in [`agent.py`](https://github.com/bojieli/ai-agent-book/blob/main/agent.py) lines 32‑73.

### Interactive Quickstart

Run the guided tutorial with live API access:

```bash
python chapter1/web-search-agent/quickstart.py

```

The script validates `MOONSHOT_API_KEY` or `KIMI_API_KEY` and presents an interactive menu for testing queries.

*Source*: [`quickstart.py`](https://github.com/bojieli/ai-agent-book/blob/main/quickstart.py) lines 1‑90.

### Programmatic Integration

Embed the agent in existing applications:

```python
from chapter1.web-search-agent.agent import WebSearchAgent

agent = WebSearchAgent()  # Auto-resolves backend and API keys

answer = agent.search_and_answer(
    "Explain the benefits of KV-cache in LLM serving."
)
print(answer)

```

*Source*: `WebSearchAgent.__init__` and `search_and_answer` in [`agent.py`](https://github.com/bojieli/ai-agent-book/blob/main/agent.py) lines 96‑108, 45‑55.

## Summary

- The **Agent = LLM + Context + Tools** formula in [`README.md`](https://github.com/bojieli/ai-agent-book/blob/main/README.md) provides the architectural foundation for all implementations
- **ReAct loop** implementation in [`chapter1/web-search-agent/agent.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter1/web-search-agent/agent.py) handles reasoning, tool invocation, and observation processing through the `search_and_answer` method
- **Backend resolution** in [`config.py`](https://github.com/bojieli/ai-agent-book/blob/main/config.py) enables provider-agnostic deployment across Moonshot and OpenRouter
- **Chapter-based structure** allows incremental adoption, with each experiment building upon tested primitives from previous sections
- **Executable examples** in [`quickstart.py`](https://github.com/bojieli/ai-agent-book/blob/main/quickstart.py) and `run_offline_demo` provide immediate hands-on validation

## Frequently Asked Questions

### What is the ReAct loop in the AI-Agent-Book?

The ReAct loop is the core reasoning engine implemented in [`chapter1/web-search-agent/agent.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter1/web-search-agent/agent.py) that cycles through Reason, Action, Observation, and Thought steps. It enables the agent to break complex queries into sub-tasks, invoke tools like web search, and synthesize answers based on external observations rather than relying solely on pre-trained knowledge.

### How does the repository handle different LLM providers?

The `resolve_llm_backend` function in [`chapter1/web-search-agent/config.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter1/web-search-agent/config.py) automatically detects available API keys and routes requests to Moonshot/Kimi or falls back to OpenRouter. This abstraction allows the same agent code to operate across multiple hosting providers without modification.

### Can I integrate these tools into my existing Python project?

Yes. The `WebSearchAgent` class exposes a clean public interface through `search_and_answer()`. Import the class from [`chapter1/web-search-agent/agent.py`](https://github.com/bojieli/ai-agent-book/blob/main/chapter1/web-search-agent/agent.py), instantiate it (which automatically handles configuration), and call the method with your query string to receive formatted responses.

### What makes this approach "modular"?

The architecture separates concerns into distinct layers: model backends (config), reasoning logic (agent), and tool execution (formulas). This modularity allows developers to swap LLM providers, add new tools, or modify context strategies without refactoring the core ReAct implementation, following the compositional pattern established across the repository's ten chapters.