### Initializing Agency Swarm Agent with Few-Shot Examples (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/few-shot-examples.mdx This snippet demonstrates how to pass a list of few-shot examples directly to the `Agent` constructor in Agency Swarm. The `examples` parameter accepts the list defined previously, configuring the agent with the desired interaction patterns from the start. ```python from agency_swarm import Agent agent = Agent( name="CustomerSupportAgent", description="Assists customers with inquiries and provides detailed information.", examples=examples ) ``` -------------------------------- ### Example Agent Instructions in Markdown Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx Provides an example of the content for an agent's instructions file (`instructions.md`), outlining the agent's role and process. This document guides the agent's behavior and task execution. ```markdown 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 ``` -------------------------------- ### Full Custom Tool Example (Calculator) in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/step-by-step-guide.mdx A complete, self-contained example of a custom calculator tool class in Python for the Agency Swarm framework. It demonstrates imports, class definition, input fields, validation, the `run` method, and an independent test block. ```Python # calculator.py from agency_swarm.tools import BaseTool from pydantic import Field, model_validator class Calculator(BaseTool): """ A simple calculator tool that evaluates mathematical expressions. """ expression: str = Field(..., description="The mathematical expression to evaluate.") @model_validator(mode="after") def validate_expression(self): if self.expression.endswith("/0"): raise ValueError("Division by zero is not permitted") def run(self): result = eval(self.expression) return str(result) if __name__ == "__main__": calc = Calculator(expression="2 + 2 * 3") print(calc.run()) # Output should be '8' ``` -------------------------------- ### Install Agency Swarm Dependencies Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Installs the necessary Python packages for Agency Swarm, including selenium, webdriver-manager, selenium_stealth, and gradio, using pip. ```python !pip install agency-swarm selenium webdriver-manager selenium_stealth gradio ``` -------------------------------- ### Provide Few-Shot Examples for Agency Swarm Agent (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/agents/advanced-configuration.mdx Illustrates how to provide few-shot examples to an agent using the `examples` parameter during initialization. The examples follow the message object format specified by OpenAI's API. ```python from agency_swarm import Agent examples=[ { "role": "user", "content": "Hi!", "attachments": [], "metadata": {}, }, { "role": "assistant", "content": "Hi! I am the CEO. I am here to help you with your tasks. Please tell me what you need help with.", "attachments": [], "metadata": {}, } ] agent = Agent( name='MyAgent', examples=examples ) ``` -------------------------------- ### Install Agency Swarm Package (Bash) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/installation.mdx Installs the `agency-swarm` package from PyPI into the currently active Python virtual environment using pip. This command fetches and installs the necessary files. ```bash pip install agency-swarm ``` -------------------------------- ### Installing Development Tools for Code Style Source: https://github.com/vrsen/agency-swarm/blob/main/docs/contributing/contributing.mdx Reiterates the command to install development dependencies, including `ruff` and other linting/formatting tools, as part of the initial setup for code style enforcement. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Install Required Libraries (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/genesis_agency.ipynb Installs the necessary Python packages including agency-swarm, selenium, webdriver-manager, selenium_stealth, and gradio using pip. This is a prerequisite for running the agency and its demo. ```python !pip install agency-swarm selenium webdriver-manager selenium_stealth gradio ``` -------------------------------- ### Defining Settings Load/Save Callbacks (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/agency_async.ipynb Provides example Python functions (`load_settings`, `save_settings`) intended to simulate database operations for managing agent settings. These functions use a global list `settings` as a placeholder for actual database interaction. They are designed to be passed as callbacks to the `Agency` constructor. ```python # settings is an array of objects with your agent settings settings = [] def load_settings(): # your code to load settings from DB here # we simply use a global variable for this example global settings return settings def save_settings(new_settings): # your code to save new_settings to DB here global settings settings = new_settings ``` -------------------------------- ### Run Genesis Agency Demo (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/genesis_agency.ipynb Calls the `demo_gradio()` method on the `test_agency` instance. This method typically starts a local web server hosting a Gradio interface to interact with the agency for demonstration purposes. ```python test_agency.demo_gradio() ``` -------------------------------- ### Assigning Few-Shot Examples to Agency Swarm Agent After Initialization (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/few-shot-examples.mdx This snippet shows an alternative method to provide few-shot examples to an Agency Swarm agent. After the agent object is created, the list of examples is assigned to the `agent.examples` attribute. This allows dynamic updating of the agent's examples. ```python agent = Agent(name="CustomerSupportAgent") agent.examples = examples ``` -------------------------------- ### Installing Git Pre-Commit Hooks Source: https://github.com/vrsen/agency-swarm/blob/main/docs/contributing/contributing.mdx Installs `pre-commit` and sets up its hooks, which automatically run checks like linting and formatting before each commit to maintain code quality. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install Required Libraries (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/os_models_with_astra_assistants_api.ipynb Installs the necessary Python packages `astra-assistants` and `gradio` using pip. This command is typically run in a notebook or environment where shell commands are prefixed with `!`. ```python !pip install astra-assistants gradio ``` -------------------------------- ### Installing and Activating Pre-Commit Hooks - Bash Source: https://github.com/vrsen/agency-swarm/blob/main/CONTRIBUTING.md These commands first install the `pre-commit` framework and then install the pre-commit hooks configured for the Agency Swarm repository. Pre-commit hooks automate code quality checks (like linting and formatting) before each commit, ensuring consistent code style. ```Bash pip install pre-commit pre-commit install ``` -------------------------------- ### Initializing Agency Swarm Agents (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/agency_async.ipynb Demonstrates how to create instances of the `Agent` class from the `agency_swarm` library. Each agent is defined with a name, description, instructions, and an empty list of tools. This sets up the basic building blocks for an agency. ```python from agency_swarm import Agency, Agent ceo = Agent( name="CEO", description="Responsible for client communication, task planning and management.", instructions="You must converse with other agents to ensure complete task execution.", # can be a file like ./instructions.md tools=[], ) test = Agent( name="Test Agent", description="Test agent", instructions="Please always respond with 'test complete'", # can be a file like ./instructions.md tools=[], ) ``` -------------------------------- ### Activate Virtual Environment (Windows Bash) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/installation.mdx Activates the previously created virtual environment on Windows by running the activation script. This makes the environment's Python and installed packages available. ```bash venv\Scripts\activate ``` -------------------------------- ### Defining Thread Load/Save Callbacks (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/agency_async.ipynb Provides example Python functions (`load_threads`, `save_threads`) intended to simulate database operations for managing conversation threads. These functions use a global dictionary `threads` as a placeholder for actual database interaction. They are designed to be passed as callbacks to the `Agency` constructor. ```python # threads is an object threads = {} def load_threads(): # your code to load threads from DB here # we simply use a global variable for this example global threads return threads def save_threads(new_threads): # your code to save new_threads to DB here global threads threads = new_threads ``` -------------------------------- ### Defining an Agent Class in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx Shows how to define a custom agent class by inheriting from `Agent` and initializing it with parameters like name, description, instructions file path, folder paths for files, schemas, and tools, temperature, max prompt tokens, and examples. ```python from agency_swarm import Agent class Developer(Agent): def __init__(self): super().__init__( name="Developer", description="Responsible for executing tasks.", instructions="./instructions.md", files_folder="./files", schemas_folder="./schemas", tools_folder="./tools", temperature=0.3, max_prompt_tokens=25000, examples=[] ) ``` -------------------------------- ### Initialize Basic Browsing Agent Agency and Demo Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Configures and initializes a single-agent agency featuring the BrowsingAgent with specified Selenium settings (e.g., headless mode). It then launches a Gradio-based demo interface for interaction. ```python from agency_swarm import Agency, Agent from agency_swarm.agents import BrowsingAgent, Devid selenium_config = { # your profile path # "chrome_profile_path": "/Users/vrsen/Library/Application Support/Google/Chrome Canary/Profile 1", "headless": False, "full_page_screenshot": False, } browsing_agent = BrowsingAgent(selenium_config=selenium_config) agency = Agency([browsing_agent]) demo = agency.demo_gradio(height=700) # reload the notebook each time you run this cell ``` -------------------------------- ### Launch Custom Agency Gradio Demo Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Launches a Gradio-based demo interface for the custom multi-agent browsing swarm, allowing interaction with the `report_manager`. ```python demo = agency.demo_gradio(height=700) ``` -------------------------------- ### Install Specific agency-swarm Version Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/open-source-models.mdx Install version 0.1.7 of the agency-swarm library, which is recommended for compatibility with most current open-source Assistants API mimics that may not support streaming or Assistants V2 features. ```bash pip install agency-swarm==0.1.7 ``` -------------------------------- ### Launching Gradio Demo (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/agency_async.ipynb Calls the `demo_gradio` method on the `agency` instance. This method is used to launch a web-based user interface built with Gradio, allowing interactive communication with the agency for testing and demonstration purposes. ```python agency.demo_gradio() ``` -------------------------------- ### Start Gradio Interface for Agency Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/open-source-models.mdx Import the `Agency` class and a specific `demo_gradio` function (presumably from `agency-swarm-lab`). Create the agency instance and then call `demo_gradio` with the agency object to launch a Gradio web interface for interacting with the agency. ```Python from agency_swarm import Agency from .demo_gradio import demo_gradio agency = Agency([ceo]) demo_gradio(agency) ``` -------------------------------- ### Installing AgentOps Dependencies (Bash) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/observability.mdx Installs the `agentops` package, a platform for managing and tracking agents. Specifies version `0.4.6` for integration with Agency Swarm, noting its limited support. ```bash pip install agentops==0.4.6 ``` -------------------------------- ### Install Astra Assistants API and Gradio Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/open-source-models.mdx Install the necessary Python packages, `astra-assistants-api` and `gradio`, using pip. These packages are required to use the Astra Assistants API and run the agency with a Gradio interface. ```Bash pip install astra-assistants-api gradio ``` -------------------------------- ### Defining Few-Shot Examples using OpenAI Message Format (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/few-shot-examples.mdx This snippet defines a list of few-shot examples using the OpenAI message object format. Each example is a dictionary with 'role' and 'content' fields, simulating a conversation turn between a user and an assistant. This structure is used by Agency Swarm agents to learn desired interaction patterns. ```python examples = [ { "role": "user", "content": "My device won't turn on.", }, { "role": "assistant", "content": "I'm sorry to hear that. Let's try some troubleshooting steps. First, please press and hold the power button for at least 10 seconds.", }, { "role": "user", "content": "I tried that, but it still won't turn on.", }, { "role": "assistant", "content": "Thank you for trying that. Please connect your device to a charger and check if any lights appear. Let me know what you observe.", } ] ``` -------------------------------- ### Activate Virtual Environment (Mac/Linux Bash) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/installation.mdx Activates the previously created virtual environment on macOS or Linux by sourcing the activation script. This makes the environment's Python and installed packages available. ```bash source venv/bin/activate ``` -------------------------------- ### Initialize Custom Browsing Agency Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Initializes the `Agency` with the defined `report_manager` and `browsing_agent`, establishing their hierarchy and communication paths. Includes shared instructions for all agents in the swarm. ```python agency = Agency( [report_manager, [report_manager, browsing_agent]], shared_instructions="You are a part of a data collection agency with the goal to find the most relevant information about people on the web. Your core value is autonomy and you are free to use any means necessary to achieve your goal. You do not stop until you have found the information you need or you have exhausted all possible means. You always to to compile a comprehensive report with as much information from the web pages as possible.", ) ``` -------------------------------- ### Creating Agency with BrowsingAgent - agency-swarm - Python Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Initializes an `Agency` instance, passing the previously created `browsing_agent` as the sole agent in an array. The `shared_instructions` parameter is set to an empty string. ```python agency = Agency([browsing_agent], shared_instructions="") ``` -------------------------------- ### Installing Langfuse Package (Bash) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/observability.mdx Installs the `langfuse` package, a recommended observability platform for advanced tracing, metrics, and debugging tools with Agency Swarm. Specifies version `2.60.5` for compatibility. ```bash pip install langfuse==2.60.5 ``` -------------------------------- ### Running Genesis Agency CLI Command (Bash) Source: https://github.com/vrsen/agency-swarm/blob/main/README.md Provides the command syntax to start the `genesis` agency via the command line, which assists in creating new agencies and agents interactively. ```bash agency-swarm genesis [--openai_key "YOUR_API_KEY"] ``` -------------------------------- ### Installing FastAPI Integration for Agency Swarm Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/fastapi-integration.mdx This command installs the necessary dependencies for integrating Agency Swarm with FastAPI, enabling the creation of HTTP APIs for agencies and tools. It uses the `[fastapi]` extra to include FastAPI-specific requirements. ```bash pip install agency-swarm[fastapi] ``` -------------------------------- ### Installing Local Tracking Dependencies (Bash) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/observability.mdx Installs the `tiktoken` package, a dependency required for Agency Swarm's lightweight SQLite-based local tracking solution. This package is used for tokenization in the local tracking process. ```bash pip install tiktoken ``` -------------------------------- ### Instantiate Genesis Agency (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/genesis_agency.ipynb Creates an instance of the imported `GenesisAgency` class, assigning it to the variable `test_agency`. This object represents the agency ready to be configured or run. ```python test_agency = GenesisAgency() ``` -------------------------------- ### Installing Test Dependencies for Agency Swarm Source: https://github.com/vrsen/agency-swarm/blob/main/docs/contributing/contributing.mdx Ensures all necessary test dependencies are installed for running the test suite, typically including development tools and testing frameworks. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Import Genesis Agency (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/genesis_agency.ipynb Imports the `GenesisAgency` class from the `agency_swarm.agency.genesis` module, making it available for use in the current script or notebook. ```python from agency_swarm.agency.genesis import GenesisAgency ``` -------------------------------- ### Start Gradio Demo with Agency Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/open-source-models.mdx Instantiate an Agency with the configured agents and then use a specific non-streaming `demo_gradio` method (presumably from agency-swarm-lab) to launch a Gradio interface for interacting with the agency. This is suitable for demonstrating the agency with open-source models that may not support streaming. ```python from agency_swarm import Agency from .demo_gradio import demo_gradio agency = Agency([ceo]) demo_gradio(agency) ``` -------------------------------- ### Install Agency Swarm Python Package Source: https://github.com/vrsen/agency-swarm/blob/main/README.md This command installs or upgrades the Agency Swarm Python package using pip, the standard package installer for Python. The `-U` flag ensures that the package is upgraded to the latest version if it is already installed. ```bash pip install -U agency-swarm ``` -------------------------------- ### Creating Agency Instance with Callbacks (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/agency_async.ipynb Initializes an `Agency` instance using the previously defined `ceo` and `test` agents. It configures the agency to use "threading" for asynchronous operations and registers the `load_threads`, `save_threads`, `load_settings`, and `save_settings` functions as callbacks for persistent storage management. ```python agency = Agency( [ceo, [ceo, test]], async_mode="threading", # only threading is supported for now threads_callbacks={"load": load_threads, "save": save_threads}, settings_callbacks={"load": load_settings, "save": save_settings}, ) ``` -------------------------------- ### Installing Agency Swarm Development Dependencies Source: https://github.com/vrsen/agency-swarm/blob/main/docs/contributing/contributing.mdx Installs the project's core and development dependencies in editable mode, allowing for local modifications to be reflected without reinstallation. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Installing Langchain for Observability Prerequisites (Bash) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/observability.mdx Installs the `langchain` package, which is a prerequisite for using Agency Swarm's observability features. Although Agency Swarm uses Langchain's callback structure, no Langchain code is directly used within Agency Swarm. ```bash pip install langchain ``` -------------------------------- ### Initializing Langfuse Tracking (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/observability.mdx Demonstrates how to initialize Langfuse tracking using `agency_swarm.init_tracking`. It shows examples for initializing a single Langfuse tracker or combining it with other trackers like 'local' for comprehensive monitoring. ```python from agency_swarm import init_tracking # Initialize single tracker init_tracking("langfuse") # Or initialize multiple trackers init_tracking("langfuse") init_tracking("local") # Add local tracking alongside Langfuse ``` -------------------------------- ### Serving Multiple Agencies and Tools with FastAPI Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/fastapi-integration.mdx This Python example illustrates how to deploy multiple Agency Swarm agencies and custom tools as FastAPI endpoints using the `run_fastapi` function from `agency_swarm.integrations.fastapi`. It defines example tools with Pydantic schemas and then registers them along with multiple agencies, generating dedicated endpoints for each. ```python from pydantic import Field from agency_swarm.agency import Agency from agency_swarm.tools import BaseTool from agency_swarm.integrations.fastapi import run_fastapi # Example tools class ExampleTool(BaseTool): example_field: str = Field(..., description="Example input.") def run(self): return "Result of ExampleTool operation" class TestTool(BaseTool): example_field: str = Field(..., description="Example input.") def run(self): return "Result of TestTool operation" # Create agencies agency1 = Agency([agent], name="test_agency_1") agency2 = Agency([agent], name="test_agency_2") run_fastapi( agencies=[agency_test_1, agency_test_2], tools=[ExampleTool, TestTool], ) ``` -------------------------------- ### Adding a Custom Tool to an Agent in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/step-by-step-guide.mdx Integrate the custom tool into an agent by importing its class and including it in the `tools` list during the `Agent` class initialization. This makes the tool available for the agent to use. ```Python from agency_swarm import Agent from .tools.calculator import Calculator agent = Agent( name="MathAgent", tools=[Calculator], # Other agent parameters ) ``` -------------------------------- ### Create Python Virtual Environment (Bash) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/installation.mdx Creates a new Python virtual environment named 'venv' in the current directory using the built-in `venv` module. This isolates project dependencies. ```bash python -m venv venv ``` -------------------------------- ### Creating Tools from OpenAPI Schema using ToolFactory (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/tool-factory.mdx Illustrates how to generate tools from an OpenAPI schema using the `ToolFactory.from_openapi_schema` method. Shows examples for loading the schema from a local file and fetching it from a URL. ```python import requests from agency_swarm.tools import ToolFactory # Using a local OpenAPI schema file with open("schemas/your_schema.json") as f: tools = ToolFactory.from_openapi_schema(f.read()) # Using an OpenAPI schema from a URL tools = ToolFactory.from_openapi_schema( requests.get("https://api.example.com/openapi.json").json() ) ``` -------------------------------- ### Call Gradio Demo Function (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/os_models_with_astra_assistants_api.ipynb Invokes the `demo_gradio` function, passing the `agency` object and a specified height parameter. This call initiates the setup and launch process for the Gradio interface. ```python demo_gradio(agency, height=900) ``` -------------------------------- ### Example Pytest Tool Test Case - Python Source: https://github.com/vrsen/agency-swarm/blob/main/CONTRIBUTING.md This Python function demonstrates a basic `pytest` test case for a custom tool. It instantiates `MyCustomTool` with an example field, calls its `run()` method, and then asserts that a specific 'expected output' is present in the result, ensuring the tool's core functionality works as expected. ```Python def test_my_tool_example(): tool = MyCustomTool(example_field="test value") result = tool.run() assert "expected output" in result ``` -------------------------------- ### Configure Model API Keys (.env) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/os_models_with_astra_assistants_api.ipynb Examples of environment variable configurations for a `.env` file to store API keys for various language models (Perplexity AI, Anthropic, Together, Groq). These keys are needed if using models other than the default OpenAI models. ```env PERPLEXITYAI_API_KEY=your_perplexityai_api_key ANTHROPIC_API_KEY=your_anthropic_api_key TOGETHER_API_KEY=your_together_api_key GROQ_API_KEY=your_groq_api_key ``` -------------------------------- ### Initialize Browsing Agent (Custom Swarm) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Initializes the `BrowsingAgent` instance with specific Selenium configuration, including disabling headless mode, for use within the custom multi-agent swarm. ```python selenium_config = { # your profile path # "chrome_profile_path": "/Users/vrsen/Library/Application Support/Google/Chrome/Profile 1", "headless": False, "full_page_screenshot": False, } browsing_agent = BrowsingAgent(selenium_config=selenium_config) ``` -------------------------------- ### Running Agency Demo with Gradio - agency-swarm - Python Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Executes the `demo_gradio` method on the `agency` instance, launching a Gradio interface to interact with the agency. The `height` parameter is set to 600 pixels. Notes about reloading the notebook and avoiding browser window resizing are included. ```python # Reload the notebook each time you run this cell # Additionally, do not change browser window size, or it will not work agency.demo_gradio(height=600) ``` -------------------------------- ### Setting OpenAI API Key - agency-swarm - Python Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Imports the `set_openai_key` function from `agency_swarm` and calls it to configure the OpenAI API key for the library. Replace "YOUR_OPENAI_API_KEY" with your actual key. ```python from agency_swarm import set_openai_key set_openai_key("YOUR_OPENAI_API_KEY") ``` -------------------------------- ### Configuring Langfuse Tracking (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/additional-features/observability.mdx Provides optional configuration examples for Langfuse tracking. It shows how to pass additional options like `debug`, `host`, and `user_id` when initializing, and how to directly pass `public_key` and `secret_key` for multi-user applications. ```python # Using environment variables with additional options init_tracking("langfuse", debug=True, host="custom-host", user_id="user-123") # Direct API key passing (useful for multi-user applications) init_tracking("langfuse", public_key="your-public-key", secret_key="your-secret-key") ``` -------------------------------- ### Installing Development Dependencies for Testing - Bash Source: https://github.com/vrsen/agency-swarm/blob/main/CONTRIBUTING.md This command installs the Agency Swarm project in editable mode along with its development dependencies, specifically required to run the test suite. It ensures that all necessary testing tools and packages are available. ```Bash pip install -e ".[dev]" ``` -------------------------------- ### Implementing the Tool's run Method in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/step-by-step-guide.mdx Implement the core functionality of the tool within the `run` method. This method is automatically called when the tool is invoked by an agent. It should perform the tool's task and return a string representing the output. ```Python def run(self): # Implement the tool's functionality result = eval(self.expression) return str(result) ``` -------------------------------- ### Defining a Custom Tool Class in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/step-by-step-guide.mdx Define a new class that inherits from `BaseTool`. The class docstring is essential as it serves as the primary documentation for agents, explaining the tool's purpose. ```Python class Calculator(BaseTool): """ A simple calculator tool that evaluates mathematical expressions. """ ``` -------------------------------- ### Provide Hints in Tool Output with Agency Swarm (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/best-practices.mdx Shows how to use the tool's return value or exceptions (like `ValueError`) to guide the agent on the next steps, especially when a desired outcome isn't met (e.g., no data found). This allows the tool to provide explicit instructions to the agent. ```python class QueryDatabase(BaseTool): question: str = Field(...) def run(self): # query your database here context = self.query_database(self.question) # context not found if context is None: # tell agent what to do next raise ValueError("No context found. Please propose to the user to change the topic.") else: # return the context to the agent return context ``` -------------------------------- ### Initializing the Agency in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx Demonstrates how to import defined agent classes (like `Developer` and `CEO`), create instances of them, and initialize the main `Agency` class with a list of agents. The first agent in the list typically serves as the entry point. ```python from agency_swarm import Agency from .Developer import Developer from .CEO import CEO developer = Developer() ceo = CEO() agency = Agency( [ ceo # CEO will be the entry point for communication with the user ] ) ``` -------------------------------- ### Instantiating BrowsingAgent - agency-swarm - Python Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Creates an instance of the `BrowsingAgent` class. It configures Selenium with `headless` set to `False`, meaning the browser window will be visible during execution. An optional `chrome_profile_path` is commented out. ```python browsing_agent = BrowsingAgent( selenium_config={ # "chrome_profile_path": "/Users/vrsen/Library/Application Support/Google/Chrome Canary/Profile 5", # path to your canary chrome profile "headless": False, # set to True if you don't want to see the browser } ) ``` -------------------------------- ### Importing Agency and BrowsingAgent - agency-swarm - Python Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Imports the core `Agency` class and the `BrowsingAgent` class from the `agency_swarm` library, which are required to define and use an agent agency with browsing capabilities. ```python from agency_swarm import Agency from agency_swarm.agents import BrowsingAgent ``` -------------------------------- ### Creating and Activating Python Virtual Environment Source: https://github.com/vrsen/agency-swarm/blob/main/docs/contributing/contributing.mdx Creates a new Python virtual environment named `.venv` and activates it, isolating project dependencies from the global Python installation. ```bash python -m venv .venv source .venv/bin/activate # On Windows use `.venv\Scripts\activate` ``` -------------------------------- ### Import Agency and Agent Classes (Custom Swarm) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Imports the necessary base classes `Agency` and `Agent`, along with the specific `BrowsingAgent`, for defining the custom multi-agent swarm. ```python from agency_swarm import Agency, Agent from agency_swarm.agents import BrowsingAgent ``` -------------------------------- ### Configure Astra DB Token (.env) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/os_models_with_astra_assistants_api.ipynb Example configuration line for a `.env` file to set the `ASTRA_DB_APPLICATION_TOKEN`. This token is required for authenticating with Astra DB using `astra-assistants`. ```env ASTRA_DB_APPLICATION_TOKEN=AstraCS:... ``` -------------------------------- ### Adding Tools via tools_folder in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/step-by-step-guide.mdx Alternatively, specify a `tools_folder` path during agent initialization. Agency Swarm will automatically discover and load tools from Python files within this directory, provided the class name matches the file name. ```Python from agency_swarm import Agent agent = Agent( name="MathAgent", tools_folder="./tools", # Other agent parameters ) ``` -------------------------------- ### Setting OpenAI API Key in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx Demonstrates how to set the OpenAI API key programmatically using the `set_openai_key` function from the `agency` library. This is an alternative to using an environment file. ```python from agency import set_openai_key set_openai_key("YOUR_API_KEY") ``` -------------------------------- ### Set OpenAI API Key (Custom Swarm) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Sets the OpenAI API key programmatically, required for agents in the custom browsing swarm that use OpenAI services. ```python # don't run this cell if you have already set the key in environment variables from agency_swarm import set_openai_key set_openai_key("YOUR_OPENAI_API_KEY") ``` -------------------------------- ### Creating Agent Directory Structure with CLI Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx Provides the command-line syntax for using `agency-swarm create-agent-template` to generate the standard folder structure for a new agent, including options for name, description, path, and instruction file type. ```bash agency-swarm create-agent-template --name "AgentName" --description "Agent Description" [--path "/path/to/directory"] [--use_txt] ``` -------------------------------- ### Defining Tool Input Fields with Pydantic in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/step-by-step-guide.mdx Use Pydantic's `Field` to define the input parameters the tool expects. The `description` argument is crucial for informing the agent about the purpose and format of the required input. ```Python expression: str = Field(..., description="The mathematical expression to evaluate.") ``` -------------------------------- ### Set OpenAI API Key (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/genesis_agency.ipynb Imports the `set_openai_key` function from `agency_swarm` and sets the OpenAI API key required for the agency to function. Replace 'YOUR_OPENAI_API_KEY' with your actual key. ```python from agency_swarm import set_openai_key set_openai_key("YOUR_OPENAI_API_KEY") ``` -------------------------------- ### Running Agency Swarm Demo with Gradio Web Interface (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx This line runs the Agency Swarm demo using a Gradio web interface, providing a graphical user interface for interaction. The `height` parameter sets the height of the embedded interface. ```python agency.demo_gradio(height=900) ``` -------------------------------- ### Specifying Custom Settings Path for Agency (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/agencies/agency-parameters.mdx This example demonstrates how to use the `settings_path` parameter when initializing the `Agency` class. This allows you to specify a custom file path (e.g., 'my_settings.json') for storing the agency's state and configuration instead of using the default `settings.json` file. ```python agency = Agency([ceo], settings_path='my_settings.json') ``` -------------------------------- ### Enable Gradio Queueing and Launch Demo (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/os_models_with_astra_assistants_api.ipynb Enables queuing for the Gradio application, allowing it to handle multiple requests concurrently and potentially stream intermediate outputs. It then launches the Gradio web interface, disabling sharing and enabling debug mode. ```python # Enable queuing for streaming intermediate outputs demo.queue() # Launch the demo demo.launch(share=False, debug=True) return demo ``` -------------------------------- ### Importing BaseTool and Pydantic in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/step-by-step-guide.mdx Import necessary modules and classes for creating a custom tool in Agency Swarm. This includes `BaseTool` from `agency_swarm.tools` and data validation components like `Field` and `model_validator` from `pydantic`. ```Python from agency_swarm.tools import BaseTool from pydantic import Field, model_validator # ... other imports ``` -------------------------------- ### Running Agency Swarm Demo as Backend Completion (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx This line runs the Agency Swarm as a backend process to get a completion for a specific prompt. The `yield_messages=False` argument indicates that the function should return the final output rather than yielding messages during execution. ```python completion_output = agency.get_completion("Please create a new website for our client.", yield_messages=False) ``` -------------------------------- ### Include Test Case for Agency Swarm Tool (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/best-practices.mdx Provides an example of how to include a simple test case within the tool's file using the `if __name__ == "__main__":` block, allowing for quick testing and verification of the tool's functionality during development. ```python if __name__ == "__main__": # Test the EmailSender tool email_sender = EmailSender( chain_of_thought="Plan to inform the team about the update.", recipient="user@example.com", subject="Project Update", body="The project is on track." ) assert email_sender.run() == "Email sent successfully." ``` -------------------------------- ### Defining an Agent Class in Agency Swarm (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/agents/overview.mdx This snippet shows the basic structure for defining a custom agent class by inheriting from `agency_swarm.Agent`. It demonstrates how to initialize the agent with core parameters like name, description, instruction file paths, folder paths for files, schemas, and tools, as well as configuration options like temperature, max prompt tokens, and examples. It requires the `Agent` class from `agency_swarm`. ```Python from agency_swarm import Agent class AgentName(Agent): def __init__(self): super().__init__( name="agent_name", description="agent_description", instructions="./instructions.md", files_folder="./files", schemas_folder="./schemas", tools_folder="./tools", tools=[], temperature=0.3, max_prompt_tokens=25000, examples=[] ) ``` -------------------------------- ### Running Agency Swarm Demo in Terminal (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx This line executes the Agency Swarm demo directly in the terminal, providing a command-line interface for interaction. ```python agency.run_demo() ``` -------------------------------- ### Add Parent Directory to Python Path (Captcha Example) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Modifies the Python system path to include the parent directory, necessary for importing local modules for the captcha-breaking example. ```python import sys sys.path.insert(0, "../") ``` -------------------------------- ### Testing a Custom Tool Independently in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/tools/custom-tools/step-by-step-guide.mdx Include a standard `if __name__ == "__main__":` block to allow the tool to be tested directly as a script. This helps verify its functionality and behavior independently before integrating it into an agent workflow. ```Python if __name__ == "__main__": calc = Calculator(expression="2 + 2 * 3") print(calc.run()) # Output should be '8' ``` -------------------------------- ### Sending Another Message to Agency (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/agency_async.ipynb Demonstrates sending a second text message ("Check status") to the `agency` instance using the `get_completion` method. Similar to the previous call, `yield_messages=False` is used. This shows how to interact with the agency after initialization. ```python agency.get_completion("Check status", yield_messages=False) ``` -------------------------------- ### Sending Message to Agency (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/agency_async.ipynb Demonstrates sending a simple text message ("Say hi to test agent") to the initialized `agency` instance using the `get_completion` method. The `yield_messages=False` argument indicates that the method should return the final response rather than yielding messages incrementally. ```python agency.get_completion("Say hi to test agent", yield_messages=False) ``` -------------------------------- ### Setting OpenAI API Key in .env File Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx Shows the format for setting the OpenAI API key within a `.env` file. This is a common practice for managing sensitive credentials. ```env OPENAI_API_KEY=sk-... ``` -------------------------------- ### Defining a Custom Tool in Python Source: https://github.com/vrsen/agency-swarm/blob/main/docs/welcome/getting-started/from-scratch.mdx Illustrates how to create a custom tool by inheriting from `BaseTool`, defining input fields using Pydantic `Field`, and implementing the `run` method to perform the tool's core logic. The docstring is used by the agent to understand the tool's purpose. ```python 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 # ... 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" ``` -------------------------------- ### Add Parent Directory to Python Path Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Modifies the Python system path to include the parent directory, which is often necessary when running examples from a subdirectory within a larger project. ```python import sys sys.path.insert(0, "../") ``` -------------------------------- ### Initializing Agency with Shared Instructions (Python) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/core-framework/agencies/agency-parameters.mdx This Python snippet demonstrates how to initialize the `Agency` class and link it to a shared instructions file. The `shared_instructions` parameter is used to specify the file path (e.g., 'agency_manifesto.md') containing the common guidelines for all agents in the agency. ```python agency = Agency( agency_chart=[...], shared_instructions='agency_manifesto.md', ... ) ``` -------------------------------- ### Add Parent Directory to Python Path (Custom Swarm) Source: https://github.com/vrsen/agency-swarm/blob/main/notebooks/web_browser_agent.ipynb Modifies the Python system path to include the parent directory, necessary for importing local modules when setting up the custom browsing swarm example. ```python import sys sys.path.insert(0, "../") ``` -------------------------------- ### Initialize ChatComponent with Additional Instructions (HTML/JS) Source: https://github.com/vrsen/agency-swarm/blob/main/docs/platform/additional-instructions.mdx Demonstrates how to embed the ChatComponent widget and pass dynamic user or session data using the `additionalInstructions` parameter in the `ChatComponent.init()` function. This allows the agent to receive context like user preferences or identifiers directly upon initialization. Requires the ChatComponent script to be loaded. ```HTML