### Example Installation Command with Version Source: https://github.com/2fastlabs/agent-squad/blob/main/python/README.md Provides a concrete example of the installation command for the agent-squad package, specifying a hypothetical version number. Ensure the version number matches your 'setup.cfg'. ```bash pip install ./dist/agent_squad-1.2.3-py3-none-any.whl ``` -------------------------------- ### Install Dependencies Source: https://github.com/2fastlabs/agent-squad/blob/main/examples/bedrock-prompt-routing/readme.md Install the necessary libraries for the example. Ensure you have Python 3.11 or higher. ```bash pip install boto3 agent-squad ``` -------------------------------- ### Minimal RealtimeRuntime Setup and Event Handling Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/voice/overview.md Demonstrates the minimal setup for RealtimeRuntime, including initializing the transport, assistant, and runtime, then starting it and processing events. ```swift let transport = URLSessionWebSocketTransport( apiKey: "sk-..." ) let assistant = OpenAIVoiceAssistant( name: "voice-assistant", transport: transport, tools: myToolProvider, userId: "u1", sessionId: UUID().uuidString ) // AudioInput / AudioOutput from AgentSquadAudio: let runtime = RealtimeRuntime( session: assistant, input: MicCapture(), output: AudioPlayback() ) try await runtime.start() for await event in runtime.events { switch event { case .state(let phase): updateUI(phase) case .userTranscript(let text, final: true): showTranscript(text) case .presenterText(let text, final: true): showReply(text) case .error(let msg): print("error:", msg) default: break } } ``` -------------------------------- ### Install Dependencies and Run Server Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/cookbook/examples/fast-api-streaming.md Install the necessary Python packages and start the FastAPI development server. ```bash pip install "fastapi[all]" agent-squad uvicorn app:app --reload ``` -------------------------------- ### Install and Run Chainlit App Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/cookbook/examples/chat-chainlit-app.md Clone the repository, navigate to the example directory, install dependencies, and run the Chainlit application. ```bash git clone https://github.com/2fastlabs/agent-squad.git cd agent-squad/examples/chat-chainlit-app pip install -r requirements.txt chainlit run app.py -w ``` -------------------------------- ### Complete BedrockLLMAgent Configuration Example Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/agents/built-in/bedrock-llm-agent.mdx A comprehensive example demonstrating the initialization of BedrockLLMAgent with all available configuration options, including model ID, region, streaming, retriever, inference settings, guardrails, tools, and custom system prompts. This serves as a template for advanced agent setups. ```typescript import { BedrockLLMAgent } from "agent-squad"; const agent = new BedrockLLMAgent({ // Required fields name: "Advanced Bedrock Assistant", description: "A fully configured AI assistant powered by Bedrock models", // Optional fields modelId: "anthropic.claude-3-sonnet-20240229-v1:0", region: "us-west-2", streaming: true, retriever: customRetriever, // Custom retriever for additional context inferenceConfig: { maxTokens: 500, temperature: 0.7, topP: 0.9, stopSequences: ["Human:", "AI:"], }, guardrailConfig: { guardrailIdentifier: "my-guardrail", guardrailVersion: "1.0", }, toolConfig: { tool: [ { name: "Weather_Tool", description: "Get current weather data", input_schema: { type: "object", properties: { location: { type: "string", description: "City name", }, }, required: ["location"], }, }, ], }, customSystemPrompt: { template: `You are an AI assistant specialized in {{DOMAIN}}. Your core competencies: {{SKILLS}} Communication style: - Maintain a {{TONE}} tone - Focus on {{FOCUS}} - Prioritize {{PRIORITY}}`, variables: { DOMAIN: "scientific research", SKILLS: [ "- Advanced data analysis", "- Statistical methodology", "- Research design", "- Technical writing", ], TONE: "professional and academic", FOCUS: "accuracy and clarity", PRIORITY: "evidence-based insights", }, }, }); ``` ```python from agent_squad.agents import BedrockLLMAgent, BedrockLLMAgentOptions ``` -------------------------------- ### Initialize Project and Install Dependencies Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/cookbook/examples/typescript-local-demo.md Sets up a new Node.js project and installs the agent-squad package. Ensure Node.js and npm are installed. ```bash mkdir test_agent_squad cd test_agent_squad npm init npm install agent-squad ``` -------------------------------- ### Usage Example Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/audio/built-in/audio-playback.md Demonstrates a basic usage pattern for AudioPlayback, including initialization, starting, enqueuing audio, flushing, and stopping. ```APIDOC ## Usage ```swift let playback = AudioPlayback() try await playback.start() // Feed frames as they arrive from the realtime runtime await playback.enqueue(pcm16Frame) // User interrupts — discard buffered audio instantly await playback.flush() await playback.stop() ``` ``` -------------------------------- ### Basic AudioPlayback Usage Example Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/audio/built-in/audio-playback.md Demonstrates the fundamental lifecycle of using AudioPlayback: initialization, starting playback, enqueuing audio frames, flushing for barge-in, and stopping. ```swift let playback = AudioPlayback() try await playback.start() // Feed frames as they arrive from the realtime runtime await playback.enqueue(pcm16Frame) // User interrupts — discard buffered audio instantly await playback.flush() await playback.stop() ``` -------------------------------- ### Run Quickstart Script Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/general/quickstart.mdx Commands to execute the quickstart script using Node.js with TypeScript or standard Python. ```bash npx ts-node quickstart.ts ``` ```bash python quickstart.py ``` -------------------------------- ### Supervisor Agent Example in Python Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/agents/built-in/supervisor-agent.mdx Illustrates the setup of a Supervisor Agent with team members, tools, and storage using Python. This is suitable for coordinating agent tasks in Python environments. ```python from agent_squad.orchestrator import AgentSquad from agent_squad.agents import ( SupervisorAgent, BedrockLLMAgent, SupervisorAgentOptions, BedrockLLMAgentOptions ) from agent_squad.storage import DynamoDBChatStorage from agent_squad.utils import AgentTool, AgentTools # Create orchestrator orchestrator = AgentSquad() # Create supervisor and team supervisor = BedrockLLMAgent(BedrockLLMAgentOptions( name="Team Lead", description="Coordinates specialized team members" )) tech_agent = BedrockLLMAgent(BedrockLLMAgentOptions( name="Tech Support", description="Handles technical issues" )) billing_agent = BedrockLLMAgent(BedrockLLMAgentOptions( name="Billing Expert", description="Handles billing and payment queries" )) # Create custom tools custom_tools = [ AgentTool( name="analyze_sentiment", description="Analyze message sentiment", properties={ "text": { "type": "string", "description": "Text to analyze" } }, required=["text"], func=analyze_sentiment ) ] # Create and add supervisor agent supervisor_agent = SupervisorAgent(SupervisorAgentOptions( lead_agent=supervisor, team=[tech_agent, billing_agent], storage=DynamoDBChatStorage(), trace=True, extra_tools=custom_tools )) orchestrator.add_agent(supervisor_agent) # Process request async def main(): response = await orchestrator.route_request( "I'm having issues with my bill and the mobile app", ``` -------------------------------- ### Run the Example Source: https://github.com/2fastlabs/agent-squad/blob/main/examples/bedrock-prompt-routing/readme.md Execute the main Python script to run the Bedrock Prompt Routing example. ```bash python main.py ``` -------------------------------- ### Install Dependencies Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/README.md Installs all the necessary dependencies for the project. ```bash npm install ``` -------------------------------- ### Install Dependencies and Run Chatbot Source: https://github.com/2fastlabs/agent-squad/blob/main/examples/grounded-agent-chatbot/readme.md Set the ANTHROPIC_API_KEY environment variable, install required packages, and run the main Python script to start the chatbot. ```bash export ANTHROPIC_API_KEY=sk-... pip install -r requirements.txt python main.py ``` -------------------------------- ### Install Dependencies Source: https://github.com/2fastlabs/agent-squad/blob/main/examples/chat-chainlit-app/README.md Install all necessary Python packages listed in the `requirements.txt` file using pip. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Dependencies with Python 3.12 Source: https://github.com/2fastlabs/agent-squad/blob/main/examples/fast-api-streaming/README.MD Set up a virtual environment and install the required Python packages for the project. ```bash python -m venv .venv source .venv/bin/activate pip install -r requirements.txt ``` -------------------------------- ### CDK Configuration Example Source: https://github.com/2fastlabs/agent-squad/blob/main/examples/chat-demo-app/README.md Example of the cdk.json configuration file for the chat-demo-app. Customize agent enablement here. ```json { "context": { "enableLexAgent": true // Additional configurations } } ``` -------------------------------- ### Complete OpenAI Agent Configuration Example (Python) Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/agents/built-in/openai-agent.mdx Provides a full example of initializing an OpenAI Agent in Python with all possible options, including model, streaming, a custom retriever, detailed inference parameters, and a multi-line custom system prompt with variables. An API key is mandatory. ```python from agent_squad import OpenAIAgent, OpenAIAgentOptions agent = OpenAIAgent(OpenAIAgentOptions( # Required fields name='Advanced OpenAI Assistant', description='A fully configured AI assistant powered by OpenAI models', api_key='your-openai-api-key', # Optional fields model='gpt-4', # Choose OpenAI model streaming=True, # Enable streaming responses retriever=custom_retriever, # Custom retriever for additional context # Inference configuration inference_config={ 'maxTokens': 500, # Maximum tokens to generate 'temperature': 0.7, # Control randomness (0-1) 'topP': 0.9, # Control diversity via nucleus sampling 'stopSequences': ['Human:', 'AI:'] # Sequences that stop generation }, # Custom system prompt with variables custom_system_prompt={ 'template': """You are an AI assistant specialized in {{DOMAIN}}. Your core competencies: {{SKILLS}} Communication style: - Maintain a {{TONE}} tone - Focus on {{FOCUS}} - Prioritize {{PRIORITY}}""", 'variables': { 'DOMAIN': 'scientific research', 'SKILLS': [ '- Advanced data analysis', '- Statistical methodology', '- Research design', '- Technical writing' ], 'TONE': 'professional and academic', 'FOCUS': 'accuracy and clarity', 'PRIORITY': 'evidence-based insights' } } )) ``` -------------------------------- ### Complete Anthropic Agent Configuration Example (TypeScript) Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/agents/built-in/anthropic-agent.mdx Demonstrates a comprehensive setup of the Anthropic Agent with all major optional configurations including model, streaming, retriever, and inference settings. ```typescript import { AnthropicAgent } from 'agent-squad'; const agent = new AnthropicAgent({ // Required fields name: 'Advanced Anthropic Assistant', description: 'A fully configured AI assistant powered by Anthropic models', apiKey: 'your-anthropic-api-key', // Optional fields modelId: 'claude-3-opus-20240229', // Choose Anthropic model streaming: true, // Enable streaming responses retriever: customRetriever, // Custom retriever for additional context // Inference configuration inferenceConfig: { maxTokens: 500, // Maximum tokens to generate temperature: 0.7, // Control randomness (0-1) topP: 0.9, // Control diversity via nucleus sampling ``` -------------------------------- ### Clone, Install, and Deploy E-commerce Simulator Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/cookbook/examples/ecommerce-support-simulator.md Follow these bash commands to clone the repository, navigate to the simulator's directory, install dependencies, and deploy the application using AWS CDK. ```bash # Clone repository git clone https://github.com/2fastlabs/agent-squad.git cd agent-squad/examples/ecommerce-support-simulator # Install and deploy npm install cdk bootstrap cdk deploy ``` -------------------------------- ### Install SQL Storage Package Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/storage/sql.mdx Install the necessary package for SQL storage functionality. This includes the `libsql-client` package. ```bash pip install "agent-squad[sql]" ``` -------------------------------- ### Supervisor Agent Example Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/agents/built-in/supervisor-agent.mdx This example demonstrates how to use the Supervisor Agent to send a message and handle both streaming and non-streaming responses. It shows how to initialize the agent and process the output. ```python from autogen import Agent, UserProxyAgent config_list = [ { "model": "gpt-4", "api_key": "sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", } ] # Initialize the Supervisor Agent supervisor = Agent( name="supervisor", system_message="You are a helpful assistant that manages other agents.", llm_config={"config_list": config_list}, ) # Initialize a UserProxyAgent user_proxy = UserProxyAgent( name="user_proxy", human_input_mode="NEVER", code_execution_config=False, system_message="You are a helpful assistant.", llm_config={"config_list": config_list}, ) async def main(): # Define the agents to be managed by the supervisor agent1 = Agent( name="agent1", system_message="You are agent 1.", llm_config={"config_list": config_list}, ) agent2 = Agent( name="agent2", system_message="You are agent 2.", llm_config={"config_list": config_list}, ) # Add agents to the supervisor supervisor.add_agents([agent1, agent2]) # Send a message to the supervisor, which will delegate it to other agents response = await supervisor.a_initiate_chats( [{"message": "Hello agents!"}], # Specify the agents to receive the message recipient_agents=[ agent1, agent2 ], # Specify the sender of the message sender=user_proxy, # Specify the user ID and session ID user_id="user123", session_id="session456" ) # Handle response based on whether it's streaming or not if response.streaming: print("\n** STREAMING RESPONSE **") print(f"Agent: {response.metadata.agent_name}") async for chunk in response.output: print(chunk, end='', flush=True) else: print("\n** RESPONSE **") print(f"Agent: {response.metadata.agent_name}") print(f"Response: {response.output}") # Run the example if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Complete OpenAI Agent Configuration Example (TypeScript) Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/agents/built-in/openai-agent.mdx A comprehensive example of initializing an OpenAI Agent with all available options, including model, streaming, custom retriever, detailed inference configuration, and a complex custom system prompt with variables. Requires an API key. ```typescript import { OpenAIAgent } from 'agent-squad'; const agent = new OpenAIAgent({ // Required fields name: 'Advanced OpenAI Assistant', description: 'A fully configured AI assistant powered by OpenAI models', apiKey: 'your-openai-api-key', // Optional fields model: 'gpt-4', // Choose OpenAI model streaming: true, // Enable streaming responses retriever: customRetriever, // Custom retriever for additional context // Inference configuration inferenceConfig: { maxTokens: 500, // Maximum tokens to generate temperature: 0.7, // Control randomness (0-1) topP: 0.9, // Control diversity via nucleus sampling stopSequences: ['Human:', 'AI:'] // Sequences that stop generation }, // Custom system prompt with variables customSystemPrompt: { template: `You are an AI assistant specialized in {{DOMAIN}}. Your core competencies: {{SKILLS}} Communication style: - Maintain a {{TONE}} tone - Focus on {{FOCUS}} - Prioritize {{PRIORITY}}`, variables: { DOMAIN: 'scientific research', SKILLS: [ '- Advanced data analysis', '- Statistical methodology', '- Research design', '- Technical writing' ], TONE: 'professional and academic', FOCUS: 'accuracy and clarity', PRIORITY: 'evidence-based insights' } } }); ``` -------------------------------- ### Install OpenSearch and Boto3 Packages Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/retrievers/custom-retriever.mdx Install the necessary Python packages for interacting with OpenSearch Serverless and AWS services. ```bash pip install opensearch-py boto3 ``` -------------------------------- ### Full Conformance Example: MyMCPClient Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/mcp/custom.md An example implementation of the MCPClient protocol using an actor. This demonstrates how to replace the default SDK client with a custom one, potentially for different transports or testing. ```APIDOC ## Full conformance example ```swift import Foundation import AgentSquad import AgentSquadMCP /// A custom MCP client backed by a different transport. /// Replace the bodies with your SDK's equivalents. public actor MyMCPClient: MCPClient { private let endpoint: URL public init(endpoint: URL) { self.endpoint = endpoint } // MARK: - MCPClient /// Connect and perform the MCP `initialize` handshake. public func connect() async throws { // e.g. try await mySDK.connect(to: endpoint) } /// List every tool the server advertises, paginating to completion. public func listTools() async throws -> [MCPToolInfo] { // e.g. let sdkTools = try await mySDK.listTools() // return sdkTools.map { // MCPToolInfo( // name: tool.name, // description: tool.description ?? "", // inputSchema: /* convert to JSONValue */, // ui: /* _meta.ui.resourceUri or nil */, // visibility: .all // ) // } return [] } /// Invoke a tool and return the structured result. public func callTool(name: String, arguments: JSONValue) async throws -> MCPCallResult { // e.g. let response = try await mySDK.callTool(name: name, arguments: arguments) // return MCPCallResult( // content: /* [ContentPart] or nil */, // structuredContent: /* JSONValue or nil */, // meta: nil, // isError: response.isError ?? false // ) return MCPCallResult() } /// Fetch an MCP resource — used for `ui://` UI template fetches. public func readResource(uri: String) async throws -> MCPResourceContents { // e.g. let raw = try await mySDK.readResource(uri: uri) // return MCPResourceContents(mimeType: raw.mimeType, text: raw.text) return MCPResourceContents(mimeType: "text/plain") } /// Tear down the connection. Must be idempotent. public func disconnect() async { // e.g. await mySDK.disconnect() } } ``` ``` -------------------------------- ### Basic MicCapture Usage Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/audio/built-in/mic-capture.md Instantiate MicCapture, start it, iterate over captured frames, and then stop it. Ensure start() and stop() are not called concurrently. ```swift let mic = MicCapture() // 24 kHz, 16-frame queue, echo-cancelled try await mic.start() for await frame in mic.frames { // frame: Data containing PCM16 little-endian mono samples } await mic.stop() ``` -------------------------------- ### Full Conformance Example for MyMCPClient Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/mcp/custom.md An example of a custom MCP client implementation named MyMCPClient. This actor conforms to the MCPClient protocol and provides placeholder implementations for each method, demonstrating how to integrate a different transport or create a test double. ```swift import Foundation import AgentSquad import AgentSquadMCP /// A custom MCP client backed by a different transport. /// Replace the bodies with your SDK's equivalents. public actor MyMCPClient: MCPClient { private let endpoint: URL public init(endpoint: URL) { self.endpoint = endpoint } // MARK: - MCPClient /// Connect and perform the MCP `initialize` handshake. public func connect() async throws { // e.g. try await mySDK.connect(to: endpoint) } /// List every tool the server advertises, paginating to completion. public func listTools() async throws -> [MCPToolInfo] { // e.g. let sdkTools = try await mySDK.listTools() // return sdkTools.map { // MCPToolInfo( // name: tool.name, // description: tool.description ?? "", // inputSchema: /* convert to JSONValue */, // ui: /* _meta.ui.resourceUri or nil */, // visibility: .all // ) // } return [] } /// Invoke a tool and return the structured result. public func callTool(name: String, arguments: JSONValue) async throws -> MCPCallResult { // e.g. let response = try await mySDK.callTool(name: name, arguments: arguments) // return MCPCallResult( // content: /* [ContentPart] or nil */, // structuredContent: /* JSONValue or nil */, // meta: nil, // isError: response.isError ?? false // ) return MCPCallResult() } /// Fetch an MCP resource — used for `ui://` UI template fetches. public func readResource(uri: String) async throws -> MCPResourceContents { // e.g. let raw = try await mySDK.readResource(uri: uri) // return MCPResourceContents(mimeType: raw.mimeType, text: raw.text) return MCPResourceContents(mimeType: "text/plain") } /// Tear down the connection. Must be idempotent. public func disconnect() async { // e.g. await mySDK.disconnect() } } ``` -------------------------------- ### Initialize and Run OpenAIVoiceAssistant Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/voice/built-in/openai-voice.md Set up the `OpenAIVoiceAssistant` with a transport, tools, user ID, session ID, storage, voice, and language. Then, initialize `RealtimeRuntime` with the assistant, audio input, and output. Finally, start the runtime and process events. ```swift import AgentSquad let transport = URLSessionWebSocketTransport( apiKey: "sk-..." ) let assistant = OpenAIVoiceAssistant( name: "support-voice", transport: transport, tools: myToolProvider, userId: currentUser.id, sessionId: UUID().uuidString, store: InMemoryChatStorage(), voice: "marin", language: "en" ) let runtime = RealtimeRuntime( session: assistant, input: MicCapture(), output: AudioPlayback() ) try await runtime.start() for await event in runtime.events { switch event { case .state(let phase): updateStatusIndicator(phase) case .userTranscript(let text, final: true): showUserBubble(text) case .presenterText(let text, final: true): showAssistantBubble(text) case .error(let msg): print("voice error:", msg) default: break } } ``` -------------------------------- ### OSLogTracer Output Example Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/tracing/built-in/oslog-tracer.md Example log output from OSLogTracer showing span lifecycle events, including start, end, and usage details. ```text ▶︎ trace "my-request" [] user=- session=- ↳ span "classifier" [] parent=[] ✓ end "classifier" [] 0.012s ↳ gen "claude-3-5-sonnet" model=claude-3-5-sonnet [] parent=[] · usage [] prompt=320 completion=87 ✓ end "claude-3-5-sonnet" [] 1.243s ✓ end "my-request" [] 1.261s ``` -------------------------------- ### ProcessingTracer Usage Example Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/tracing/built-in/processing-tracer.md Demonstrates the common setup for ProcessingTracer by initializing it with an OTLPExporter and then using it with a MultiAgentOrchestrator. ```APIDOC ## Usage ```swift let tracer = ProcessingTracer( exporter: OTLPExporter( endpoint: URL(string: "https://collector.example.com/v1/traces")!, headers: ["Authorization": "Basic "] ) ) let orchestrator = MultiAgentOrchestrator( config: OrchestratorConfig(tracer: tracer) ) ``` ``` -------------------------------- ### URLSessionWebSocketTransport Usage Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/voice/built-in/websocket-transport.md Examples demonstrating how to initialize and use the URLSessionWebSocketTransport with different configurations, including minimal setup and custom endpoints. ```APIDOC ## Usage ```swift import AgentSquad // Minimal — just an API key let transport = URLSessionWebSocketTransport( apiKey: "sk-..." ) // Custom endpoint (e.g. Azure OpenAI or a proxy) let transport = URLSessionWebSocketTransport( url: URL(string: "wss://my-proxy.example.com/v1/realtime")!, model: "gpt-4o-realtime-preview", apiKey: myToken, headers: ["X-Request-ID": requestId] ) let assistant = OpenAIVoiceAssistant( name: "voice-assistant", transport: transport, tools: myToolProvider, userId: "u1", sessionId: UUID().uuidString ) ``` :::caution One `URLSessionWebSocketTransport` instance represents one connection. Never share an instance between two assistants or across reconnects — construct a fresh one each time. ::: ``` -------------------------------- ### Initialize and Run OpenAIGroundedVoiceAssistant Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/voice/built-in/openai-grounded-voice.md Set up the assistant with a transport, tools, user ID, session ID, storage, curator, and voice. Then, initialize the RealtimeRuntime with the assistant, microphone input, and audio output. The runtime can be started to begin processing events. ```swift import AgentSquad let transport = URLSessionWebSocketTransport( apiKey: "sk-..." ) let assistant = OpenAIGroundedVoiceAssistant( name: "grounded-voice", transport: transport, tools: myToolProvider, userId: currentUser.id, sessionId: UUID().uuidString, store: InMemoryChatStorage(), curator: .dataBlock, voice: "marin" ) let runtime = RealtimeRuntime( session: assistant, input: MicCapture(), output: AudioPlayback() ) try await runtime.start() for await event in runtime.events { switch event { case .state(.thinking): showSpinner("Looking it up…") case .state(.presenting): showSpinner("Speaking…") case .state(.listening): hideSpinner() case .userTranscript(let text, final: true): showUserBubble(text) case .presenterText(let text, final: true): showAssistantBubble(text) case .widget(let payload): renderWidget(payload) case .error(let msg): print("voice error:", msg) default: break } } ``` -------------------------------- ### Add Executable Target for AgentSquad Demo Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/examples/overview.md Configure your Package.swift to include an executable target that depends on AgentSquad. This setup is necessary for running the provided examples. ```swift .executableTarget(name: "demo", dependencies: [ .product(name: "AgentSquad", package: "agent-squad"), ]) ``` -------------------------------- ### Initialize Node.js Project Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/cookbook/lambda/aws-lambda-nodejs.md Initialize a new Node.js project with default settings. ```bash npm init -y ``` -------------------------------- ### Quick Agent Usage Example Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/agents/built-in/agent.md Demonstrates the basic usage of the Agent class, including initialization, processing a text input with history, and iterating through the streamed events. ```swift import AgentSquad let agent = Agent( name: "Support Agent", description: "Handles customer support questions.", model: myLLMClient, tools: myToolProvider ) let context = AgentContext(userId: "u1", sessionId: "s1") let stream = agent.process(.text("What is my order status?"), history: [], context: context) for try await event in stream { switch event { case .textDelta(let chunk): print(chunk, terminator: "") case .final(let msg): print("\nDone: \(msg)") default: break } } ``` -------------------------------- ### Create and Initialize Python Project Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/general/quickstart.mdx Use these bash commands to create a new project directory, navigate into it, and set up a Python virtual environment. ```bash mkdir test_agent_squad cd test_agent_squad # Optional: Set up a virtual environment python -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate` ``` -------------------------------- ### Run AgentSquad Example Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/examples/overview.md Execute the demo target using Swift Package Manager. Ensure your OPENAI_API_KEY environment variable is set. You can optionally specify a baseURL for different API endpoints. ```bash OPENAI_API_KEY=sk-… swift run demo ``` -------------------------------- ### Minimal Grounded Agent Example (TypeScript) Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/agents/built-in/grounded-agent.mdx Demonstrates the basic setup of a GroundedAgent in TypeScript, configuring a gatherer and presenter agent. Ensure API keys and tool configurations are correctly set. ```typescript import { GroundedAgent, AnthropicAgent, AgentTools, } from 'agent-squad'; const brain = new AnthropicAgent({ name: 'Shop brain', description: 'Gathers product facts.', apiKey: process.env.ANTHROPIC_API_KEY, toolConfig: { tool: myTools }, // myTools: AgentTools customSystemPrompt: { template: `You are the data brain of a shopping assistant. GATHER the facts needed to answer the user — never write the final reply. Never invent values. Do NOT address the user — the presenter does that.`, }, }); const voice = new AnthropicAgent({ name: 'Shop presenter', description: 'Presents product facts.', apiKey: process.env.ANTHROPIC_API_KEY, // no toolConfig — the presenter never calls tools }); const agent = new GroundedAgent({ name: 'Shop', description: 'Product search with grounded answers.', gatherer: brain, presenter: voice, tools: myTools, }); ``` -------------------------------- ### Implement PrivacyRedactor for Custom Redaction Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/tracing/custom.md This example shows a `PrivacyRedactor` that strips metadata keys starting with an underscore and removes the `input` field for `generation` spans. It reconstructs the `TraceEvent` with the modified data. ```swift /// Strips metadata keys that start with an underscore (internal keys) /// and removes the `input` field for `generation` spans. struct PrivacyRedactor: Redactor { func redact(_ event: TraceEvent) -> TraceEvent { let cleanedMetadata: JSONValue? = event.metadata.flatMap { meta in guard case .object(let dict) = meta else { return meta } let filtered = dict.filter { !$0.key.hasPrefix("_") } return filtered.isEmpty ? nil : .object(filtered) } let input: JSONValue? = event.kind == .generation ? nil : event.input return TraceEvent( traceId: event.traceId, id: event.id, parentId: event.parentId, kind: event.kind, name: event.name, status: event.status, startedAt: event.startedAt, endedAt: event.endedAt, input: input, output: event.output, error: event.error, model: event.model, promptTokens: event.promptTokens, completionTokens: event.completionTokens, userId: event.userId, sessionId: event.sessionId, metadata: cleanedMetadata ) } } ``` -------------------------------- ### Dropping Debug Messages Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/storage/built-in/transforming.md Create a transform that conditionally drops messages. This example specifically drops messages that start with '/debug', preventing them from being stored in the chat history. Be mindful of the caution regarding message dropping and its impact on message pairing. ```swift let dropDebugTurns: MessageTransform = { message in message.text.hasPrefix("/debug") ? nil : message } ``` -------------------------------- ### Grounded Agent Chatbot Example (Python) Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/agents/built-in/grounded-agent.mdx Implements a complete, runnable console chatbot using GroundedAgent. It demonstrates how a 'gatherer' agent uses tools to fetch data from an in-memory catalog, and a 'presenter' agent crafts responses based solely on that data. Includes setup for Anthropic agents, tool definitions, and the main chat loop. ```python import asyncio import os from agent_squad.agents import ( AnthropicAgent, AnthropicAgentOptions, GroundedAgent, GroundedAgentOptions, PresenterPrompt, ) from agent_squad.types import ConversationMessage, ParticipantRole from agent_squad.utils import AgentTool, AgentTools # A tiny in-memory catalog (stands in for a real backend). CATALOG = { "p1": {"id": "p1", "name": "Aurora Wireless Headphones", "price": 89.0, "rating": 4.6, "stock": 12}, "p2": {"id": "p2", "name": "Nimbus Bluetooth Speaker", "price": 59.0, "rating": 4.3, "stock": 0}, "p3": {"id": "p3", "name": "Zephyr Earbuds", "price": 39.0, "rating": 4.1, "stock": 40}, } def search_products(query: str, max_price: float = 1000.0) -> list[dict]: """Search the catalog by name substring, cheapest first. :param query: text to match against product names :param max_price: only return products at or below this price """ q = query.lower() hits = [p for p in CATALOG.values() if q in p["name"].lower() and p["price"] <= max_price] return sorted(hits, key=lambda p: p["price"]) def get_product(product_id: str) -> dict: """Look up a single product by id. :param product_id: the product id, e.g. "p1" """ return CATALOG.get(product_id, {"error": f"no product with id {product_id}"}) tools = AgentTools([ AgentTool(name="search_products", func=search_products, required=["query"]), AgentTool(name="get_product", func=get_product, required=["product_id"]), ]) api_key = os.environ["ANTHROPIC_API_KEY"] # The gatherer owns the tools + its own prompt. It gathers facts and never speaks to the user. gatherer = AnthropicAgent(AnthropicAgentOptions( name="Shop brain", description="Gathers product facts by calling tools.", api_key=api_key, model_id="claude-3-5-sonnet-20240620", tool_config={"tool": tools, "toolMaxRecursions": 5}, custom_system_prompt={"template": """ You are the data brain of a shopping assistant. GATHER the facts needed to answer the user — never write the final reply. - Call whatever tools you need; you may chain several. - Use the chat history to resolve follow-ups ("cheaper ones?", "is it in stock?"). - Never invent values. If a tool returns nothing, say so. - Do NOT address the user or format anything — the presenter does that. """}, )) # The presenter has NO tools; it speaks only from the curated feed. A cheaper model is a fine fit. presenter = AnthropicAgent(AnthropicAgentOptions( name="Shop voice", description="Presents gathered product facts to the user.", api_key=api_key, model_id="claude-3-5-haiku-20241022", )) presenter_prompt = PresenterPrompt( default="Use ONLY the data provided; never invent a value. Be concise and friendly.", per_tool={ "search_products": ( "You are presenting product search results. Use ONLY the data block — never invent a " "price, rating, name, or stock status. Lead with the best match (name + price), then " "one standout detail. Two short sentences." ), "get_product": ( "You are presenting one product. State its name, price, rating, and whether it is in " "stock, in one sentence. Use only the data provided." ), }, ) shop = GroundedAgent(GroundedAgentOptions( name="Shop", description="A grounded shopping assistant.", gatherer=gatherer, presenter=presenter, tools=tools, presenter_prompt=presenter_prompt, )) async def main() -> None: user_id, session_id = "demo-user", "demo-session" history: list[ConversationMessage] = [] print("Shop assistant ready. Try: 'headphones under €100?' (empty line to quit)\n") while True: user_input = input("you> ").strip() if not user_input: break response = await shop.process_request(user_input, user_id, session_id, history) reply = response.content[0]["text"] print(f"shop> {reply}\n") # Persist both sides so follow-ups ("cheaper ones?") have context. history.append(ConversationMessage(role=ParticipantRole.USER.value, content=[{"text": user_input}])) history.append(ConversationMessage(role=ParticipantRole.ASSISTANT.value, content=[{"text": reply}])) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/2fastlabs/agent-squad/blob/main/examples/python/readme.md Installs project dependencies using pip within a virtual environment. Ensure Python 3.8+ is installed. ```bash git clone https://github.com/2fastlabs/agent-squad.git cd agent-squad/examples/python python -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate` pip install -r requirements.txt ``` -------------------------------- ### Local Tool Demo with AgentSquad Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/examples/local-tool.md This Swift program defines a main entry point that sets up local tools for an agent. It includes tools for retrieving the current time and performing addition, demonstrating how to integrate custom Swift functions as tools for an agent. The agent then processes a user query using these tools. ```swift import Foundation import AgentSquad @main struct LocalToolDemo { static func main() async throws { let apiKey = ProcessInfo.processInfo.environment["OPENAI_API_KEY"] ?? "" let model = ChatCompletionsClient(model: "gpt-4o-mini", apiKey: apiKey) let tools = ToolKit( .local(name: "current_time", description: "The current UTC time (ISO-8601).") { _ in ToolResult(content: [.text(ISO8601DateFormatter().string(from: Date()))]) }, .local( name: "add", description: "Adds two integers.", inputSchema: [ "type": "object", "properties": ["a": ["type": "integer"], "b": ["type": "integer"]], "required": ["a", "b"], ] ) { args in let sum = (args["a"]?.intValue ?? 0) + (args["b"]?.intValue ?? 0) return ToolResult(content: [.text("\(sum)")], structuredContent: ["sum": .int(sum)]) } ) let agent = Agent(name: "helper", description: "Local utilities.", model: model, tools: tools) let context = AgentContext(userId: "demo", sessionId: "s1") for try await event in agent.process(.text("What time is it, and what is 2 + 3?"), history: [], context: context) { if case .textDelta(let token) = event { print(token, terminator: "") } } print("") } } ``` -------------------------------- ### Install Agent Squad with All Extras Source: https://github.com/2fastlabs/agent-squad/blob/main/python/README.md Installs the agent-squad package with all available extra features, including Anthropic and OpenAI support. This is a comprehensive installation for full functionality. ```bash pip install agent-squad[all] ``` -------------------------------- ### Deploy the E-commerce Support Simulator Source: https://github.com/2fastlabs/agent-squad/blob/main/examples/ecommerce-support-simulator/README.md Deploy the demo chat web application using AWS CDK. ```bash cdk deploy ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/2fastlabs/agent-squad/blob/main/python/CONTRIBUTING.md Upgrades pip and installs dependencies from 'test_requirements.txt'. ```bash pip install --upgrade pip pip install -r test_requirements.txt ``` -------------------------------- ### Configuring PresenterPrompt with Per-Tool Overrides Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/agents/built-in/grounded-agent.md Example of initializing PresenterPrompt with a default prompt and specific prompts for 'search_products' and 'get_order' tools. Unmapped tools will use the default prompt. ```swift let presenterPrompt = PresenterPrompt( default: """ You are presenting information to the user. Use ONLY the data provided. Be concise and \\ natural, and never invent or infer values that are not present in the data. """, perTool: [ "search_products": """ You are presenting product search results. Use ONLY the data block provided — never invent a price, rating, name, or stock status. Lead with the best match: its name and price, then one standout detail. Two short sentences, natural tone. Do not call tools. """, "get_order": """ You are presenting an order status. State the order ID, current status, and estimated \\ delivery in one sentence. Use only the data provided. "") ``` -------------------------------- ### Install AWS Dependencies Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/agents/built-in/bedrock-flows-agent.mdx Install the necessary AWS-related dependencies for agent-squad. ```bash pip install "agent-squad[aws]" ``` -------------------------------- ### Install Agent Squad with pip for Python Source: https://github.com/2fastlabs/agent-squad/blob/main/README.md Install the Agent Squad library for Python, including AWS support. Other backends like Anthropic, OpenAI, or all can be installed using different extras. ```bash pip install "agent-squad[aws]" # or [anthropic], [openai], [all] — see the docs ``` -------------------------------- ### Install Agent Squad Dependencies Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/cookbook/examples/python-local-demo.md Installs the necessary agent-squad library using pip. ```bash pip install agent-squad ``` -------------------------------- ### Create Project Directory Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/cookbook/lambda/aws-lambda-python.md Creates a new directory for your project and navigates into it. ```bash mkdir multi-agent-lambda && cd multi-agent-lambda ``` -------------------------------- ### Init Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/audio/built-in/audio-playback.md Initializes AudioPlayback with optional sample rate, audio session policy, and an engine configuration closure. ```APIDOC ## Init ```swift public init( sampleRate: Double = 24_000, sessionPolicy: AudioSessionPolicy = .managed, configureEngine: (@Sendable (AVAudioEngine) throws -> Void)? = nil ) ``` ### Parameters - `sampleRate` (Double) - Optional - Default: `24_000` - Sample rate in Hz for the internal float32 `AVAudioFormat`. Must match the PCM16 frames the runtime will enqueue. - `sessionPolicy` (AudioSessionPolicy) - Optional - Default: `.managed` - Who configures the `AVAudioSession` — pass the **same policy** as `MicCapture`. See [AudioSessionPolicy](/agent-squad/swift/audio/built-in/mic-capture/#audiosessionpolicy-ios-only). - `configureEngine` ((@Sendable (AVAudioEngine) throws -> Void)?) - Optional - Default: `nil` - Escape hatch: runs with the raw `AVAudioEngine` after the player node is attached, before the engine starts. Do **not** enable voice processing here — it belongs on the capture engine (`MicCapture`), not playback. ``` -------------------------------- ### Install OpenAI Dependencies Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/classifiers/built-in/openai-classifier.mdx Install the necessary dependencies for using the OpenAI classifier with Agent Squad. ```bash pip install "agent-squad[openai]" ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/cookbook/examples/python-local-demo.md Sets up a new project directory and creates a Python virtual environment for dependency management. ```bash mkdir test_agent_squad cd test_agent_squad python -m venv venv source venv/bin/activate # On Windows use `venv\Scripts\activate` ``` -------------------------------- ### Install OpenSearch npm Package Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/retrievers/custom-retriever.mdx Install the necessary OpenSearch npm package before using the custom retriever. ```bash npm install "@opensearch-project/opensearch" ``` -------------------------------- ### Install Agent Squad and Boto3 Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/cookbook/lambda/aws-lambda-python.md Installs the necessary Python packages for Agent Squad and AWS interaction. ```bash pip install agent-squad boto3 ``` -------------------------------- ### Initialize MCPServer and Agent Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/mcp/overview.md Create an MCPServer instance with the MCP server URL and pass it to an Agent as its tool provider. The connection is established lazily on first use. ```swift import AgentSquad import AgentSquadMCP let tools = MCPServer(url: "https://mcp.example.com/sse") let agent = Agent( name: "Assistant", description: "General assistant with MCP tools.", model: model, toolProvider: tools ) ``` -------------------------------- ### Import AgentSquadAudio Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/audio/built-in/audio-playback.md Import the necessary framework to use AudioPlayback and related classes. ```swift import AgentSquadAudio ``` -------------------------------- ### Initialize Orchestrator with All Options (TypeScript) Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/orchestrator/overview.mdx Demonstrates initializing the Orchestrator with custom storage, configuration, logger, and classifier. All options are optional and will use defaults if not provided. ```typescript import { AgentSquad, AgentSquadConfig } from "agent-squad"; import { DynamoDBChatStorage } from "agent-squad/storage"; import { CustomClassifier } from "./custom-classifier"; import { CustomLogger } from "./custom-logger"; const orchestrator = new AgentSquad({ storage: new DynamoDBChatStorage(), config: { LOG_AGENT_CHAT: true, LOG_CLASSIFIER_CHAT: true, LOG_CLASSIFIER_RAW_OUTPUT: false, LOG_CLASSIFIER_OUTPUT: true, LOG_EXECUTION_TIMES: true, MAX_RETRIES: 3, MAX_MESSAGE_PAIRS_PER_AGENT: 50, USE_DEFAULT_AGENT_IF_NONE_IDENTIFIED: true, CLASSIFICATION_ERROR_MESSAGE: "Oops! We couldn't process your request. Please try again.", NO_SELECTED_AGENT_MESSAGE: "I'm sorry, I couldn't determine how to handle your request. Could you please rephrase it?", GENERAL_ROUTING_ERROR_MSG_MESSAGE: "An error occurred while processing your request. Please try again later.", }, logger: new CustomLogger(), classifier: new CustomClassifier(), }); ``` -------------------------------- ### Typical MCPServer Initialization Source: https://github.com/2fastlabs/agent-squad/blob/main/docs/src/content/docs/swift/mcp/built-in/sdk-client.md Convenience initializers for MCPServer that automatically construct an SDKMCPClient. Use these for typical usage scenarios. ```swift import AgentSquad import AgentSquadMCP // String overload let tools = MCPServer(url: "https://mcp.example.com/sse") // URL overload with auth let tools = MCPServer( url: URL(string: "https://mcp.example.com/sse")!, tokenProvider: { await TokenStore.shared.currentToken() } ) ```