← Back to DevBytes

Building a Content Writing Agent with AutoGen: Complete Guide

What is a Content Writing Agent?

A content writing agent is an AI-powered system that automates the process of planning, researching, drafting, and editing written material. Instead of relying on a single large language model (LLM) to generate an entire article in one shot, a multi-agent approach breaks the task into specialized roles—much like a human editorial team. With AutoGen, Microsoft's open-source framework for building conversational agents, you can orchestrate multiple LLM-based agents that collaborate through structured conversation to produce high-quality, coherent content.

This tutorial teaches you how to build a complete content writing agent using AutoGen. You'll learn to define agent roles, set up a group chat, and implement a production-ready pipeline that can scale your content creation while maintaining quality and consistency.

Why It Matters

Building a content writing agent with AutoGen offers several concrete advantages:

Prerequisites and Setup

To follow along, you need:

Install AutoGen and its dependencies in a new virtual environment:

python -m venv autogen-env
source autogen-env/bin/activate   # On Windows: autogen-env\Scripts\activate
pip install pyautogen openai

Store your API key in an environment variable or use AutoGen's OAI_CONFIG_LIST file. A minimal JSON config list (e.g., OAI_CONFIG_LIST.json) looks like:

[
    {
        "model": "gpt-4",
        "api_key": "sk-your-key-here"
    }
]

AutoGen provides a helper to load this configuration:

import autogen

config_list = autogen.config_list_from_json(
    "OAI_CONFIG_LIST",
    filter_dict={"model": ["gpt-4"]}
)

You can also pass the API key directly via environment variable OPENAI_API_KEY and omit the file, but the config list approach is more flexible for multiple models.

Designing the Multi-Agent Workflow

A content writing pipeline typically involves four core roles. We'll map each to an AutoGen AssistantAgent:

Optionally, a Human Proxy agent can be inserted to allow a human reviewer to approve or modify the content at any stage. The agents communicate through a GroupChat managed by a GroupChatManager, which decides who speaks next based on the conversation state.

The typical conversation flow:

  1. User (or Human Proxy) sends the initial task message.
  2. Planner produces an outline.
  3. Researcher adds facts to the outline.
  4. Writer drafts the full article.
  5. Editor reviews and finalizes.
  6. If human mode is active, the Human Proxy asks for approval; otherwise the process ends.

Implementing the Agents with AutoGen

Below is the complete Python script to build the content writing agent. Each agent receives a carefully crafted system_message that defines its role, constraints, and output format.

import autogen
from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager
import os

# Load LLM configuration (replace with your own config path or env vars)
config_list = autogen.config_list_from_json(
    "OAI_CONFIG_LIST",
    filter_dict={"model": ["gpt-4"]}
)

# -------------------------------------------------------
# 1. Planner – creates structured outline
# -------------------------------------------------------
planner = AssistantAgent(
    name="Planner",
    system_message=(
        "You are a senior content planner. Given a topic, create a detailed outline "
        "with 5-7 sections. Each section must have a heading and 3-5 bullet points "
        "of key ideas. Reply ONLY with the outline in markdown format."
    ),
    llm_config={"config_list": config_list}
)

# -------------------------------------------------------
# 2. Researcher – enriches outline with facts
# -------------------------------------------------------
researcher = AssistantAgent(
    name="Researcher",
    system_message=(
        "You are a thorough researcher. You will receive an outline. For each section, "
        "add factual information, statistics, examples, and credible sources. "
        "Do NOT write full paragraphs; keep your notes concise and data-driven. "
        "If you cannot find information, state 'Insufficient data' honestly."
    ),
    llm_config={"config_list": config_list}
)

# -------------------------------------------------------
# 3. Writer – composes the draft
# -------------------------------------------------------
writer = AssistantAgent(
    name="Writer",
    system_message=(
        "You are a professional content writer. You will receive an outline and "
        "research notes. Write a complete article in a friendly, engaging tone. "
        "Follow the outline exactly, but expand each point into flowing paragraphs. "
        "Use the research data to support claims. Output the full article in markdown."
    ),
    llm_config={"config_list": config_list}
)

# -------------------------------------------------------
# 4. Editor – reviews and polishes
# -------------------------------------------------------
editor = AssistantAgent(
    name="Editor",
    system_message=(
        "You are a meticulous editor. Review the draft article for grammar, clarity, "
        "structural flow, and factual consistency. Make improvements directly. "
        "Provide the final version without additional commentary. "
        "If you spot factual errors, correct them based on the earlier research notes."
    ),
    llm_config={"config_list": config_list}
)

# -------------------------------------------------------
# Human proxy (optional) – enables human approval
# -------------------------------------------------------
human_proxy = UserProxyAgent(
    name="Human",
    human_input_mode="ALWAYS",   # Set to "NEVER" for full automation
    max_consecutive_auto_reply=0,
    code_execution_config=False
)

# -------------------------------------------------------
# Group chat and manager
# -------------------------------------------------------
groupchat = GroupChat(
    agents=[planner, researcher, writer, editor, human_proxy],
    messages=[],
    max_round=15,
    speaker_selection_method="auto"   # Let the manager decide turns
)

manager = GroupChatManager(
    groupchat=groupchat,
    llm_config={"config_list": config_list}
)

# -------------------------------------------------------
# Launch the pipeline
# -------------------------------------------------------
task = "Write a blog post about the top 5 AI trends in 2025."
human_proxy.initiate_chat(
    manager,
    message=task
)

Let's walk through the key parts.

Running the Content Writing Pipeline

When you execute the script, the conversation proceeds automatically:

  1. Human Proxy sends the task: "Write a blog post about the top 5 AI trends in 2025."
  2. Planner responds with a markdown outline containing sections like "1. Multimodal AI", "2. AI Agents", etc., each with bullet points.
  3. Researcher appends facts and sources to each section (e.g., "According to Gartner, by 2026 80% of enterprises will use AI agents").
  4. Writer receives the enriched outline and composes a full blog post in a friendly tone, weaving in the research.
  5. Editor reviews the draft, fixes any awkward phrasing, checks that statistics match the research notes, and outputs the final article.
  6. If human_input_mode="ALWAYS", the Human Proxy pauses and asks you to approve or request changes. If approved, the conversation ends; otherwise, you can give feedback that loops back to the appropriate agent.

Here's a simplified snippet of what the conversation looks like in the console (abridged):

Planner: ## Outline: Top 5 AI Trends in 2025
1. Multimodal AI
   - Combining text, image, audio...
...

Researcher: ### Research Notes
1. Multimodal AI
   - Fact: OpenAI's GPT-4 already processes images...
   - Source: OpenAI Blog, 2024
...

Writer: # The 5 AI Trends That Will Define 2025
(Full draft article...)

Editor: (Polished final version...)

Best Practices for Production-Grade Content Agents

1. Craft Precise System Messages

The quality of the output depends heavily on how you define each agent's role. Use clear verbs, specify the exact output format (markdown, plain text), and set boundaries. For example, tell the Researcher: "Do NOT write full paragraphs" to prevent it from stealing the Writer's job. Iterate on system messages by observing the conversation logs and tightening constraints.

2. Implement Human-in-the-Loop Wisely

Use human_input_mode="TERMINATE" or "ALWAYS" only at critical checkpoints—after the outline, after the draft, or after the final edit. Too many interruptions slow down the pipeline. You can also create multiple Human Proxy agents with different modes for different stages.

3. Control Model Usage and Cost

Assign different models to agents based on task complexity. For example:

Set max_tokens in each agent's llm_config to avoid runaway costs.

4. Integrate External Data Sources

The Researcher agent can be enhanced by giving it access to a web search tool or a vector database. In AutoGen, you can register functions that the agent can call. For instance, wrap a SerpAPI call as a tool and describe it in the system message. This transforms the agent from relying purely on LLM internal knowledge to retrieving real-time data.

5. Log and Monitor Conversations

AutoGen provides built-in logging. Enable it with:

import autogen
autogen.ChatAgent.logger.set_level(logging.DEBUG)

Save the complete message history for each run. This log is invaluable for auditing, debugging agent behavior, and refining prompts.

6. Add Error Handling and Retries

Wrap the initiate_chat call in a try-except block to handle API failures gracefully. Use the max_consecutive_auto_reply parameter to prevent infinite loops. If an agent produces an empty or malformed response, the GroupChatManager will automatically select another speaker, but you can also implement a custom speaker selection function for more control.

7. Cache Responses

AutoGen supports response caching to avoid repeating identical LLM calls during development or for repeated topics. Set use_cache=True in the llm_config to enable disk caching. This speeds up iterations and reduces cost.

8. Iterate on the Workflow

Start with the simple linear pipeline described here, then experiment with more complex patterns: add a fact-checker agent, split the Writer into a drafter and a copywriter, or introduce a SEO specialist agent. AutoGen's group chat architecture makes it easy to add or remove agents without rewriting the entire script.

Conclusion

Building a content writing agent with AutoGen transforms a one-shot LLM prompt into a collaborative, multi-stage editorial process. You gain fine-grained control over quality, tone, and factual accuracy while keeping humans in the loop exactly where needed. By following the design patterns and best practices outlined in this guide, you can create a robust, scalable content pipeline that adapts to blogs, technical documentation, marketing copy, or any other written format. Start with the provided code, customize the system messages for your brand voice, and gradually enhance the workflow with tools and specialized models. The result is a reliable AI teammate that accelerates your content production without sacrificing quality.

— Ad —

Google AdSense will appear here after approval

← Back to all articles