How to use Agency Swarm for open source

open-source入门20 分钟阅读2026/7/2

Last month, I hit a wall with a client project. We were building an automated content pipeline—research, drafting, editing, formatting—and I'd been stringing together individual API calls with a mess of Python scripts. Every time one step failed, the whole chain collapsed. I'd spend hours debugging why the "editor" step was receiving malformed input from the "drafter" step. The code was becoming unmaintainable.

I needed a framework that let me define distinct roles, give each one specific tools, and let them talk to each other without me hand-holding every message. After experimenting with a few options that felt either too rigid or too abstract, I found Agency Swarm. It's an open-source framework built on top of the OpenAI Agents SDK that models multi-agent systems after real-world organizations. That clicked for me—instead of thinking about "nodes" and "edges," I could think about a CEO agent, a researcher agent, and a writer agent, each with their own job description.

Here's how I got it working, including the parts that tripped me up.

Setting Up Agency Swarm

First, install the framework:

pip install agency-swarm

You'll need an OpenAI API key set in your environment:

export OPENAI_API_KEY="sk-your-key-here"

This was straightforward. The surprise came when I tried to run my first agent without setting the key properly—I got a cryptic Pydantic validation error instead of a clear "missing API key" message. So learn from my mistake: double-check your environment variable before diving deeper.

Building Your First Agent

Agency Swarm lets you define agents by extending a base Agent class. Each agent gets a role description, which serves double duty: it guides the agent's behavior, and it tells other agents what this agent can do. This is crucial—agents discover each other's capabilities through these descriptions alone.

Here's a concrete example of a researcher agent I built:

from agency_swarm import Agent

class Researcher(Agent):
    def __init__(self):
        super().__init__(
            name="Researcher",
            description="Conducts thorough web research on given topics and returns structured findings with sources.",
            instructions="""You are a research specialist. When given a topic:
1. Search for relevant, recent information
2. Verify facts across multiple sources when possible
3. Structure your findings with clear headings
4. Always include source URLs
5. Flag any information you couldn't verify""",
            model="gpt-4o",
            tools=[],
        )

The description field is what other agents see. The instructions field is private—it's the system prompt that shapes behavior. I initially put too much detail in the description and not enough in instructions, which meant other agents were trying to micromanage the researcher instead of just handing off topics. Once I separated concerns—short description for communication, detailed instructions for behavior—things worked much better.

Creating Custom Tools

This is where Agency Swarm shines. Agents need tools to actually do things, and the framework makes it easy to build them with Pydantic validation. Every tool parameter gets type-checked, which prevents the hallucination problem I was hitting before—agents can't pass a string where an integer is expected.

Here's a tool I built for the researcher to save findings:

from agency_swarm import Tool
from pydantic import Field, HttpUrl
from typing import List

class SaveResearch(Tool):
    """Save research findings to a structured file."""
    
    topic: str = Field(
        ..., description="The research topic"
    )
    findings: str = Field(
        ..., description="Key findings in markdown format"
    )
    sources: List[HttpUrl] = Field(
        ..., description="List of source URLs used"
    )
    confidence: int = Field(
        ..., description="Confidence level 1-5", ge=1, le=5
    )

    def run(self):
        filename = f"research/{self.topic.replace(' ', '_')}.md"
        content = f"# {self.topic}\n\n{self.findings}\n\n## Sources\n"
        for source in self.sources:
            content += f"- {source}\n"
        content += f"\nConfidence: {self.confidence}/5"
        
        with open(filename, 'w') as f:
            f.write(content)
        
        return f"Research saved to {filename}"

The Pydantic validation caught a real bug during testing: the agent tried to pass confidence: "high" instead of an integer. The framework automatically corrected it and asked the agent to retry with the right type. That's the error correction feature in action, and it saved me from writing a bunch of manual validation code.

Wiring Agents Into an Agency

An Agency is the orchestrator that connects agents and manages their communication. Here's how I set up a simple content pipeline:

from agency_swarm import Agency

class Writer(Agent):
    def __init__(self):
        super().__init__(
            name="Writer",
            description="Writes engaging content based on research findings.",
            instructions="""You are a skilled writer. Take research findings and craft 
well-structured, engaging content. Match the tone requested. Always cite sources 
from the research provided.""",
            model="gpt-4o",
            tools=[],
        )

class Editor(Agent):
    def __init__(self):
        super().__init__(
            name="Editor",
            description="Reviews and improves written content for clarity, grammar, and style.",
            instructions="""You are a strict editor. Review content for:
- Grammar and spelling errors
- Logical flow and structure
- Factual consistency with provided research
- Appropriate tone
Return the edited version with a summary of changes.""",
            model="gpt-4o",
            tools=[],
        )

researcher = Researcher()
writer = Writer()
editor = Editor()

agency = Agency(
    name="ContentAgency",
    agents=[researcher, writer, editor],
    communication_flows=[
        (researcher, writer),
        (writer, editor),
        (editor, writer),  # Editor can send revisions back
    ],
    shared_instructions="Focus on producing high-quality, accurate content.",
)

The communication_flows define who can talk to whom. I initially made the mistake of allowing all agents to talk to all other agents, which led to chaos—the editor was trying to do research, the researcher was trying to edit. Restricting communication to specific flows forced each agent to stay in its lane.

Running the Agency

To kick off work:

response = agency.get_response(
    message="Research the latest developments in Rust's async ecosystem and write a 500-word summary",
    recipient=researcher
)

The agency automatically routes messages. The researcher does its work, passes findings to the writer, who drafts content, sends it to the editor, and if the editor finds issues, it goes back to the writer. The whole loop runs without manual intervention.

I watched this play out in the logs and it was genuinely satisfying—until the writer hallucinated a source that wasn't in the research. The editor caught it and sent it back for revision. That's the system working as designed.

Using AutoSwarm for Quick Setup

If you want to prototype fast, Agency Swarm includes AutoSwarm, which generates agent configurations automatically:

from agency_swarm import AutoSwarm, AutoSwarmRouter

swarm = AutoSwarm(
    name="QuickContentTeam",
    description="A team that researches and writes technical articles",
)

agency = swarm.create()

This is handy for getting something running quickly, but I found the auto-generated agents needed significant manual tuning for production use. Treat AutoSwarm as a starting point, not a finished product.

Practical Tips and Honest Limitations

After using Agency Swarm for a few weeks, here's what I've learned:

Start with two agents, not five. I built a five-agent pipeline first and spent days debugging communication issues. Once I got a simple researcher-writer pair working reliably, adding more agents was much easier.

Descriptions matter more than you think. Other agents use the description to decide what to ask and how to phrase requests. Vague descriptions lead to confused handoffs. Be specific: "Conducts web research and returns findings in markdown with source URLs" is better than "Does research."

Watch your token costs. Each agent call is a separate API request. My five-agent pipeline burned through tokens fast, especially when the editor and writer got into revision loops. I added a max_revisions parameter to cap this.

The framework is OpenAI-centric. While you can technically use other providers, the tight integration with OpenAI's Responses API means you'll have the smoothest experience sticking with GPT models. If you need Claude or open-source models, expect some friction.

Error handling is good but not magical. The Pydantic validation catches type mismatches, but it can't fix fundamentally confused agents. I still had to iterate on instructions to get reliable behavior.

Deployment is possible but needs work. The framework claims production readiness, and the core orchestration is solid. But you'll need to add your own logging, monitoring, and retry logic for a real production system. I wrapped my agency calls in a try/except with exponential backoff for API rate limits.

Agency Swarm solved my original problem—the content pipeline now runs reliably, and when something fails, I can see exactly which agent and which step broke. The mental model of specialized agents with clear communication channels maps well to how I actually think about workflows. It's not perfect, but it's the most practical multi-agent framework I've used so far.

相关 Agent

O

OpenClaw

开源 AI Agent 框架,用于构建自主工作流

了解更多 →