from-scratch.mdx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. ---
  2. title: "From Scratch"
  3. description: "Quick start guide to building an Agency from scratch."
  4. icon: "code"
  5. ---
  6. <Note>
  7. Use this guide when you need to build everything manually. Otherwise, start from the [Starter Template](/welcome/getting-started/starter-template).
  8. </Note>
  9. <Steps>
  10. <Step title="Set Your OpenAI Key">
  11. Begin by setting your OpenAI API key in the `.env` file. It will be loaded automatically on agency initialization.
  12. ```
  13. OPENAI_API_KEY=sk-...
  14. ```
  15. </Step>
  16. <Step title="Create Project Structure">
  17. When you run the create-agent-template command, it creates the following folder structure for your agent:
  18. <Accordion title="Create the folder with the CLI" defaultOpen={false}>
  19. ```bash
  20. agency-swarm create-agent-template "Developer"
  21. ```
  22. </Accordion>
  23. **Agent Folder Structure:**
  24. ```
  25. /your-agency-path/
  26. └── agent_name/ # Directory for the specific agent
  27. ├── files/ # Directory for files that will be uploaded to openai
  28. ├── schemas/ # Directory for OpenAPI schemas to be converted into tools
  29. ├── tools/ # Directory for tools to be imported by default.
  30. ├── agent_name.py # The agent definition module
  31. ├── __init__.py # Initializes the agent folder as a Python package
  32. └── instructions.md or .txt # Instruction document for the agent
  33. ```
  34. This structure ensures that each agent has its dedicated space with all necessary files to start working on its specific tasks.
  35. **Agency Folder Structure:**
  36. The full structure of the project will look like this:
  37. ```
  38. agency_name/
  39. ├── agent_name/ # Agent folder created with the command above
  40. ├── another_agent/ # Another agent folder
  41. ├── agency.py # Main file where agents are imported and the agency is defined
  42. ├── agency_manifesto.md # Shared instructions and guidelines for all agents
  43. ├── requirements.txt # File listing all dependencies
  44. └── ...
  45. ```
  46. </Step>
  47. <Step title="Create Tools">
  48. You have 2 ways of defining custom tools:
  49. **my_custom_tool.py:**
  50. ```python
  51. from agency_swarm import function_tool
  52. @function_tool
  53. def my_custom_tool(example_field: str) -> str:
  54. """
  55. A brief description of what the custom tool does.
  56. The docstring should clearly explain the tool's purpose and functionality.
  57. It will be used by the agent to determine when to use this tool.
  58. Args:
  59. example_field: Description of the example field, explaining its purpose and usage for the Agent.
  60. Returns:
  61. Result of the tool's operation as a string.
  62. """
  63. # Your custom tool logic goes here
  64. do_something(example_field)
  65. # Return the result of the tool's operation as a string
  66. return "Result of MyCustomTool operation"
  67. ```
  68. <Accordion title="Preferred: BaseTool class version" defaultOpen={false}>
  69. **my_custom_tool_class.py:**
  70. ```python
  71. from agency_swarm.tools import BaseTool
  72. from pydantic import Field
  73. class MyCustomTool(BaseTool):
  74. """
  75. A brief description of what the custom tool does.
  76. The docstring should clearly explain the tool's purpose and functionality.
  77. It will be used by the agent to determine when to use this tool.
  78. """
  79. # Define the fields with descriptions using Pydantic Field
  80. example_field: str = Field(
  81. ..., description="Description of the example field, explaining its purpose and usage for the Agent."
  82. )
  83. # Additional Pydantic fields as required
  84. # ...
  85. async def run(self):
  86. """
  87. The implementation of the run method, where the tool's main functionality is executed.
  88. This method should utilize the fields defined above to perform the task.
  89. Doc string is not required for this method and will not be used by your agent.
  90. """
  91. # Your custom tool logic goes here
  92. do_something(self.example_field)
  93. # Return the result of the tool's operation as a string
  94. return "Result of MyCustomTool operation"
  95. ```
  96. </Accordion>
  97. BaseTool classes support `async def run(...)`, which is preferred for I/O-bound tools.
  98. See [Custom Tools](/core-framework/tools/custom-tools/step-by-step-guide) for full patterns.
  99. </Step>
  100. <Step title="Define Agent Roles">
  101. Adjust the parameters and instructions for each agent.
  102. **developer.py:**
  103. ```python
  104. from agency_swarm import Agent, ModelSettings
  105. from agency_swarm import Reasoning
  106. from .tools.my_custom_tool import my_custom_tool
  107. from .tools.my_custom_tool_class import MyCustomTool
  108. developer = Agent(
  109. name="Developer",
  110. description="Responsible for executing tasks.",
  111. instructions="./instructions.md",
  112. tools=[my_custom_tool, MyCustomTool], # Import tools directly
  113. model="gpt-5.4-mini",
  114. model_settings=ModelSettings(
  115. temperature=0.3,
  116. max_tokens=25000,
  117. reasoning=Reasoning(effort="medium"),
  118. ),
  119. )
  120. ```
  121. `model` and `reasoning` are both set explicitly in this configuration.
  122. <Accordion title="Alternative: load tools/files/schemas from folders" defaultOpen={false}>
  123. ```python
  124. from agency_swarm import Agent, ModelSettings
  125. from agency_swarm import Reasoning
  126. developer = Agent(
  127. name="Developer",
  128. description="Responsible for executing tasks.",
  129. model="gpt-5.4-mini",
  130. instructions="./instructions.md",
  131. tools_folder="./tools",
  132. files_folder="./files",
  133. schemas_folder="./schemas",
  134. model_settings=ModelSettings(
  135. max_tokens=25000,
  136. reasoning=Reasoning(effort="medium"),
  137. ),
  138. )
  139. ```
  140. </Accordion>
  141. **instructions.md:**
  142. ```md
  143. You are a Developer agent responsible for executing tasks.
  144. # Role
  145. You are responsible for writing clean, efficient, and reusable code.
  146. # Process
  147. 1. How to handle incoming requests
  148. 2. When and how to use available tools
  149. 3. How to collaborate with other agents
  150. ```
  151. </Step>
  152. <Step title="Create Agency">
  153. Import your agents and initialize the Agency class.
  154. **agency.py:**
  155. ```python
  156. from agency_swarm import Agency
  157. from .developer import developer
  158. from .ceo import ceo
  159. agency = Agency(
  160. ceo, # Entry point agent as positional argument
  161. communication_flows=[
  162. ceo > developer, # CEO can initiate communication with Developer
  163. ],
  164. shared_instructions='./agency_manifesto.md' # shared instructions for all agents
  165. )
  166. ```
  167. The first positional argument is the entry point agent that users interact with directly. Communication flows are defined separately.
  168. <Note title="Note on Communication Flows">
  169. 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.
  170. </Note>
  171. See [Communication Flows](/core-framework/agencies/communication-flows) for multi-agent setups.
  172. </Step>
  173. <Step title="Run Demo">
  174. There are multiple ways to run the demo. Add one of the following to your `agency.py` file:
  175. **Backend Version (Async):**
  176. ```python
  177. import asyncio
  178. async def main():
  179. result = await agency.get_response("Please create a new website for our client.")
  180. print(result.final_output)
  181. asyncio.run(main())
  182. ```
  183. **Terminal Version:**
  184. ```python
  185. agency.tui()
  186. ```
  187. The first run downloads the matching terminal UI automatically.
  188. <Accordion title="Other run modes" defaultOpen={false}>
  189. **Web Interface:**
  190. ```python
  191. agency.copilot_demo()
  192. ```
  193. **Backend Version (Sync):**
  194. ```python
  195. result = agency.get_response_sync("Please create a new website for our client.")
  196. print(result.final_output)
  197. ```
  198. </Accordion>
  199. </Step>
  200. </Steps>
  201. ## Next Steps
  202. - Learn the core concepts: [Tools Overview](/core-framework/tools/overview), [Agents Overview](/core-framework/agents/overview), and [Agencies Overview](/core-framework/agencies/overview).
  203. - Run your first end-to-end flow with [Running an Agency](/core-framework/agencies/running-agency).
  204. - Deploy your project with [Deployment to Production](/additional-features/deployment-to-production).