---
title: 'Book Writing Agent'
description: 'Build an AI agent that writes complete books using multi-agent workflows'
icon: 'book'
---

import NeedHelp from '/snippets/need-help.mdx';

<Info>
  **Prerequisites**: Completed the [Deploy Your First Agent](/tutorials/deploy-your-first-agent) tutorial
</Info>

## What You'll Build

In this tutorial, you'll create a book writing agent that:
- Generates comprehensive book outlines based on topics and goals
- Writes complete books chapter by chapter using specialized agents
- Orchestrates multiple AI agents to handle different writing tasks
- Produces well-structured, coherent book content
- Uses CrewAI flows for multi-agent collaboration

## The Book Writing Challenge

Writing a complete book is a complex, multi-stage process:
- **Outline creation**: Structuring the book logically
- **Chapter writing**: Writing detailed, coherent chapters
- **Consistency**: Maintaining tone and style across chapters
- **Research**: Gathering relevant information
- **Time investment**: Writing a book takes months or years

RunAgent solves this by orchestrating multiple specialized AI agents that work together to create complete books efficiently.

## Architecture Overview

The book writing agent uses a multi-agent workflow:

```
┌─────────────────┐
│   User Input    │
│ (Topic, Goal)   │
└────────┬────────┘
         │
         ↓
┌─────────────────┐
│  OutlineCrew    │
│ (Generate       │
│  Book Outline)  │
└────────┬────────┘
         │
         ↓
┌─────────────────┐
│ WriteBook       │
│ ChapterCrew     │
│ (One per        │
│  chapter)       │
└────────┬────────┘
         │
         ↓
┌─────────────────┐
│  Join Chapters  │
│  & Save Book    │
└─────────────────┘
```

## Step 1: Understanding the Agent Structure

The book writing agent uses CrewAI flows with specialized crews:

**Key Components:**
- **OutlineCrew**: Generates comprehensive book outlines
  - Searches the internet for relevant information
  - Defines book structure and main topics
  - Creates detailed chapter breakdowns

- **WriteBookChapterCrew**: Writes individual chapters
  - One crew instance per chapter
  - Ensures detailed and coherent content
  - Maintains consistency with outline

**Entrypoints:**
- `generate_outline`: Generate book outline from topic and goal
- `write_book`: Write complete book with all chapters

## Step 2: Agent Configuration

The agent is configured using `runagent.config.json`:

```json
{
  "agent_name": "book-writer",
  "description": "AI-powered book writing with multi-agent workflows",
  "framework": "crewai",
  "agent_architecture": {
    "entrypoints": [
      {
        "file": "main.py",
        "module": "generate_outline",
        "tag": "generate_outline"
      },
      {
        "file": "main.py",
        "module": "write_book",
        "tag": "write_book"
      }
    ]
  }
}
```

## Step 3: Core Agent Logic (Gist)

The agent writes books through a structured workflow:

```python
# Simplified flow structure
def generate_outline(
    title: str,
    topic: str,
    goal: str
) -> Dict[str, Any]:
    """
    Generates a comprehensive book outline:
    1. Researches the topic using web search
    2. Defines book structure and main topics
    3. Creates detailed chapter breakdowns
    4. Returns structured outline
    """
    outline_crew = OutlineCrew()
    result = outline_crew.kickoff(
        title=title,
        topic=topic,
        goal=goal
    )
    return result

def write_book(
    title: str,
    topic: str,
    goal: str,
    num_chapters: int = 5
) -> Dict[str, Any]:
    """
    Writes a complete book:
    1. Generates book outline
    2. Creates WriteBookChapterCrew for each chapter
    3. Writes each chapter in parallel or sequentially
    4. Joins all chapters into a single markdown file
    5. Saves the complete book
    """
    # Generate outline
    outline = generate_outline(title, topic, goal)
    
    # Write each chapter
    chapters = []
    for chapter_info in outline['chapters']:
        chapter_crew = WriteBookChapterCrew()
        chapter = chapter_crew.kickoff(
            title=title,
            chapter_info=chapter_info,
            previous_chapters=chapters
        )
        chapters.append(chapter)
    
    # Join and save
    complete_book = join_chapters(title, chapters)
    save_book(complete_book)
    
    return {
        "title": title,
        "chapters": chapters,
        "complete_book": complete_book
    }
```

## Step 4: Backend Integration

The Flask backend provides REST API endpoints:

```python
# Backend API structure
@app.route('/api/generate-outline', methods=['POST'])
def generate_outline():
    """
    Endpoint that:
    - Receives book topic and goal
    - Calls RunAgent agent to generate outline
    - Returns structured outline
    """
    client = RunAgentClient(
        agent_id=agent_id,
        entrypoint_tag="generate_outline",
        local=False
    )
    
    result = client.run(
        title=title,
        topic=topic,
        goal=goal
    )
    
    return jsonify(result)

@app.route('/api/write-book', methods=['POST'])
def write_book():
    """
    Endpoint that:
    - Receives book parameters
    - Calls RunAgent agent to write complete book
    - Returns book content or file
    """
    client = RunAgentClient(
        agent_id=agent_id,
        entrypoint_tag="write_book",
        local=False
    )
    
    result = client.run(
        title=title,
        topic=topic,
        goal=goal,
        num_chapters=num_chapters
    )
    
    return jsonify(result)
```

## Step 5: Frontend Integration

The React frontend provides a user-friendly interface:

**Key Features:**
- Book title and topic input
- Goal description input
- Outline preview
- Chapter-by-chapter writing progress
- Complete book download
- Real-time status updates

## Step 6: Deployment

### Local Deployment

```bash
# 1. Deploy the RunAgent agent
cd examples/book_writer/write_a_book_with_flows
runagent serve .

# 2. Start the backend
cd ../backend
python app.py

# 3. Start the frontend
cd ../frontend
npm run dev
```

### Production Deployment

The agent can be deployed to RunAgent Cloud:

```bash
runagent deploy .
```

## What You've Accomplished

You've built a complete book writing system:

<CardGroup cols={2}>
  <Card title="📚 Book Generation" icon="book">
    Automated book writing from topic to complete manuscript
  </Card>
  <Card title="🤖 Multi-Agent Workflow" icon="robot">
    Orchestrated multiple specialized agents for different tasks
  </Card>
  <Card title="📝 Structured Writing" icon="pencil">
    Generates well-structured outlines and coherent chapters
  </Card>
  <Card title="🔍 Research Integration" icon="search">
    Automatically researches topics using web search
  </Card>
</CardGroup>

## Key Features

### Outline Generation
- Researches topics using web search
- Creates logical book structure
- Defines main topics and chapter breakdowns
- Ensures comprehensive coverage

### Chapter Writing
- Writes detailed, coherent chapters
- Maintains consistency across chapters
- References previous chapters for continuity
- Adapts to book outline structure

### Multi-Agent Orchestration
- Uses CrewAI flows to coordinate agents
- Parallel or sequential chapter writing
- Specialized agents for different tasks
- Efficient resource utilization

## Example Usage

```python
from runagent import RunAgentClient

# Generate outline
outline_client = RunAgentClient(
    agent_id="your_agent_id",
    entrypoint_tag="generate_outline",
    local=False
)

outline = outline_client.run(
    title="Introduction to AI",
    topic="Artificial Intelligence",
    goal="Provide a comprehensive introduction to AI for beginners"
)

# Write complete book
book_client = RunAgentClient(
    agent_id="your_agent_id",
    entrypoint_tag="write_book",
    local=False
)

book = book_client.run(
    title="Introduction to AI",
    topic="Artificial Intelligence",
    goal="Provide a comprehensive introduction to AI for beginners",
    num_chapters=5
)
```

## Customization

### Adjusting Book Structure
- Modify `config/agents.yaml` to customize agent behavior
- Update `config/tasks.yaml` to change writing tasks
- Adjust flow in `main.py` for different workflows

### Adding Features
- Add research agents for deeper topic exploration
- Include editing agents for content refinement
- Add formatting agents for different output formats

## Next Steps

<CardGroup cols={2}>
  <Card title="Customize Agents" icon="cog" href="/how-to/advanced-tasks">
    Customize agent prompts and behaviors
  </Card>
  <Card title="Add Features" icon="plus" href="/how-to/advanced-tasks">
    Add features like editing, formatting, and publishing
  </Card>
  <Card title="Production Deployment" icon="cloud" href="/runagent-cloud/cloud-deployment">
    Deploy to production with proper scaling
  </Card>
  <Card title="View Full Example" icon="code" href="https://github.com/runagent-dev/runagent/tree/main/examples/book_writer">
    Explore the complete example code
  </Card>
</CardGroup>

## Repository

View the complete example code and documentation:

**Repository**: [https://github.com/runagent-dev/runagent/tree/main/examples/book_writer](https://github.com/runagent-dev/runagent/tree/main/examples/book_writer)

The repository includes:
- Complete agent implementation with CrewAI flows
- Flask backend API
- React frontend application
- Configuration files for agents and tasks
- Example outputs and documentation

<Note>
**🎉 Excellent work!** You've learned how to build a sophisticated book writing system using RunAgent and CrewAI. This demonstrates the power of multi-agent orchestration for complex creative tasks!
</Note>

<NeedHelp context="Book Writing Agent" />
