---
description: AI Agent Creator Instructions for Agency Swarm Framework
alwaysApply: true
---

Agency Swarm **v1.0.0** is the latest version of the framework built on the OpenAI Agents SDK. It allows anyone to create a collaborative swarm of agents (Agencies), each with distinct roles and capabilities. Your primary role is to architect tools and agents that fulfill specific needs within the agency. Helpful references for building agents include:

- Official docs: <https://agency-swarm.ai>
- Source code: <https://github.com/VRSEN/agency-swarm>
- Examples repository: <https://github.com/VRSEN/agency-swarm/tree/main/examples>
- Migration guide: <https://agency-swarm.ai/migration/guide>

Use these resources to familiarize yourself with v1.x patterns (the `/examples` directory is up to date, while `/docs` may still contain v0.x references). The following steps outline how to build agents from a single prompt:


1. **PRD Creation:** Gather information to draft a Product Requirements Document (PRD) for the agency.
2. **Folder Structure and Template Creation:** Create the Agent Templates for each agent using the CLI Commands provided below.
3. **Tool Development:** Develop each tool and place it in the correct agent's tools folder, ensuring it is robust and ready for production environments.
4. **Agent Creation:** Create agent classes and instructions for each agent, ensuring correct folder structure.
5. **Agency Creation:** Create the agency class in the agency folder, properly defining the communication flows between the agents.
6. **Testing:** Test each tool for the agency, and the agency itself, to ensure they are working as expected.
7. **Iteration:** Repeat the above steps as instructed by the user, until the agency performs consistently to the user's satisfaction.

You will find a detailed guide for each of the steps below.

# Step 1: PRD Creation

First, ask the user to provide all necessary details:
- Agency Name
- Purpose (a high-level description of what the agency aims to achieve, its target market, and its value proposition)
- Communication Flows (between agents and from agents to user)
- Agents (for each agent: name, role, tools with descriptions)

Once you have gathered all details, create the file `agency_name/prd.txt` using the following template:

```md
# [Agency Name]

---

- **Purpose:** [A high-level description of what the agency aims to achieve, its target market, and the value it offers to its clients.]
- **Communication Flows:**
    - **Between Agents:**
        - [Description of the communication protocols and flows between different agents within the agency, including any shared resources or data.]
        - **Example Flow:**
            - **Agent A -> Agent B:** [Description of the interaction, including trigger conditions and expected outcomes.]
            - **Agent B -> Agent C:** [Description of the interaction, including trigger conditions and expected outcomes.]
    - **Agent to User Communication:** [Description of how agents will communicate with end-users, including any user interfaces or channels used.]

---

## Agent Name

### **Role within the Agency**

[Description of the agent's specific role and responsibilities within the agency.]

### Tools

- **ToolName:**
    - **Description**: [Description on what this tool should do and how it will be used]
    - **Inputs**:
        - [name] (type) - description
    - **Validation**:
        - [Condition] - description
    - **Core Functions:** [List of the main functions the tool must perform.]
    - **APIs**: [List of APIs the tool will use]
    - **Output**: [Description of the expected output of the tool. Output must be a string or a JSON object.]

---

...repeat for each agent
```

After the user provides the requested details, proceed to drafting the PRD file right away. Provide file path to the PRD file in the response and ask the user to edit it if needed. Once approved, read the PRD file contents again and proceed to the next step.

### Best Practices

- **4-16 Tools Per Agent**: Each agent should have between 4 and 16 tools. Avoid breaking down the agency into too many agents, unless their responsibilities are significantly different, or the user has requested it.

# Step 2: Folder Structure and Template Creation

After creating the PRD file, create the folder structure and agent templates, for each agent.

Repeat this step for each agent in the agency. Make sure to correctly specify the path to the agency folder.

**Folder Structure**:

After creating the templates, the folder structure is organized as follows:

```
agency_name/
├── agent_name/
│   ├── __init__.py
│   ├── agent_name.py
│   ├── instructions.md
│   └── tools/
│       ├── tool_name1.py
│       ├── tool_name2.py
│       ├── tool_name3.py
│       ├── ...
├── another_agent/
│   ├── __init__.py
│   ├── another_agent.py
│   ├── instructions.md
│   └── tools/
│       ├── tool_name1.py
│       ├── tool_name2.py
│       ├── tool_name3.py
│       ├── ...
├── agency.py
├── agency_manifesto.md
├── requirements.txt
├── .env
└──...
```

**Folder Structure Rules**:

- Agency folder must be named in lowercase, with underscores instead of spaces.
- Each agency and agent has its own dedicated folder.
- Within each agent folder:

  - A 'tools' folder contains all tools for that agent.
  - An 'instructions.md' file provides agent-specific instructions.
  - An '**init**.py' file contains the import of the agent.

- Tool Import Process:

  - Create a file in the 'tools' folder with the same name as the tool class.
  - Tools are automatically imported to the agent class.
  - All new requirements must be added to the requirements.txt file.

- Agency Configuration:
  - The 'agency.py' file is the main file where all new agents are imported.
  - When creating a new agency folder, use descriptive names, like for example: marketing_agency, development_agency, etc.
  - Create a `.env` file in the agency folder and add a placeholder for `OPENAI_API_KEY` and any other API keys that are required by the tools.

Follow this folder structure when further creating or modifying any files.

# Step 3: Tool Creation

Tools are the specific actions that agents can perform. They are defined using pydantic, which provides a convenient interface and automatic type validation. In v1.x you may also use the `@function_tool` decorator to define tools as simple functions. To create a tool:

1. Import Necessary Modules
   Start by importing `BaseTool` from `agency_swarm.tools` and `Field` from `pydantic`. These imports will serve as the foundation for your custom tool class. Import any additional packages necessary to implement the tool's logic based on the user's requirements. Import `load_dotenv` from `dotenv` to load the environment variables.

2. Define Your Tool Class and Docstring
   Create a new class that inherits from `BaseTool`. Write a clear docstring describing the tool's purpose. This docstring is crucial as it helps agents understand how to use the tool. `BaseTool` extends `BaseModel` from pydantic.

3. Specify Tool Fields
   Define the fields your tool will use, utilizing Pydantic's `Field` for clear descriptions and validation. These fields represent the inputs your tool will work with, including only variables that vary with each use. Define any constant variables globally.

4. Implement the `run` Method
   The `run` method is where your tool's logic is executed. Use the fields defined earlier to perform the tool's intended task. It must contain the actual fully functional correct python code. It can utilize various python packages, previously imported in step 1.

5. Test the Tool
   Add a test case at the bottom of the file in if **name** == "**main**": block. It will be used to test the tool later.

### Best Practices

- **Use Python Packages**: Prefer to use various API wrapper packages and SDKs available on pip, rather than calling these APIs directly using requests.
- **Documentation**: The documentation should clearly describe the purpose and functionality of the tool, as well as how to use it.
- **Code Reliability**: Write actual functional code, without placeholders or hypothetical examples.
- **NEVER include API keys as tool inputs**: If a tool needs an API key or access token, always retrieve it from environment variables using the `os` package inside the `run` method. Do not define API keys or tokens as input fields for the tool.
- **Use global variables for constants**: If a tool requires a constant value that doesn't change from use to use (for example, `ad_account_id`, `pull_request_id`, etc.), define it above the tool function instead of passing it as a parameter.
- **Add a test case at the bottom of the file**: Add a test case for each tool in if **name** == "**main**": block. It will be used to test the tool later.

### Complete Example of a Tool File

```python
# MyCustomTool.py
from agency_swarm.tools import BaseTool
from pydantic import Field
import os
from dotenv import load_dotenv

load_dotenv() # always load the environment variables

class MyCustomTool(BaseTool):
    """
    A brief description of what the custom tool does.
    The docstring should clearly explain the tool's purpose and functionality.
    It will be used by the agent to determine when to use this tool.
    """
    # Define the fields with descriptions using Pydantic Field
    example_field: str = Field(
        ..., description="Description of the example field, explaining its purpose and usage for the Agent."
    )

    def run(self):
        """
        The implementation of the run method, where the tool's main functionality is executed.
        This method should utilize the fields defined above to perform the task.
        """
        # Your custom tool logic goes here
        # Example:
        # account_id = "MY_ACCOUNT_ID"
        # api_key = os.getenv("MY_API_KEY") # or access_token = os.getenv("MY_ACCESS_TOKEN")
        # do_something(self.example_field, api_key, account_id)

        # Return the result of the tool's operation as a string
        return "Result of MyCustomTool operation"

if __name__ == "__main__":
    tool = MyCustomTool(example_field="example value")
    print(tool.run())
```

### Using `function_tool` Decorator

Alternatively, tools can be implemented as simple functions using the `@function_tool` decorator.

```python
from agency_swarm import function_tool
import os
from dotenv import load_dotenv

load_dotenv()  # always load environment variables

@function_tool
def my_custom_tool(example_field: str) -> str:
    """A brief description of what the custom tool does."""
    # Your custom tool logic goes here
    return f"Result: {example_field}"

if __name__ == "__main__":
    print(my_custom_tool("example value"))
```

Remember, each tool code snippet you create must be IMMEDIATELY ready to use by the user. It must not contain any mocks, placeholders or hypothetical examples.

### Agency Context (Shared State)

Agency context lets your tools and agents share data without passing it in conversation messages.

```python
from agency_swarm import function_tool

@function_tool
async def my_tool(ctx, arg1: str) -> str:
    ctx.context.set("my_key", arg1)            # Store data
    data = ctx.context.get("my_key", "default")  # Retrieve data
    return data
```

Use agency context for:
- Large data structures that are expensive to pass between agents
- Maintaining state across multiple tool calls
- Sharing data among tools and agents

Best practices:
- Use descriptive keys to avoid conflicts
- Provide default values when calling `get`
- Clean up unneeded data to keep the context small

### MCP Integration

Alternatively to creating custom tools, you can use special MCP servers which already contain predefined tools. In this case, you don't need to create custom tool files for the same functionality or add them to the PRD. You can use MCPs interchangeably with custom tools

```python
from agency_swarm.tools.mcp import MCPServerStdio

filesystem_server = MCPServerStdio(
    # This name determines how the agent accesses the tools (e.g., Filesystem_Server.list_files)
    name="Filesystem_Server",
    params={
        "command": "npx",
        "args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
    },
    cache_tools_list=True
)
# Attach this server to your Agent via the mcp_servers list:
# my_agent = Agent(..., mcp_servers=[sse_server])
# Reference: https://agency-swarm.ai/core-framework/tools/mcp-integration#step-2-define-sse-server-connection-optional
```

# Step 4: Agent Creation

To create an agent:

1. **Create an agent module.**

   In v1.x you instantiate `Agent` directly rather than subclassing. Create a Python file (e.g., `ceo.py`) and instantiate the agent as follows:

   ```python
   from agency_swarm import Agent, ModelSettings

   ceo = Agent(
       name="CEO",
       description="Responsible for client communication, task planning and management.",
       instructions="./instructions.md",
       tools_folder="./tools",
       model_settings=ModelSettings(
           model="gpt-4o",
           temperature=0.5,
           max_completion_tokens=25000,
       ),
   )
   ```

   - **name**: The agent's name, reflecting its role.
   - **description**: A brief summary of the agent's responsibilities.
   - **instructions**: Path to a markdown file containing detailed instructions for the agent.
   - **tools_folder**: Folder containing the tools for the agent. Tool modules are automatically imported. Each tool class must be named the same as the tool file. For example, if the tool class is named `MyTool`, the tool file must be named `MyTool.py`.
   - **Other Parameters**: Additional settings like `model_settings` or persistence callbacks.

   Make sure to create a separate folder for each agent, as described in the folder structure above. After creating the agent, you need to import it into the agency.py file.

2. **Create an `instructions.md` file in the agent's folder.**

   Each agent also needs to have an `instructions.md` file, which is the system prompt for the agent. Inside those instructions, you need to define the following:

   - **Agent Role**: A description of the role of the agent.
   - **Goals**: A list of goals that the agent should achieve, aligned with the agency's mission.
   - **Process Workflow**: A step by step guide on how the agent should perform its tasks. Each step must be aligned with the other agents in the agency, and with the tools available to this agent.

   Use the following template for the instructions.md file:

   ```md
    # Role
    You are **[insert role, e.g., "a helpful expert" or "a creative storyteller".]**

    # Instructions
    **[Provide a step-by-step instructions process on how this process should be performed. Use a numbered list.]**

    # Additional Notes
    - **[Specify any additional notes here, if any. Use bullet points if needed.]**
    ```

### Best Practices

   **Avoid Speculation**: Be conscience when creating the instructions, and avoid any speculation. If certain information is not available, simply leave it blank.

# Step 5: Agency Creation

Agencies are collections of agents that work together to achieve a common goal. They are defined in the `agency.py` file, which you need to create in the agency folder.

1. **Create an `agency.py` file in the agency folder.**

   Import `Agency` from `agency_swarm` and instantiate it with your agents. The first argument is the entry point for user communication.

   ```python
   from dotenv import load_dotenv
   from agency_swarm import Agency
   from ceo import ceo
   from developer import developer
   from virtual_assistant import virtual_assistant

   load_dotenv()

   agency = Agency(
       ceo,
       communication_flows=[
           (ceo, developer),
           (ceo, virtual_assistant),
           (developer, virtual_assistant),
       ],
       shared_instructions="agency_manifesto.md",
   )

   if __name__ == "__main__":
       agency.terminal_demo()
   ```

   **A Note on Communication Flows**:

   Communication flows are directional. In the `communication_flows` parameter above, the agent on the left can initiate conversations with the agent on the right.

2. **Define the `agency_manifesto.md` file.**

   Agency manifesto is a file that contains shared instructions for all agents in the agency. It is a markdown file that is located in the agency folder. Please write the manifesto file when creating a new agency. Include the following details:

   - **Agency Description**: A brief description of the agency.
   - **Mission Statement**: A concise statement that encapsulates the purpose and guiding principles of the agency.
   - **Context**: Additional information provided by the user. For example, their preferences, business details, personal information, etc.

# Step 6: Testing

The final step is to test each tool and the agency itself, to ensure they are working as expected.

1. First, install the dependencies for the agency using the following command:

   ```bash
   pip install -r agency_name/requirements.txt
   ```

2. Then, run each tool file in the tools folder that you created, to ensure they are working as expected.

   ```bash
   python agency_name/agent_name/tools/tool_name.py
   ```

   If any of the tools return an error, you need to fix the code in the tool file.

3. Once all tools are working as expected, you can test the agency by running the following command:

   ```bash
   python agency_name/agency.py
   ```

   If the terminal demo runs successfully, you have successfully created an agency that works as expected.

**Important**: Please do not stop until all new tools and agents have been tested and are working as expected. Do not ask for confirmation or wait for the user to respond. Just keep iterating until the agency performs as expected.

# Step 7: Iteration

Repeat the above steps as instructed by the user, until the agency performs consistently to the user's satisfaction. First, adjust the tools, then adjust the agents and instructions, then test again. Make sure to repeat each step accordingly.

# Final Notes

- NEVER output code snippets or file contents in the chat. Always create or modify the actual files in the file system. If you're unsure about a file's location or content, check the current folder structure and file contents before proceeding. If you find yourself about to output code in the chat, STOP and reconsider your approach.

- When creating or modifying files:

1. Use the appropriate file creation or modification syntax (e.g., ```python:path/to/file.py for Python files).
2. Write the full content of the file, not just snippets or placeholders.
3. Ensure all necessary imports and dependencies are included.
4. Follow the specified file creation order rigorously: 1. tools, 2. agents, 3. agency, 4. requirements.txt.
