> ## Documentation Index
> Fetch the complete documentation index at: https://agency-swarm.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# From Scratch

> Quick start guide to building an Agency from scratch.

> [!NOTE]
>
> Use this guide when you need to build everything manually. Otherwise, start from the [Starter Template](https://agency-swarm.ai/welcome/getting-started/starter-template.md).

**1. Set Your OpenAI Key**

Begin by setting your OpenAI API key in the `.env` file. It will be loaded automatically on agency initialization.

```
OPENAI_API_KEY=sk-...
```

**2. Create Project Structure**

When you run the create-agent-template command, it creates the following folder structure for your agent:

> [accordion] Create the folder with the CLI
>
> ```bash theme={null}
> agency-swarm create-agent-template "Developer"
> ```

**Agent Folder Structure:**

```
/your-agency-path/
└── agent_name/                   # Directory for the specific agent
    ├── files/                    # Directory for files that will be uploaded to openai
    ├── schemas/                  # Directory for OpenAPI schemas to be converted into tools
    ├── tools/                    # Directory for tools to be imported by default.
    ├── agent_name.py             # The agent definition module
    ├── __init__.py               # Initializes the agent folder as a Python package
    └── instructions.md or .txt   # Instruction document for the agent
```

This structure ensures that each agent has its dedicated space with all necessary files to start working on its specific tasks.

**Agency Folder Structure:**

The full structure of the project will look like this:

```
agency_name/
├── agent_name/           # Agent folder created with the command above
├── another_agent/        # Another agent folder
├── agency.py             # Main file where agents are imported and the agency is defined
├── agency_manifesto.md   # Shared instructions and guidelines for all agents
├── requirements.txt      # File listing all dependencies
└── ...
```

**3. Create Tools**

You have 2 ways of defining custom tools:

**my\_custom\_tool.py:**

```python theme={null}
from agency_swarm import function_tool

@function_tool
def my_custom_tool(example_field: str) -> str:
    """
    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.

    Args:
        example_field: Description of the example field, explaining its purpose and usage for the Agent.

    Returns:
        Result of the tool's operation as a string.
    """

    # Your custom tool logic goes here
    do_something(example_field)

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

> [accordion] Preferred: BaseTool class version
>
> **my\_custom\_tool\_class.py:**
>
> ```python theme={null}
> from agency_swarm.tools import BaseTool
> from pydantic import Field
>
> 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."
>     )
>
>     # Additional Pydantic fields as required
>     # ...
>
>     async 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.
>         Doc string is not required for this method and will not be used by your agent.
>         """
>
>         # Your custom tool logic goes here
>         do_something(self.example_field)
>
>         # Return the result of the tool's operation as a string
>         return "Result of MyCustomTool operation"
> ```

BaseTool classes support `async def run(...)`, which is preferred for I/O-bound tools.

See [Custom Tools](https://agency-swarm.ai/core-framework/tools/custom-tools/step-by-step-guide.md) for full patterns.

**4. Define Agent Roles**

Adjust the parameters and instructions for each agent.

**developer.py:**

```python theme={null}
from agency_swarm import Agent, ModelSettings
from agency_swarm import Reasoning
from .tools.my_custom_tool import my_custom_tool
from .tools.my_custom_tool_class import MyCustomTool

developer = Agent(
    name="Developer",
    description="Responsible for executing tasks.",
    instructions="./instructions.md",
    tools=[my_custom_tool, MyCustomTool],  # Import tools directly
    model="gpt-6-luna",
    model_settings=ModelSettings(
        max_tokens=25000,
        reasoning=Reasoning(effort="medium"),
    ),
)
```

`model` and `reasoning` are both set explicitly in this configuration.

> [accordion] Alternative: load tools/files/schemas from folders
>
> ```python theme={null}
> from agency_swarm import Agent, ModelSettings
> from agency_swarm import Reasoning
>
> developer = Agent(
>     name="Developer",
>     description="Responsible for executing tasks.",
>     model="gpt-6-luna",
>     instructions="./instructions.md",
>     tools_folder="./tools",
>     files_folder="./files",
>     schemas_folder="./schemas",
>     model_settings=ModelSettings(
>         max_tokens=25000,
>         reasoning=Reasoning(effort="medium"),
>     ),
> )
> ```

**instructions.md:**

```md theme={null}
You are a Developer agent responsible for executing tasks.

# Role
You are responsible for writing clean, efficient, and reusable code.

# Process
1. How to handle incoming requests
2. When and how to use available tools
3. How to collaborate with other agents
```

**5. Create Agency**

Import your agents and initialize the Agency class.

**agency.py:**

```python theme={null}
from agency_swarm import Agency
from .developer import developer
from .ceo import ceo

agency = Agency(
    ceo,  # Entry point agent as positional argument
    communication_flows=[
        ceo > developer,  # CEO can initiate communication with Developer
    ],
    shared_instructions='./agency_manifesto.md'  # shared instructions for all agents
)
```

The first positional argument is the entry point agent that users interact with directly. Communication flows are defined separately.

> [!NOTE]
>
> In Agency Swarm, communication flows are directional. For instance, in the example above: `ceo > developer`, the CEO can initiate a chat with the Developer, and the Developer can respond in this chat. However, the Developer cannot initiate a chat with the CEO.

See [Communication Flows](https://agency-swarm.ai/core-framework/agencies/communication-flows.md) for multi-agent setups.

**6. Run Demo**

There are multiple ways to run the demo. Add one of the following to your `agency.py` file:

**Backend Version (Async):**

```python theme={null}
import asyncio

async def main():
    result = await agency.get_response("Please create a new website for our client.")
    print(result.final_output)

asyncio.run(main())
```

**Terminal Version:**

```python theme={null}
agency.tui()
```

The first run downloads the matching terminal UI automatically.

> [accordion] Other run modes
>
> **Web Interface:**
>
> ```python theme={null}
> agency.copilot_demo()
> ```
>
> **Backend Version (Sync):**
>
> ```python theme={null}
> result = agency.get_response_sync("Please create a new website for our client.")
> print(result.final_output)
> ```

## Next Steps

* Learn the core concepts: [Tools Overview](https://agency-swarm.ai/core-framework/tools/overview.md), [Agents Overview](https://agency-swarm.ai/core-framework/agents/overview.md), and [Agencies Overview](https://agency-swarm.ai/core-framework/agencies/overview.md).
* Run your first end-to-end flow with [Running an Agency](https://agency-swarm.ai/core-framework/agencies/running-agency.md).
* Deploy your project with [Deployment to Production](https://agency-swarm.ai/additional-features/deployment-to-production.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.