Skip to main content
Prerequisites: Completed the Deploy Your First Agent tutorial

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:
{
  "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:
# 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:
# 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

# 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:
runagent deploy .

What You’ve Accomplished

You’ve built a complete book writing system:

📚 Book Generation

Automated book writing from topic to complete manuscript

🤖 Multi-Agent Workflow

Orchestrated multiple specialized agents for different tasks

📝 Structured Writing

Generates well-structured outlines and coherent chapters

🔍 Research Integration

Automatically researches topics using web search

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

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

Repository

View the complete example code and documentation: Repository: 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
🎉 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!