Agency Swarm Documentation

repository·main·Indexed 26 days ago

https://github.com/vrsen/agency-swarm

A framework for building multi-agent applications that extends the OpenAI Agents SDK. It enables the creation and orchestration of collaborative AI agent swarms using organizational structures. Key features include custom tool definition via @function_tool or BaseTool, communication flow configuration using the Agency class, and multiple interaction interfaces including Web UI, TUI, and programmatic async/sync methods. It also provides integrations for FastAPI, OpenClaw, and Twilio Realtime API, as well as a centralized Agency Context for state management.

Tokens
66.4K
Snippets
151
Records
293
Agent score
87%

What's inside Agency Swarm

  1. Overview of Agency Swarm

    main
    Agency Swarm is an open-source agent orchestration framework built on the OpenAI Agents SDK / Responses API. It is designed to simplify the creation of collaborative swarms of agents (Agencies) where each agent has distinct roles and capabilities. The framework models automation using real-world entities like agencies and specialized roles to make agent interaction more intuitive.
  2. Key Features of Agency Swarm

    main

    Agency Swarm provides several core capabilities for building agentic workflows:

    • Customizable Agent Roles: Define specific roles (e.g., CEO, virtual assistant, developer) and their functionalities.
    • Full Control Over Prompts: Complete customization of prompts to avoid the restrictions of pre-defined templates.
    • Error Correction: Uses Pydantic-based type validation to prevent hallucinations and ensure data integrity.
    • Efficient Communication: Agents communicate using only their own provided descriptions.
    • Custom Tools: Ability to build custom Python-based tools to connect agents to external APIs and new capabilities.
    • Production Ready: Designed for reliability and deployment in production environments.
  3. Compare Agency Swarm Pricing Plans

    main

    Agency Swarm offers two main subscription tiers based on agency count and credit capacity:

    • Free Tier: $0/month. Includes 25 daily credits, no monthly credits, and supports up to 5 agencies.
    • Pro: $20/month. Includes 25 daily credits, 2,000 monthly credits, and supports unlimited agencies.
  4. Compare Agency Swarm with other multi-agent frameworks

    main

    Agency Swarm is designed for real-world business use cases, prioritizing control, reliability, and lightweight architecture. Key differentiators include:

    • No Predefined Prompts: Unlike CrewAI or AutoGen, Agency Swarm does not write prompts for you, providing full control over agent behavior.
    • Automatic Error Correction: Uses automatic type checking and validation to prevent hallucinations.
    • Uniform Communication Flows: Allows for custom communication flow definitions without rigid constraints.
    • Reliability: Employs robust type checking and validation for all tools using Pydantic, integrated with a guardrails system.
    • Scalability: Adding agents is as simple as passing them to the Agency class.
    • Model Support: Supports over a dozen models via the LiteLLM SDK.

    Comparison Table

    CriteriaAgency SwarmAutoGenCrewAI
    OriginsReal AI agency productionResearch experimentFunding vehicle
    ArchitectureLightweight, minimal abstractions, built on OpenAI Assistants/Responses APIEvent-driven, supports ChatCompletions/AssistantsBuilt on LangChain with high abstraction
    ReliabilityRobust Pydantic type checking & guardrailsType hints but no validationLimited/inconvenient validation via BaseTool
    FlexibilityNo predefined prompts; uniform communicationOverridable predefined prompts; GroupChat orchestrationNumerous predefined prompts; limited customization
    ScalabilityHigh (add agents to Agency class)Moderate (complex graphs need custom orchestration)Moderate (Flows enable conditional orchestration)
    DeployabilityEasy via callback functions and open-source templatesRequires self-hosted SDK deploymentEnterprise platform deployment
    Model SupportHigh (via LiteLLM)ModerateFull open-source support
  5. Understand Agency Swarm credit consumption

    main

    Credits power all agent activities, including replies and multi-step workflows. Usage is based on task complexity and sandbox runtime.

    Key consumption factors:

    • AI Tokens: LLM processing, image generation, etc.
    • Compute: Running agents in sandboxes and execution environments.
    • Agent Builds: Creating, configuring, and deploying agents.
    • File Storage: Managing files created during tasks.
    • Web Searches: Internet searches for task completion.
    • Third-Party Services: Accessing external APIs.

    Important Notes:

    • AI token usage stops when a task completes, but compute usage continues until the sandbox reaches its timeout.
    • Storage and downloads may consume small amounts of credits while agents are idle.
    • Using your own API keys prevents credits from being deducted for AI tokens or third-party services.
  6. Understand Guardrail types in Agency Swarm

    main

    Guardrails are checkpoint functions used to ensure agent behavior remains safe and predictable. They function at two distinct stages of the agent lifecycle:

    1. Input Guardrails: Executed before the agent processes input.
      • Non-strict mode: Returns guidance to the agent.
      • Strict mode: Raises an InputGuardrailTripwireTriggered exception.
    2. Output Guardrails: Executed after the agent drafts an output but before delivery.
      • If validation fails, the agent will retry up to the configured validation_attempts.
      • If retries are exhausted, it raises an OutputGuardrailTripwireTriggered exception.
  7. Import third-party agents into Agency Swarm

    main

    Agency Swarm allows you to import external agent runtimes that operate outside the standard Agency Swarm Python stack. This pattern is used when you want Agency Swarm to maintain control over orchestration while delegating specific tasks to a different agent runtime.

    One supported implementation is the OpenClawAgent, which can be used as a delegated worker within an Agency Swarm agency.

  8. Understand the Agency class and its benefits

    main

    An Agency in Agency Swarm is a collection of Agent instances that collaborate to complete tasks. Using an agency instead of a single agent provides:

    • Fewer Hallucinations: Agents can supervise each other to reduce mistakes.
    • Complex Task Completion: Multiple agents allow for longer sequences of actions.
    • Scalability: You can scale solutions by adding more agents as complexity grows.

    Best Practice: Start with a minimal number of agents and fine-tune them before adding more to avoid debugging difficulties caused by complex interactions.

  9. Configure required environment variables for production

    main

    Before deploying to a production environment, ensure the following environment variables are configured:

    VariableRequiredDescription
    OPENAI_API_KEYYesYour OpenAI API key
    APP_TOKENRecommendedAuthentication token for FastAPI endpoints

    Note: Thread persistence is managed via callbacks that allow you to store conversation history in your chosen database.

  10. Combine multiple multimodal outputs in a single tool

    main

    To return multiple different types of content (e.g., images, text, and files) from a single tool execution, return a list from the run method. This allows the agent to receive a rich set of feedback in one turn.

    from agency_swarm import BaseTool, ToolOutputFileContent, ToolOutputImage, ToolOutputText
    
    class PrepareShowcase(BaseTool):
        """Return rich media and a short description."""
        teaser_a: str = "https://example.com/teaser-a.png"
        teaser_b: str = "https://example.com/teaser-b.png"
        report_id: str = "file-report-123"
    
        def run(self) -> list:
            return [
                ToolOutputImage(image_url=self.teaser_a),
                ToolOutputImage(image_url=self.teaser_b),
                ToolOutputText(text="Gallery updated: Teaser A and Teaser B now live."),
                ToolOutputFileContent(file_id=self.report_id),
            ]
  11. Transfer data between tools and agents

    main

    Data can be transferred between tools and agents using two primary methods:

    1. Agency Context: Access the agency context directly inside your tools.
    2. File Uploads: Create or modify a tool to upload files to storage and return a file ID. This ID can then be consumed by other tools or agents.