### Complete Navigation Example in Python Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/contexts_guide.md Illustrates a comprehensive setup for SignalWire Agents, defining multiple contexts and steps with explicit navigation rules for both steps and contexts. It shows how context-level settings can be inherited or overridden at the step level. ```python contexts = self.define_contexts() # Main context main = contexts.add_context("main") main.set_valid_contexts(["help", "settings"]) # Context-level setting main.add_step("welcome") \ .set_text("Welcome! How can I help you?") \ .set_valid_steps(["menu"]) # Must go to menu # Inherits context-level valid_contexts main.add_step("menu") \ .set_text("Choose an option: 1) Help 2) Settings 3) Continue") \ .set_valid_contexts(["help", "settings", "main"]) # Override context setting # No valid_steps = this is a branching point # Help context help_ctx = contexts.add_context("help") help_ctx.add_step("help_info") \ .set_text("Here's how to use the system...") \ .set_valid_contexts(["main"]) # Can return to main # Settings context settings = contexts.add_context("settings") settings.add_step("settings_menu") \ .set_text("Choose a setting to modify...") \ .set_valid_contexts(["main"]) # Can return to main ``` -------------------------------- ### Python Setup Script for SignalWire Skill Package Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/third_party_skills.md An example `setup.py` file for packaging custom SignalWire skills. It defines package metadata, dependencies, and uses `entry_points` to register skills for discovery by the SignalWire Agents framework. ```python # setup.py from setuptools import setup, find_packages setup( name="my-signalwire-skills", version="1.0.0", author="Your Name", description="Custom skills for SignalWire AI Agents", packages=find_packages(), install_requires=[ "signalwire-agents>=1.0.12", "requests>=2.25.0", ], entry_points={ 'signalwire_agents.skills': [ 'weather = my_signalwire_skills.weather.skill:WeatherSkill', 'translate = my_signalwire_skills.translation.skill:TranslationSkill', ] }, python_requires='>=3.7', ) ``` -------------------------------- ### Python Skill Package Setup (setup.py) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/third_party_skills.md Illustrates how to create an installable Python skill package using setuptools. It defines package metadata, dependencies, and registers skills using entry points under the 'signalwire_agents.skills' group. ```python from setuptools import setup, find_packages setup( name="my-signalwire-skills", version="1.0.0", packages=find_packages(), install_requires=[ "signalwire-agents", "requests", ], entry_points={ 'signalwire_agents.skills': [ 'weather = my_skills.weather:WeatherSkill', 'stock = my_skills.stock:StockMarketSkill', 'translate = my_skills.translate:TranslationSkill', ] } ) ``` -------------------------------- ### Webhook GET Request Example Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/datamap_guide.md Provides an example of configuring a GET request using the `.webhook` method, including how to append query parameters dynamically using variables. ```python # GET request .webhook('GET', 'https://api.example.com/data?param=${args.value}') ``` -------------------------------- ### Skill Setup with Error Handling (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/third_party_skills.md Provides an example of a `setup` method within a skill class that includes robust error handling. It validates required packages and parameters, tests API connectivity, and logs errors. ```python def setup(self) -> bool: """Proper setup with error handling""" # Validate packages if not self.validate_packages(): return False # Validate required parameters if not self.params.get('api_key'): self.logger.error("API key is required") return False # Test connectivity try: self._test_api_connection() except Exception as e: self.logger.error(f"Failed to connect to API: {e}") return False return True ``` -------------------------------- ### Quick Start WebService Initialization and Start (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/web_service.md Demonstrates the basic usage of the WebService class. It initializes a service to serve files from specified directories and then starts the service. The example shows how to map URL paths to local directories and provides default access information. ```python from signalwire_agents import WebService # Create a service to serve files service = WebService( port=8002, directories={ "/docs": "./documentation", "/assets": "./static/assets" } ) # Start the service service.start() # Service available at http://localhost:8002 # Basic Auth: dev:w00t (auto-generated) ``` -------------------------------- ### Install and Use Custom SignalWire Skills Package Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/third_party_skills.md Demonstrates the command to install a custom SignalWire skill package from a Git repository using pip. It also shows a Python example of initializing an agent and adding the installed skills. ```bash pip install git+https://github.com/yourname/my-signalwire-skills.git ``` ```python from signalwire_agents import AgentBase agent = AgentBase(name="my-agent") agent.add_skill("weather", {"api_key": "..."}) agent.add_skill("translate", {"api_key": "..."}) ``` -------------------------------- ### Basic File Serving Example Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/web_service.md Demonstrates how to initialize and start the WebService to serve files from multiple directories. ```APIDOC ### Basic File Serving ```python from signalwire_agents import WebService # Serve documentation service = WebService( directories={ "/docs": "./documentation", "/api": "./api-specs" } ) service.start() # Files accessible at: # http://localhost:8002/docs/index.html # http://localhost:8002/api/swagger.json ``` ``` -------------------------------- ### Integrate Search into an Agent with Python Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_installation.md Provides a Python code example of integrating the search functionality into a SignalWire Agent. It shows how to initialize a SearchEngine within an agent, define a tool for searching, and handle cases where the search functionality might not be available. ```python from signalwire_agents import AgentBase from signalwire_agents.core.function_result import SwaigFunctionResult class SearchAgent(AgentBase): def __init__(self): super().__init__(name="search-agent") # Check if search is available try: from signalwire_agents.search import SearchEngine self.search_engine = SearchEngine("concepts.swsearch") self.search_available = True except ImportError: self.search_available = False @AgentBase.tool( name="search_knowledge", description="Search the knowledge base", parameters={ "query": {"type": "string", "description": "Search query"} } ) def search_knowledge(self, args, raw_data): if not self.search_available: return SwaigFunctionResult( "Search not available. Install with: pip install signalwire-agents[search]" ) # Perform search... return SwaigFunctionResult("Search results...") ``` -------------------------------- ### Example Use Case URLs for Agent Configuration (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/agent_guide.md Illustrates example URL patterns for configuring agents based on different use cases like multi-tenancy, A/B testing, personalization, and localization. These are conceptual examples and do not contain executable code. ```python # Different tenants get different capabilities # /agent?tenant=acme&industry=healthcare # /agent?tenant=globex&industry=finance ``` ```python # Split traffic between different configurations # /agent?test_group=A (control) # /agent?test_group=B (experimental) ``` ```python # Personalized based on user profile # /agent?user_id=123&voice_speed=fast&formality=casual ``` ```python # Location-based configuration # /agent?country=mx&language=es&timezone=America/Mexico_City ``` -------------------------------- ### JSON Configuration with Environment Variable Substitution Examples Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/configuration.md Provides examples of using environment variable substitution within JSON configuration files. It demonstrates how to use variables directly or with default values. ```json { "database": { "host": "${DB_HOST|localhost}", "port": "${DB_PORT|5432}", "password": "${DB_PASSWORD}" } } ``` -------------------------------- ### SignalWire Search Command Examples Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/agent_guide.md Examples of using the 'sw-search' command-line tool to build search indexes from various sources. This includes single file indexing, indexing multiple files, and advanced configuration with custom settings. ```bash # Build index from the comprehensive concepts guide sw-search docs/signalwire_agents_concepts_guide.md --output concepts.swsearch # Build from multiple sources sw-search docs/signalwire_agents_concepts_guide.md examples README.md --output comprehensive.swsearch # Traditional directory approach with custom settings sw-search ./knowledge \ --output knowledge.swsearch \ --file-types md,txt,pdf \ --chunking-strategy sentence \ --max-sentences-per-chunk 8 \ --verbose ``` -------------------------------- ### Install pip using ensurepip (Bash) Source: https://github.com/signalwire/signalwire-agents/blob/main/tutorial/fred/tutorial/02-setup.md This command ensures that pip is installed for the current Python environment by running the `ensurepip` module. It's a reliable method to get pip if it's missing, especially when dealing with Python installations that don't include it by default. ```bash # Install pip python3 -m ensurepip ``` -------------------------------- ### Run Azure Functions Locally Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/cloud_functions_guide.md Installs the Azure Functions Core Tools globally and then starts the local Azure Functions host. This is used to test Azure Functions locally before deploying. Ensure Node.js and npm are installed. ```bash # Install Azure Functions Core Tools npm install -g azure-functions-core-tools@4 # Run locally func start ``` -------------------------------- ### Basic AgentServer Setup in Python Source: https://github.com/signalwire/signalwire-agents/blob/main/tutorial/multi_agents/lesson3_multi_agent_systems.md Demonstrates the fundamental setup of an AgentServer to host multiple agents on a single port. It shows how to create the server instance and register different agents to specific routes. ```python from signalwire_agents import AgentServer, AgentBase # Create the server server = AgentServer( host="0.0.0.0", port=3001, log_level="info" ) # Create and register agents triage_agent = TriageAgent() server.register(triage_agent, "/") sales_agent = SalesAgent() server.register(sales_agent, "/sales") # Run the server server.run() ``` -------------------------------- ### Agent Initialization and Execution (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/signalwire_ai_developer_guide.md Shows the minimal setup required to run a production-ready AI agent. It highlights the SDK's ability to auto-detect the execution environment, simplifying deployment. ```python # This is ALL you need for a production-ready AI agent agent = MyAgent() agent.run() # Auto-detects environment (server/CGI/Lambda) ``` -------------------------------- ### URL Parameter Substitution Example Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/datamap_guide.md Shows how to dynamically substitute variables into a URL for making GET requests. This is commonly used for passing parameters like API keys or user-provided locations. ```python # URL parameter substitution .webhook('GET', 'https://api.weather.com/v1/current?key=${global_data.api_key}&q=${args.location}') ``` -------------------------------- ### Building and Deploying .swsearch Files (Bash) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_system_full.md This command-line example shows how to build a self-contained knowledge index using the `sw-search` tool and then deploy this index file to various environments like Lambda, Docker containers, or edge devices. This highlights the portability of SignalWire's search solution. ```bash # Build once sw-search ./docs --output knowledge.swsearch # Deploy anywhere scp knowledge.swsearch lambda:/var/task/ scp knowledge.swsearch docker-container:/app/ scp knowledge.swsearch edge-device:/opt/agent/ ``` -------------------------------- ### Create a Basic SignalWire AI Agent (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/signalwire_ai_blog.md This Python code defines a simple AI agent named 'QuickStart Assistant' using the SignalWire SDK. It inherits from `AgentBase` and sets a basic prompt. The agent can handle conversations, maintain context, and provide natural language responses. ```python from signalwire_agents import AgentBase class QuickStartAssistant(AgentBase): def __init__(self): super().__init__(name="QuickStart Assistant") self.set_prompt_text("You are a helpful assistant that can answer questions and provide information.") agent = QuickStartAssistant() if __name__ == "__main__": agent.run() ``` -------------------------------- ### Basic Single-Context Workflow with SignalWire Agents (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/contexts_guide.md Demonstrates creating a simple, linear onboarding agent. It defines a single 'default' context with sequential steps for collecting user information. This workflow is suitable for straightforward, guided conversations. ```python from signalwire_agents import AgentBase class OnboardingAgent(AgentBase): def __init__(self): super().__init__(name="Onboarding Assistant", route="/onboarding") # Define contexts (replaces traditional prompt setup) contexts = self.define_contexts() # Single context must be named "default" workflow = contexts.add_context("default") # Step 1: Welcome workflow.add_step("welcome") \ .set_text("Welcome to our service! Let's get you set up. What's your name?") \ .set_step_criteria("User has provided their name") \ .set_valid_steps(["collect_email"]) # Step 2: Collect Email workflow.add_step("collect_email") \ .set_text("Thanks! Now I need your email address to create your account.") \ .set_step_criteria("Valid email address has been provided") \ .set_valid_steps(["confirm_details"]) # Step 3: Confirmation workflow.add_step("confirm_details") \ .set_text("Perfect! Let me confirm your details before we proceed.") \ .set_step_criteria("User has confirmed their information") \ .set_valid_steps(["complete"]) # Step 4: Completion workflow.add_step("complete") \ .set_text("All set! Your account has been created successfully.") # No valid_steps = end of workflow agent = OnboardingAgent() agent.run() if __name__ == "__main__": main() ``` -------------------------------- ### Complete BedrockAgent Example in Python Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/bedrock_agent.md A full Python script demonstrating how to initialize and configure a BedrockAgent. This includes setting up system prompts, adding languages, defining custom tools, and enabling SIP routing. ```python #!/usr/bin/env python3 from signalwire_agents import BedrockAgent import os # Create a BedrockAgent with full configuration agent = BedrockAgent( name="production_bedrock", route="/api/bedrock", system_prompt="You are a professional AI assistant.", voice_id="matthew", temperature=0.7, top_p=0.9, max_tokens=1024 ) # Configure prompt with POM agent.prompt_add_section( "Role", "You are a helpful customer service agent.", bullets=[ "Be professional and courteous", "Provide accurate information", "Ask clarifying questions when needed" ] ) # Add languages agent.add_language( name="Spanish", code="es", voice="miguel" # Bedrock will map this appropriately ) # Add skills agent.add_skill("datetime") if os.environ.get("WEATHER_API_KEY"): agent.add_skill("weather_api", { "api_key": os.environ["WEATHER_API_KEY"] }) # Add custom tools @agent.tool def transfer_to_support(): """Transfer the call to support department""" return "transfer:support" @agent.tool def check_order_status(order_id: str): """Check the status of an order""" # Simulate order lookup return f"Order {order_id} is currently being processed and will ship tomorrow." # Enable SIP routing agent.enable_sip_routing() agent.register_sip_username("bedrock-support") # Run the agent if __name__ == "__main__": print(f"Starting BedrockAgent on {agent.get_full_url()}") agent.run() ``` -------------------------------- ### Basic Voicemail Service Example Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/swml_service_guide.md A complete example demonstrating the creation of a basic voicemail service using SWMLService. ```APIDOC ## Basic Voicemail Service ### Description This example defines a `VoicemailService` class that inherits from `SWMLService` and builds a SWML document for a voicemail application, including answering, playing greetings, recording messages, and hanging up. ### Method `SWMLService` subclassing and document building methods. ### Request Example ```python from signalwire_agents.core.swml_service import SWMLService class VoicemailService(SWMLService): def __init__(self, host="0.0.0.0", port=3000): super().__init__( name="voicemail", route="/voicemail", host=host, port=port ) # Build the SWML document self.build_voicemail_document() def build_voicemail_document(self): """Build the voicemail SWML document""" # Reset the document self.reset_document() # Add answer verb self.add_verb("answer", {{}}) # Add play verb for greeting self.add_verb("play", {{ "url": "say:Hello, you've reached the voicemail service. Please leave a message after the beep." }}) # Play a beep self.add_verb("play", {{ "url": "https://example.com/beep.wav" }}) # Record the message self.add_verb("record", {{ "format": "mp3", "stereo": False, "max_length": 120, # 2 minutes max "terminators": "#" }}) # Thank the caller self.add_verb("play", {{ "url": "say:Thank you for your message. Goodbye!" }}) # Hang up self.add_verb("hangup", {{}}) self.log.debug("voicemail_document_built") ``` ### Response This code defines a service that, when run, will handle incoming calls by playing a greeting, recording a message, and then hanging up. ``` -------------------------------- ### Install SignalWire Agents with PostgreSQL pgvector Support Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_installation.md Installs the SignalWire Agents SDK with support for PostgreSQL's pgvector extension, enabling scalable vector search. This can be installed standalone or combined with other search features. ```bash # Just pgvector support pip install signalwire-agents[pgvector] # Or with search features pip install signalwire-agents[search,pgvector] # Already included in search-all pip install signalwire-agents[search-all] ``` -------------------------------- ### Static Agent Configuration Example Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/agent_guide.md Demonstrates a traditional static agent configuration where settings are applied once at startup. This approach is simple but offers less flexibility compared to dynamic configuration. ```python class StaticAgent(AgentBase): def __init__(self): super().__init__(name="static-agent") # Configuration happens once at startup self.add_language("English", "en-US", "rime.spore:mistv2") self.set_params({"end_of_speech_timeout": 500}) self.prompt_add_section("Role", "You are a customer service agent.") self.set_global_data({"service_level": "standard"}) ``` -------------------------------- ### Check pip Version (Bash) Source: https://github.com/signalwire/signalwire-agents/blob/main/tutorial/fred/tutorial/02-setup.md Verifies if pip, the Python package installer, is installed and accessible. Pip is required to install the SignalWire AI Agents SDK. ```bash pip3 --version # or pip --version ``` -------------------------------- ### Run and Test a SignalWire Agent Source: https://github.com/signalwire/signalwire-agents/blob/main/signalwire_ai_blog.md Demonstrates how to run a SignalWire agent from the command line and provides an example of the expected output, including the agent's name, network address, and available skills. Also shows example user queries for testing different skills. ```bash python agent.py ``` ```text * Agent 'Enhanced Assistant' running on http://0.0.0.0:5000 * Available skills: web_search, datetime, math * Authentication: Basic (username: 8A7B9C, password: X3R8K9) ``` ```text - Web Search: "What's the latest news about AI?" - Date/Time: "What time is it in Tokyo right now?" - Math: "What's the square root of 1764?" - Knowledge Search: "Tell me about our refund policy" (if using local search) ``` -------------------------------- ### Basic Search Index Building from Files and Directories (Bash) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search-system.md This set of bash commands illustrates basic index creation using the 'sw-search' tool. It covers building an index from a single file, multiple files, a mix of files and directories, and a whole directory, specifying output files with the '--output' flag. ```bash # Build index from the comprehensive concepts guide sw-search docs/signalwire_agents_concepts_guide.md --output concepts.swsearch # Build from multiple individual files sw-search README.md docs/agent_guide.md docs/architecture.md --output knowledge.swsearch # Build from mixed sources (files and directories) sw-search docs/signalwire_agents_concepts_guide.md examples --file-types md,py --output comprehensive.swsearch # Build from a directory (traditional approach) sw-search docs --output docs.swsearch # Include specific file types sw-search docs --file-types md,txt,py # Exclude patterns sw-search docs --exclude "**/test/**,**/__pycache__/**" # JSON-based chunking (for pre-chunked content) sw-search api_chunks.json --chunking-strategy json --file-types json ``` -------------------------------- ### Install SignalWire Agents with All Search Features Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_installation.md Installs the SignalWire Agents SDK with the complete set of search features, including basic search, full document processing, advanced NLP, and pgvector support. This is the largest installation and has the slowest performance. ```bash pip install signalwire-agents[search-all] ``` -------------------------------- ### Dynamic Call Routing Service Example Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/swml_service_guide.md An example demonstrating a dynamic call routing service that routes calls based on department information. ```APIDOC ## Dynamic Call Routing Service ### Description This example implements a `CallRouterService` that overrides the `on_swml_request` method to dynamically route incoming calls based on a 'department' parameter in the request data. It constructs an SWML document to answer, play a greeting, connect the call, or provide a fallback message. ### Method `SWMLService.on_swml_request(request_data)` ### Request Example ```python class CallRouterService(SWMLService): def on_swml_request(self, request_data=None): # If there's no request data, use default routing if not request_data: self.log.debug("no_request_data_using_default") return None # Create a new document self.reset_document() self.add_verb("answer", {{}}) # Get routing parameters department = request_data.get("department", "").lower() # Add play verb for greeting self.add_verb("play", {{ "url": f"say:Thank you for calling our {department} department. Please hold." }}) # Route based on department phone_numbers = {{ "sales": "+15551112222", "support": "+15553334444", "billing": "+15555556666" }} # Get the appropriate number or use default to_number = phone_numbers.get(department, "+15559990000") # Connect to the department self.add_verb("connect", {{ "to": to_number, "timeout": 30, "answer_on_bridge": True }}) # Add fallback message and hangup self.add_verb("play", {{ "url": "say:We're sorry, but all of our agents are currently busy. Please try again later." }}) self.add_verb("hangup", {{}}) return None # Use the document we've built ``` ### Response When `on_swml_request` is called with `request_data` containing a 'department' key, the service constructs an SWML document to route the call accordingly. If no `request_data` is provided, it returns `None`, indicating default routing behavior should be used. ``` -------------------------------- ### Basic File Serving Example (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/web_service.md Initializes and starts a WebService instance to serve static files from specified directories. Files are made accessible via HTTP requests to the defined routes. ```python from signalwire_agents import WebService # Serve documentation service = WebService( directories={ "/docs": "./documentation", "/api": "./api-specs" } ) service.start() # Files accessible at: # http://localhost:8002/docs/index.html # http://localhost:8002/api/swagger.json ``` -------------------------------- ### Install SignalWire Agents with Basic Search Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_installation.md Installs the SignalWire Agents SDK with basic search capabilities, including vector embeddings and keyword search. This option has minimal dependencies and is suitable for development and testing. ```bash pip install signalwire-agents[search] ``` -------------------------------- ### Initialize Agent with Zero Configuration (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/configuration.md Demonstrates initializing an agent without any explicit configuration, relying on default behavior. This is the simplest way to start. ```python # Works exactly as before - no config needed agent = MyAgent() agent.run() ``` -------------------------------- ### Check Python Version (Bash) Source: https://github.com/signalwire/signalwire-agents/blob/main/tutorial/fred/tutorial/02-setup.md Verifies the installed Python version on your system. This is a prerequisite for installing the SignalWire AI Agents SDK. ```bash python3 --version # or python --version ``` -------------------------------- ### Installing Skill Package (Bash) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/third_party_skills.md Command to install a SignalWire skill package using pip. After installation, the skills defined in the package's entry points are automatically available to the agent. ```bash pip install my-signalwire-skills ``` -------------------------------- ### List SWML Methods Example Source: https://github.com/signalwire/signalwire-agents/blob/main/mcp/swml-schema-search/README.md This example demonstrates how to use the 'list_swml_methods' tool provided by the SWML Schema MCP Server. It shows the tool name, expected arguments (an empty dictionary in this case), and a sample output listing available SWML methods with brief descriptions. ```text Tool: list_swml_methods Arguments: {} Output: Available SWML Methods (25 total): ai Starts an AI agent session with configurable prompts, functions, and behaviors connect Connects the call to another destination play Plays audio files or text-to-speech ... ``` -------------------------------- ### Install SignalWire Agents with User Permissions (Bash) Source: https://github.com/signalwire/signalwire-agents/blob/main/tutorial/fred/tutorial/02-setup.md This command installs the signalwire-agents package using the `--user` flag, which is recommended to avoid permission issues when installing packages in system-wide directories. It's a common solution for permission denied errors during pip installations. ```bash # Use --user flag pip install --user signalwire-agents ``` -------------------------------- ### Install SignalWire Agents SDK Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/swml_service_guide.md Installs the SignalWire AI Agent SDK, which includes the SWMLService class, using pip. This is the first step to using the service. ```bash pip install signalwire-agents ``` -------------------------------- ### Agent Initialization with Custom Skill Parameters (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/skills_system.md Demonstrates how to initialize an agent and add skills with custom parameters. This example configures the 'web_search' skill to retrieve more results and introduce a delay, optimizing it for research tasks. ```python from signalwire_agents import AgentBase # Create agentagent = AgentBase("Research Assistant", route="/research") # Add web search optimized for research (more results)agent.add_skill("web_search", { "num_results": 5, # Get more comprehensive results "delay": 1.0 # Be respectful to websites }) # Add other skills without parametersagent.add_skill("datetime")agent.add_skill("math") # Start the agentagent.run() ``` -------------------------------- ### Check and Start PostgreSQL Service Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/troubleshooting_search.md Bash commands to check the status of the PostgreSQL service and start it if it's not running. This is a common step when encountering connection issues. ```bash # Check if PostgreSQL is running sudo systemctl status postgresql # Start if needed sudo systemctl start postgresql ``` -------------------------------- ### Create a Simple 'Hello World' Agent in Python Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/signalwire_ai_developer_guide.md This Python snippet shows how to create a basic 'Hello World' agent using the SignalWire Agents SDK. It defines a simple agent class and runs it, automatically generating webhook URLs for deployment. ```python from signalwire_agents import AgentBase class HelloWorldAgent(AgentBase): def get_prompt(self): return "You are a friendly AI assistant" agent = HelloWorldAgent() agent.run() ``` -------------------------------- ### Install Google Cloud Functions Framework Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/cloud_functions_guide.md This snippet provides the command to install the Functions Framework for local testing of Google Cloud Functions. ```bash pip install functions-framework ``` -------------------------------- ### pgvector Extension Setup and Table Creation - SQL Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_system_full.md Provides SQL commands for setting up the pgvector extension and creating a table to store knowledge chunks. It includes installing the extension, defining the table schema with an embedding vector, and creating indexes for efficient querying. ```sql -- Install extension (as superuser) CREATE EXTENSION IF NOT EXISTS vector; -- Create table for collection CREATE TABLE IF NOT EXISTS knowledge_chunks ( id SERIAL PRIMARY KEY, collection_name TEXT NOT NULL, content TEXT NOT NULL, embedding vector(384), -- 384 for mini, 768 for base, 1024 for large metadata JSONB, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); -- Create indexes for performance CREATE INDEX ON knowledge_chunks USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100); CREATE INDEX ON knowledge_chunks (collection_name); CREATE INDEX ON knowledge_chunks USING gin (metadata jsonb_path_ops); ``` -------------------------------- ### Install SignalWire Agents with Advanced NLP Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_installation.md Installs the SignalWire Agents SDK with advanced Natural Language Processing capabilities using spaCy for better search relevance. This option requires downloading a spaCy model and is slower than basic search. ```bash pip install signalwire-agents[search-nlp] ``` -------------------------------- ### Run Custom Customer Support Agent (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/agent_guide.md Demonstrates how to instantiate and run the `CustomerSupportAgent` prefab. It shows passing configuration parameters and starting the agent server with specified host and port. ```python # Create an instance of the custom prefab support_agent = CustomerSupportAgent( product_name="SignalWire Voice API", knowledge_base_path="./product_docs", support_email="support@example.com", escalation_path="tier 2 support", name="voice-support", route="/voice-support" ) # Start the agent support_agent.serve(host="0.0.0.0", port=8000) ``` -------------------------------- ### Install PostgreSQL with pgvector (macOS) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_system_full.md Installs PostgreSQL and the pgvector extension on macOS using Homebrew. This command is part of the setup process for using pgvector as a backend. ```bash # macOS brew install postgresql pgvector ``` -------------------------------- ### Webhook PUT Request with Authentication Example Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/datamap_guide.md Illustrates configuring a PUT request that includes authentication headers and a request body. This example shows how to pass dynamic values for authorization tokens. ```python # PUT request with authentication .webhook('PUT', 'https://api.example.com/update/${args.id}', headers={'Authorization': 'Bearer ${global_data.token}'}) .body({'status': '${args.status}'}) ``` -------------------------------- ### Webhook POST Request Example Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/datamap_guide.md Shows how to configure a POST request with a JSON body. This example demonstrates setting the request method, URL, and providing dynamic data in the request body. ```python # POST request with JSON body .webhook('POST', 'https://api.example.com/create') .body({'name': '${args.name}', 'value': '${args.value}'}) ``` -------------------------------- ### Configure FAQBotAgent with Knowledge Base Content (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/signalwire_ai_blog.md Shows how to initialize a FAQBotAgent using different methods for providing knowledge base content: directly as a list of dictionaries, from a local JSON file, or from a remote URL with a refresh interval. ```python from signalwire_agents.prefabs import FAQBotAgent # Create an agent with direct FAQ content support_agent = FAQBotAgent( name="product-support", route="/support", faq_content=[ { "question": "How do I reset my password?", "answer": "To reset your password, visit the login page and click on 'Forgot Password'. Follow the instructions sent to your email." }, { "question": "What payment methods do you accept?", "answer": "We accept Visa, Mastercard, American Express, and PayPal." }, { "question": "How long does shipping take?", "answer": "Standard shipping typically takes 3-5 business days within the continental US." } ] ) # Alternatively, load from a file documentation_agent = FAQBotAgent( name="api-docs", route="/docs", faq_file="documentation.json" # JSON file with question/answer pairs ) # Or load from a URL knowledge_agent = FAQBotAgent( name="knowledge-base", route="/kb", faq_url="https://example.com/api/knowledge-base", refresh_interval=3600 # Refresh content every hour ) ``` -------------------------------- ### Build Search Index with CLI Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_installation.md Demonstrates building a search index using the SignalWire Agents CLI tool. It shows how to specify input files, directories, file types, and the output file name. The CLI supports building indexes from single files, multiple sources, or entire directories. ```bash sw-search docs/signalwire_agents_concepts_guide.md --output concepts.swsearch sw-search docs/signalwire_agents_concepts_guide.md examples README.md --file-types md,py,txt --output comprehensive.swsearch sw-search ./docs --output knowledge.swsearch --file-types md,txt,pdf ``` -------------------------------- ### Install SignalWire Agents with Full Document Processing Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/search_installation.md Installs the SignalWire Agents SDK with comprehensive document processing support for PDF, DOCX, Excel, and PowerPoint files. This option includes basic search features plus additional libraries for document handling. ```bash pip install signalwire-agents[search-full] ``` -------------------------------- ### Install and Configure PgBouncer for Connection Pooling Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/troubleshooting_search.md Instructions for installing PgBouncer, a connection pooler for PostgreSQL, and configuring it to manage connections efficiently for multiple agents. This helps prevent connection pool exhaustion. ```bash # Install pgbouncer for connection pooling sudo apt-get install pgbouncer ``` ```ini # /etc/pgbouncer/pgbouncer.ini [databases] knowledge = host=localhost port=5432 dbname=knowledge [pgbouncer] pool_mode = transaction max_client_conn = 1000 default_pool_size = 25 ``` -------------------------------- ### Initialize Agent with Configuration File (Python) Source: https://github.com/signalwire/signalwire-agents/blob/main/docs/configuration.md Shows how to initialize an agent using a configuration file. The SDK automatically detects 'config.json' or allows specifying a custom file path. ```python # Automatically detects config.json if present agent = MyAgent() # Or specify a config file agent = MyAgent(config_file="production_config.json") ```