### README.md Navigation Structure Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/MANIFEST.md This snippet shows the navigation structure starting from the README.md file, outlining the quick start guide, installation instructions, and links to all other documents. ```markdown README.md ├── Quick start guide ├── Installation instructions └── Links to all documents ``` -------------------------------- ### Install Wheel File Source: https://github.com/retellai/retell-python-sdk/blob/main/CONTRIBUTING.md Install the Retell Python SDK efficiently using a previously built wheel file. ```sh pip install ./path-to-wheel-file.whl ``` -------------------------------- ### Add and Run Example Script Source: https://github.com/retellai/retell-python-sdk/blob/main/CONTRIBUTING.md Add a new Python file to the examples directory and make it executable to run against your API. ```python # add an example to examples/.py #!/usr/bin/env -S rye run python … ``` ```sh chmod +x examples/.py # run the example against your api $ ./examples/.py ``` -------------------------------- ### Install SDK from Git Source: https://github.com/retellai/retell-python-sdk/blob/main/CONTRIBUTING.md Install the Retell Python SDK directly from a Git repository using pip. ```sh pip install git+ssh://git@github.com/RetellAI/retell-python-sdk.git ``` -------------------------------- ### Install Retell Python SDK Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/README.md Install the Retell Python SDK using pip. ```bash pip install retell-sdk ``` -------------------------------- ### Install Retell SDK with aiohttp support Source: https://github.com/retellai/retell-python-sdk/blob/main/README.md Install the Retell SDK with optional aiohttp support for improved concurrency. ```sh pip install retell-sdk[aiohttp] ``` -------------------------------- ### Install Dependencies with Pip Source: https://github.com/retellai/retell-python-sdk/blob/main/CONTRIBUTING.md If not using Rye, install development dependencies using pip and the requirements-dev.lock file. ```sh pip install -r requirements-dev.lock ``` -------------------------------- ### Start ngrok Tunnel Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/webhooks-and-events.md Start an ngrok tunnel to expose your local server to the internet. Use the ngrok URL in your webhook configuration. ```bash # Start ngrok tunnel to your local server ngrok http 5000 # Use ngrok URL in webhook configuration # https://abc123.ngrok.io/webhooks/call_started ``` -------------------------------- ### Create Agent with Custom LLM and Voice Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-llm-voice.md Example of creating a custom LLM, finding a suitable voice, and then creating an agent using these resources. ```python # Create a custom LLM llm = client.llm.create( llm_name="Support Bot LLM", llm_model="gpt-4-turbo", general_prompt_override="You are a helpful support agent.", temperature=0.8 ) # Find a suitable voice voices = client.voice.list() female_voice = next(v for v in voices.voices if v.gender == "female") # Create agent using custom LLM and voice agent = client.agent.create( response_engine={ "type": "retell-llm", "llm_id": llm.llm_id }, voice_id=female_voice.voice_id, agent_name="Support Agent" ) ``` -------------------------------- ### AsyncRetell Client Initialization and Usage Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/client-initialization.md Example of initializing the AsyncRetell client with an API key from environment variables and making an asynchronous API call to list agents. ```python import asyncio import os from retell import AsyncRetell async def main(): client = AsyncRetell( api_key=os.environ.get("RETELL_API_KEY"), ) # Make async API calls with await response = await client.agent.list() print(response) asyncio.run(main()) ``` -------------------------------- ### PronunciationGuide Configuration Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/types-reference.md Provides a guide for correct pronunciation of specific words or names. Includes a list of word-pronunciation pairs. ```python pronunciation_guide = { "guide": [ { "word": "Acme", "pronunciation": "AK-mee" }, { "word": "Nguyen", "pronunciation": "win" } ] } ``` -------------------------------- ### Creating Agent with Nested Configuration Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/types-reference.md Example of creating an agent with complex nested configuration, including response engine, voice, webhook, and call screening options. ```python # Create agent with complex nested config agent = client.agent.create( response_engine={ "type": "retell-llm", "llm_id": "llm_123" }, voice_id="retell-Cimo", webhook_config={ "call_started": "https://example.com/started", "call_ended": "https://example.com/ended" }, call_screening_option={ "enable": True, "agent_identity": "Support Team" } ) ``` -------------------------------- ### Synchronous Usage Example Source: https://github.com/retellai/retell-python-sdk/blob/main/README.md Demonstrates creating an agent using the synchronous Retell client. Ensure the RETELL_API_KEY environment variable is set. ```python import os from retell import Retell client = Retell( api_key=os.environ.get("RETELL_API_KEY"), # This is the default and can be omitted ) agent_response = client.agent.create( response_engine={ "llm_id": "llm_234sdertfsdsfsdf", "type": "retell-llm", }, voice_id="retell-Cimo", ) print(agent_response.agent_id) ``` -------------------------------- ### Playground Completion Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-other-resources.md Gets a completion from the LLM for testing and playground purposes. ```APIDOC ## Playground Completion ### Description Get a completion for testing/playground purposes. ### Method POST ### Endpoint /playground/completion ### Parameters #### Request Body - **llm_id** (str) - Required - The ID of the language model to use. - **context** (Optional[str] | Omit) - Optional - The context for the completion. - **extra_headers** (Headers | None) - Optional - Extra headers to send with the request. - **extra_query** (Query | None) - Optional - Extra query parameters to send with the request. - **extra_body** (Body | None) - Optional - Extra body parameters to send with the request. - **timeout** (float | httpx.Timeout | None | NotGiven) - Optional - Timeout for the request. ### Response #### Success Response (200) - **llm_completion** (str) - The LLM completion response. ### Response Example ```json { "llm_completion": "This is a sample completion." } ``` ``` -------------------------------- ### Asynchronous Usage Example Source: https://github.com/retellai/retell-python-sdk/blob/main/README.md Shows how to create an agent using the asynchronous Retell client with asyncio. Ensure the RETELL_API_KEY environment variable is set. ```python import os import asyncio from retell import AsyncRetell client = AsyncRetell( api_key=os.environ.get("RETELL_API_KEY"), # This is the default and can be omitted ) async def main() -> None: agent_response = await client.agent.create( response_engine={ "llm_id": "llm_234sdertfsdsfsdf", "type": "retell-llm", }, voice_id="retell-Cimo", ) print(agent_response.agent_id) asyncio.run(main()) ``` -------------------------------- ### Print SDK Version Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/INDEX.md Import the retell library and print its version. This helps in verifying the installed SDK version. ```python import retell print(retell.__version__) ``` -------------------------------- ### Sync Dependencies with Rye Source: https://github.com/retellai/retell-python-sdk/blob/main/CONTRIBUTING.md If Rye is installed manually, use this command to sync all dependencies and features. ```sh rye sync --all-features ``` -------------------------------- ### Client Initialization with Custom Timeout Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/configuration-and-setup.md Configure a custom timeout for all requests made by the Retell client. This example sets a 30-second timeout. ```python client = Retell( api_key="your-api-key", timeout=30.0 # 30 second timeout for all requests ) ``` -------------------------------- ### AsyncRetell Client with aiohttp HTTP Client Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/client-initialization.md Shows how to initialize the AsyncRetell client using DefaultAioHttpClient for potentially improved concurrency performance. Ensure 'retell-sdk[aiohttp]' is installed. ```python from retell import AsyncRetell, DefaultAioHttpClient async def main(): async with AsyncRetell( api_key="your-api-key", http_client=DefaultAioHttpClient(), ) as client: response = await client.agent.list() ``` -------------------------------- ### Async Python Webhook Server Example Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/webhooks-and-events.md A complete asynchronous Python web server using aiohttp to handle 'call_started' and 'call_ended' webhooks, including signature verification. ```python import asyncio import json from aiohttp import web WEBHOOK_SECRET = "your-webhook-secret" async def verify_signature(request): import hmac import hashlib signature = request.headers.get("X-Retell-Signature") body = await request.read() expected = hmac.new( WEBHOOK_SECRET.encode(), body, hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, expected) async def handle_call_started(request): if not await verify_signature(request): return web.Response(status=401, text="Invalid signature") data = await request.json() print(f"Call started: {data['call_id']}") return web.json_response({"status": "received"}) async def handle_call_ended(request): if not await verify_signature(request): return web.Response(status=401, text="Invalid signature") data = await request.json() print(f"Call ended: {data['call_id']}") return web.json_response({"status": "received"}) app = web.Application() app.router.add_post("/webhooks/call_started", handle_call_started) app.router.add_post("/webhooks/call_ended", handle_call_ended) if __name__ == "__main__": web.run_app(app, port=8080) ``` -------------------------------- ### Create a Text Chat Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/INDEX.md Start a text-based chat session with a chat agent. Metadata can be attached for contextual information. ```python chat = client.chat.create( chat_agent_id="chat_agent_123", metadata={"user_id": "user_456"} ) print(f"Chat ID: {chat.chat_id}") ``` -------------------------------- ### Get All Agent Versions Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-agent.md Retrieve a list of all available versions for a given agent. Useful for auditing or selecting a version to manage. ```python versions = client.agent.get_versions("agent_123") for version in versions.versions: print(f"Version {version.version_id}: created {version.created_at}") ``` -------------------------------- ### Logging Webhook Activity Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/webhooks-and-events.md Python example using the logging module to record incoming webhook events and their processing status. Includes error logging for failed processing to aid in debugging. ```python import logging logger = logging.getLogger(__name__) def handle_webhook(event): logger.info(f"Webhook received: {event['event']}") try: process_event(event) logger.info(f"Webhook processed successfully: {event['call_id']}") except Exception as e: logger.error(f"Error processing webhook: {e}", exc_info=True) raise ``` -------------------------------- ### Set Up Webhooks for Agent Events Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/INDEX.md Configure webhook URLs for specific agent events like call start, call end, and transcript delivery. This allows the agent to send real-time notifications to your application. ```python agent = client.agent.create( response_engine={ "type": "retell-llm", "llm_id": "llm_123" }, voice_id="retell-Cimo", webhook_config={ "call_started": "https://api.example.com/webhooks/call_started", "call_ended": "https://api.example.com/webhooks/call_ended", "call_transcript": "https://api.example.com/webhooks/transcript" } ) ``` -------------------------------- ### Initialize Retell Synchronous Client Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/client-initialization.md Demonstrates basic and advanced initialization of the synchronous Retell client. Shows how to use environment variables, provide an API key directly, and configure custom network settings. ```python import os from retell import Retell # Basic usage with environment variable client = Retell() # Explicit API key client = Retell(api_key="your-api-key") # Custom configuration client = Retell( api_key="your-api-key", timeout=30.0, max_retries=5, ) ``` ```python from retell import DefaultHttpxClient import httpx client = Retell( http_client=DefaultHttpxClient( proxy="http://proxy.example.com:8080", ) ) ``` -------------------------------- ### Configure HTTP Client with Proxies and Transports Source: https://github.com/retellai/retell-python-sdk/blob/main/README.md Override the default `httpx` client to customize it, for example, by adding proxy support or custom transports. This configuration is applied when initializing the `Retell` client. ```python import httpx from retell import Retell, DefaultHttpxClient client = Retell( # Or use the `RETELL_BASE_URL` env var base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Client Initialization with Custom HTTP Client (Proxy) Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/configuration-and-setup.md Configure a custom httpx client, such as one with proxy settings. This is useful for network environments that require a proxy. ```python import httpx from retell import Retell, DefaultHttpxClient client = Retell( api_key="your-api-key", http_client=DefaultHttpxClient( proxy="http://proxy.example.com:8080" ) ) ``` -------------------------------- ### Initialize Retell Client with Configuration Options Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/README.md Instantiate the Retell client with essential configuration parameters like API key, base URL, timeout, and retry settings. Use environment variables for API keys instead of hardcoding. ```python Retell( api_key="key", # API authentication base_url="https://api.retellai.com", # API endpoint timeout=60.0, # Request timeout max_retries=2, # Retry count default_headers={}, # Custom headers http_client=None, # Custom HTTP client ) ``` -------------------------------- ### ChatAgent - Get Versions Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Retrieves all versions for a specified chat agent. ```APIDOC ## GET /get-chat-agent-versions/{agent_id} ### Description Retrieves all versions for a chat agent. ### Method GET ### Endpoint /get-chat-agent-versions/{agent_id} ### Parameters #### Path Parameters - **agent_id** (string) - Required - The ID of the chat agent. ### Response #### Success Response (200) - **ChatAgentGetVersionsResponse** (object) - The response object containing a list of chat agent versions. ### Request Example ```python client.chat_agent.get_versions(agent_id) ``` ### Response Example ```json { "example": "ChatAgentGetVersionsResponse" } ``` ``` -------------------------------- ### Basic Client Initialization Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/configuration-and-setup.md Initialize the Retell client with your API key. Ensure your API key is kept secure. ```python from retell import Retell client = Retell(api_key="your-api-key") ``` -------------------------------- ### GET /v2/list-test-case-definitions Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Lists all defined test cases, with options for filtering and pagination. ```APIDOC ## GET /v2/list-test-case-definitions ### Description Lists all defined test cases, with options for filtering and pagination. ### Method GET ### Endpoint /v2/list-test-case-definitions ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination of test case definitions. ### Response #### Success Response (200) - **TestListTestCaseDefinitionsResponse** (object) - A list of test case definitions. ``` -------------------------------- ### Using Context Manager for Client Cleanup Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/configuration-and-setup.md Demonstrates the recommended way to use the Retell client by employing context managers (`with` and `async with`) to ensure proper cleanup of HTTP connections. This is the preferred method for resource management. ```python # Good: Context manager ensures cleanup with Retell(api_key="key") as client: result = client.agent.list() # Or async async with AsyncRetell(api_key="key") as client: result = await client.agent.list() # Manual cleanup if not using context manager client = Retell(api_key="key") try: result = client.agent.list() finally: client.close() ``` -------------------------------- ### GET /v2/list-batch-tests Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Lists all available batch tests, with options for filtering and pagination. ```APIDOC ## GET /v2/list-batch-tests ### Description Lists all available batch tests, with options for filtering and pagination. ### Method GET ### Endpoint /v2/list-batch-tests ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination of batch tests. ### Response #### Success Response (200) - **TestListBatchTestsResponse** (object) - A list of batch tests. ``` -------------------------------- ### Core Documentation Navigation Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/MANIFEST.md This snippet outlines the core documentation files, linking to specific topics like client initialization, configuration, and error handling. ```markdown Core Documentation ├── client-initialization.md → Types + Methods ├── configuration-and-setup.md → Options + Patterns └── errors.md → Exception types + Examples ``` -------------------------------- ### Accessing SDK Resources Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/client-initialization.md Demonstrates how to access and use various resource properties like agent, call, and voice to perform operations such as listing agents or retrieving call details. ```python # Access resources agent_response = client.agent.list() call_response = client.call.retrieve("call_123") voice_list = client.voice.list() ``` -------------------------------- ### GET /get-test-case-definition/{test_case_definition_id} Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Retrieves a specific test case definition by its ID. ```APIDOC ## GET /get-test-case-definition/{test_case_definition_id} ### Description Retrieves a specific test case definition by its ID. ### Method GET ### Endpoint /get-test-case-definition/{test_case_definition_id} ### Parameters #### Path Parameters - **test_case_definition_id** (string) - Required - The ID of the test case definition to retrieve. ### Response #### Success Response (200) - **TestCaseDefinitionResponse** (object) - Details of the requested test case definition. ``` -------------------------------- ### create_chat_completion Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-chat-phone.md Get a chat completion (single-turn LLM response without message history). ```APIDOC ## create_chat_completion ### Description Get a chat completion (single-turn LLM response without message history). ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Query Parameters - **chat_agent_id** (str) - Required - Chat agent ID. - **messages** (List[Message]) - Required - Messages in OpenAI chat format. Each with role ("user", "assistant") and content. - **custom_attributes** (Dict) - Optional - Custom attributes. - **metadata** (object) - Optional - Metadata. ### Request Example { "example": "response = client.chat.create_chat_completion( chat_agent_id=\"chat_agent_123\", messages=[ {\"role\": \"user\", \"content\": \"What's your return policy?\"}, ] )" } ### Response #### Success Response (200) - **assistant_message** (str) - The assistant's message in the chat completion. #### Response Example { "example": "Agent: {response.assistant_message}" } ``` -------------------------------- ### GET /get-mcp-tools/{agent_id} Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Retrieves the MCP tool definitions associated with a specific agent. ```APIDOC ## GET /get-mcp-tools/{agent_id} ### Description Retrieves the MCP tool definitions associated with a specific agent. ### Method GET ### Endpoint /get-mcp-tools/{agent_id} ### Parameters #### Path Parameters - **agent_id** (string) - Required - The ID of the agent whose MCP tools are to be retrieved. #### Query Parameters - **params** (object) - Optional - Parameters for filtering MCP tools. ### Response #### Success Response (200) - **McpToolGetMcpToolsResponse** (object) - A list of MCP tool definitions for the agent. ``` -------------------------------- ### Client Initialization with Environment Variable Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/configuration-and-setup.md Initialize the Retell client using the RETELL_API_KEY environment variable. This is a recommended practice for managing sensitive credentials. ```python import os from retell import Retell client = Retell( api_key=os.environ.get("RETELL_API_KEY") ) ``` -------------------------------- ### Get Test Run Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Retrieves the details of a specific test run. Requires the test_case_job_id. ```python client.tests.get_test_run(test_case_job_id) -> TestCaseJobResponse ``` -------------------------------- ### Create Knowledge Base Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Creates a new knowledge base. Requires parameters for configuration. ```python client.knowledge_base.create(**params) -> KnowledgeBaseResponse ``` -------------------------------- ### retrieve Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-chat-phone.md Get phone number details. Retrieve the configuration and status of a specific phone number. ```APIDOC ## retrieve ### Description Get phone number details. Retrieve the configuration and status of a specific phone number. ### Method GET ### Endpoint /v1/phone-numbers/{phone_number} ### Parameters #### Path Parameters - **phone_number** (str) - Required - Phone number. #### Response #### Success Response (200) - **phone_number** (str) - The phone number. - **agent_id** (str) - The default outbound agent ID. - **nickname** (str) - The display name for the phone number. - **inbound_agent_id** (str) - The agent ID for handling inbound calls. - **inbound_agent_greeting** (str) - The custom greeting for inbound calls. ### Response Example ```json { "phone_number": "+14155552671", "agent_id": "agent_123", "nickname": "Main Support Line", "inbound_agent_id": "agent_456", "inbound_agent_greeting": "Thank you for calling. An agent will be with you shortly." } ``` ``` -------------------------------- ### Get Mcp Tools Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Retrieves Mcp tools associated with a specific agent. Requires the agent_id. ```python client.mcp_tool.get_mcp_tools(agent_id, **params) -> McpToolGetMcpToolsResponse ``` -------------------------------- ### Async Client Initialization with aiohttp Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/configuration-and-setup.md Initialize the asynchronous Retell client using aiohttp. This is suitable for non-blocking I/O operations. ```python from retell import AsyncRetell, DefaultAioHttpClient client = AsyncRetell( api_key="your-api-key", http_client=DefaultAioHttpClient() ) ``` -------------------------------- ### Get Chat Agent Versions Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Retrieves all versions associated with a given chat agent ID. ```python client.chat_agent.get_versions(agent_id) -> ChatAgentGetVersionsResponse ``` -------------------------------- ### Get Agent Versions Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Use this method to retrieve all versions of a specific agent using its ID. ```python from retell.types import ( AgentResponse, AgentListResponse, AgentCreateVersionResponse, AgentGetVersionsResponse, ) # Assuming 'client' is an initialized Retell client instance # Example usage: # client.agent.get_versions(agent_id) ``` -------------------------------- ### Basic Usage: Create Agent and Phone Call Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/README.md Demonstrates how to initialize the Retell client, create a voice agent, and initiate a phone call. ```python from retell import Retell client = Retell(api_key="your-api-key") # Create a voice agent agent = client.agent.create( response_engine={ "type": "retell-llm", "llm_id": "llm_123" }, voice_id="retell-Cimo" ) # Create a phone call call = client.call.create_phone_call( agent_id=agent.agent_id, phone_number="+14155552671" ) ``` -------------------------------- ### stop Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-calls.md Stops an active or queued phone call. This is useful for terminating calls that are in progress or waiting to start. ```APIDOC ## stop ### Description Stops an active or queued call. Use this method to terminate a call that is currently in progress or waiting in the queue. ### Method POST ### Endpoint /v1/calls/{call_id}/stop ### Parameters #### Path Parameters - **call_id** (str) - Required - Call ID to stop. #### Query Parameters None #### Request Body None ### Request Example ```json { "call_id": "call_67890" } ``` ### Response #### Success Response (200) None (Indicates the call was successfully stopped). #### Response Example (No response body for success) ``` -------------------------------- ### Bootstrap Environment with Rye Source: https://github.com/retellai/retell-python-sdk/blob/main/CONTRIBUTING.md Run this script to automatically provision a Python environment with the expected Python version using Rye. ```sh ./scripts/bootstrap ``` -------------------------------- ### Get MCP Tools Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-other-resources.md Retrieves a list of available MCP tools. This method is part of the McpTool resource. ```python from retell.types import McpToolGetMcpToolsResponse from typing import Dict, Optional # Assuming 'client' is an initialized Retell client instance # and Headers, Query, Body, and NotGiven are appropriately defined. def get_mcp_tools( *, extra_headers: Dict | None = None, extra_query: Dict | None = None, extra_body: Dict | None = None, timeout: float | None = None, # Simplified timeout type for example ) -> McpToolGetMcpToolsResponse: # This is a placeholder for the actual SDK method call. # The actual implementation would involve client.mcp_tool.get_mcp_tools(...) pass ``` -------------------------------- ### Get Playground Completion Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-other-resources.md Obtain an LLM completion for testing and debugging purposes. Requires an LLM ID. ```python def completion( *, llm_id: str, context: Optional[str] | Omit = omit, extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> PlaygroundCompletionResponse: ``` -------------------------------- ### GET /get-test-run/{test_case_job_id} Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Retrieves the status and results of a specific test run using its job ID. ```APIDOC ## GET /get-test-run/{test_case_job_id} ### Description Retrieves the status and results of a specific test run using its job ID. ### Method GET ### Endpoint /get-test-run/{test_case_job_id} ### Parameters #### Path Parameters - **test_case_job_id** (string) - Required - The ID of the test case job to retrieve. ### Response #### Success Response (200) - **TestCaseJobResponse** (object) - Details of the requested test run. ``` -------------------------------- ### GET /get-batch-test/{test_case_batch_job_id} Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Retrieves details of a specific batch test job using its job ID. ```APIDOC ## GET /get-batch-test/{test_case_batch_job_id} ### Description Retrieves details of a specific batch test job using its job ID. ### Method GET ### Endpoint /get-batch-test/{test_case_batch_job_id} ### Parameters #### Path Parameters - **test_case_batch_job_id** (string) - Required - The ID of the batch test job to retrieve. ### Response #### Success Response (200) - **BatchTestResponse** (object) - Details of the requested batch test job. ``` -------------------------------- ### Build Wheel File Source: https://github.com/retellai/retell-python-sdk/blob/main/CONTRIBUTING.md Create a distributable wheel file for the library using Rye or Python's build module. ```sh $ rye build # or $ python -m build ``` -------------------------------- ### Get Batch Test Status Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Retrieves the status and results of a batch test job. Requires the test_case_batch_job_id. ```python client.tests.get_batch_test(test_case_batch_job_id) -> BatchTestResponse ``` -------------------------------- ### Initialize Retell Client and Retrieve Call Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-calls.md Demonstrates how to initialize the Retell client and retrieve details for a specific call using its ID. ```python from retell import Retell client = Retell(api_key="your-api-key") response = client.call.retrieve("call_id") ``` -------------------------------- ### Create Agent with Nested Parameters Source: https://github.com/retellai/retell-python-sdk/blob/main/README.md Demonstrates how to create an agent using nested dictionaries for response engine and call screening options. Ensure the `llm_id` and `voice_id` are valid. ```python from retell import Retell client = Retell() agent_response = client.agent.create( response_engine={ "llm_id": "llm_234sdertfsdsfsdf", "type": "retell-llm", }, voice_id="retell-Cimo", call_screening_option={ "agent_identity": "Acme Health scheduling team", "call_purpose": "confirming your appointment for tomorrow", }, ) print(agent_response.call_screening_option) ``` -------------------------------- ### Retrieve Conversation Flow Component Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Use the `retrieve` method to get a specific conversation flow component by its ID. ```python client.conversation_flow_component.retrieve(conversation_flow_component_id) ``` -------------------------------- ### copy() Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/client-initialization.md Creates a new client instance with modified options, reusing settings from the current client. This method allows for flexible configuration adjustments without affecting the original client instance. ```APIDOC ## copy() ### Description Create a new client instance with modified options, reusing settings from the current client. ### Method ```python Retell.copy( *, api_key: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, http_client: httpx.Client | None = None, max_retries: int | NotGiven = not_given, default_headers: Mapping[str, str] | None = None, set_default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, set_default_query: Mapping[str, object] | None = None, _extra_kwargs: Mapping[str, Any] = {}, ) -> Self ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **api_key** (str) - New API key. - **base_url** (str | httpx.URL) - New base URL. - **timeout** (float | Timeout) - New timeout. - **http_client** (httpx.Client) - New HTTP client. - **max_retries** (int) - New maximum retries. - **default_headers** (Mapping[str, str]) - Additional headers to merge with existing headers. Mutually exclusive with `set_default_headers`. - **set_default_headers** (Mapping[str, str]) - Replace all default headers. Mutually exclusive with `default_headers`. - **default_query** (Mapping[str, object]) - Additional query params to merge. Mutually exclusive with `set_default_query`. - **set_default_query** (Mapping[str, object]) - Replace all default query params. Mutually exclusive with `default_query`. ### Returns A new client instance with modified settings. ### Raises `ValueError` — If both `default_headers` and `set_default_headers` are provided, or both `default_query` and `set_default_query` are provided. ### Request Example ```python client = Retell(api_key="key1", timeout=60.0) # Create a new client with different timeout, reusing other settings client_fast = client.copy(timeout=5.0) # Replace all default headers client_custom = client.copy(set_default_headers={"X-Custom": "value"}) ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Create an Agent Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-agent.md Use this snippet to create a new agent with specified LLM configuration, voice, name, and webhook settings. Ensure the response_engine and voice_id are correctly provided. ```python agent = client.agent.create( response_engine={ "type": "retell-llm", "llm_id": "llm_234sdertfsdsfsdf", }, voice_id="retell-Cimo", agent_name="Customer Service Bot", language="en-US", enable_backchannel=True, interruption_sensitivity=0.5, webhook_config={ "call_started": "https://example.com/webhooks/call_started", "call_ended": "https://example.com/webhooks/call_ended", } ) print(f"Agent created: {agent.agent_id}") ``` -------------------------------- ### Retrieve Call Details Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-calls.md Example of retrieving a specific call's details using the call ID and printing its attributes. ```python call = client.call.retrieve("call_67890") print(f"Call ID: {call.call_id}") print(f"Status: {call.status}") print(f"Start time: {call.start_timestamp}") ``` -------------------------------- ### Create a New Agent Version Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-agent.md Create a snapshot of the current agent configuration. This is useful for version control and rollback. ```python version = client.agent.create_version("agent_123") print(f"New version created: {version.version_id}") ``` -------------------------------- ### GET /v2/list-test-runs/{test_case_batch_job_id} Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Lists all test runs associated with a specific batch test job, with options for filtering and pagination. ```APIDOC ## GET /v2/list-test-runs/{test_case_batch_job_id} ### Description Lists all test runs associated with a specific batch test job, with options for filtering and pagination. ### Method GET ### Endpoint /v2/list-test-runs/{test_case_batch_job_id} ### Parameters #### Path Parameters - **test_case_batch_job_id** (string) - Required - The ID of the batch test job whose runs are to be listed. #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination of test runs. ### Response #### Success Response (200) - **TestListTestRunsResponse** (object) - A list of test runs. ``` -------------------------------- ### create Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-other-resources.md Creates a new knowledge base with a specified name. It allows for additional headers, query parameters, and body content, as well as timeout overrides. ```APIDOC ## create Knowledge Base ### Description Create a new knowledge base. ### Method POST ### Endpoint /v1/knowledge_bases ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **kb_name** (str) - Yes - Name of the knowledge base. - **extra_headers** (Headers) - No - Additional headers. - **extra_query** (Query) - No - Additional query parameters. - **extra_body** (Body) - No - Additional JSON properties. - **timeout** (float | httpx.Timeout) - No - Override timeout. ### Request Example ```json { "kb_name": "Company Documentation" } ``` ### Response #### Success Response (200) - **knowledge_base_id** (str) - The ID of the created knowledge base. #### Response Example ```json { "knowledge_base_id": "kb_abc123" } ``` ``` -------------------------------- ### Retrieve Conversation Flow Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Use the `retrieve` method to get a specific conversation flow by its ID. Optional parameters can be passed. ```python client.conversation_flow.retrieve(conversation_flow_id, **params) ``` -------------------------------- ### Initialize Synchronous Retell Client Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/INDEX.md Instantiate the synchronous Retell client with your API key. Use this for standard API requests. ```python from retell import Retell client = Retell(api_key="your-api-key") response = client.agent.list() ``` -------------------------------- ### Get Retell SDK Version Information Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/configuration-and-setup.md Access the SDK's version number and title using the `__version__` and `__title__` attributes. ```python import retell # Get SDK version print(retell.__version__) # e.g., "5.53.0" # Get title print(retell.__title__) # "retell-sdk" ``` -------------------------------- ### Create Agent Instance Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-agent.md Instantiate the Retell client and access the agent resource for creating a new voice agent. Replace 'your-api-key' with your actual API key. ```python from retell import Retell client = Retell(api_key="your-api-key") agent = client.agent.create(...) ``` -------------------------------- ### FastAPI Webhook Handler Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/webhooks-and-events.md Example of a FastAPI application to handle Retell webhook events, including signature verification and Pydantic model validation. ```python from fastapi import FastAPI, Request, HTTPException from pydantic import BaseModel import hmac import hashlib from typing import List, Optional app = FastAPI() WEBHOOK_SECRET = "your-webhook-secret" class Message(BaseModel): role: str content: str timestamp: int class CallStartedEvent(BaseModel): event: str call_id: str agent_id: str phone_number: str direction: str custom_attributes: Optional[dict] = None timestamp: int class CallEndedEvent(BaseModel): event: str call_id: str agent_id: str phone_number: str direction: str duration_ms: int call_status: str end_reason: str custom_attributes: Optional[dict] = None timestamp: int async def verify_signature(request: Request) -> bool: signature = request.headers.get("X-Retell-Signature") body = await request.body() expected = hmac.new( WEBHOOK_SECRET.encode(), body, hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, expected) @app.post("/webhooks/call_started") async def handle_call_started(request: Request, event: CallStartedEvent): if not await verify_signature(request): raise HTTPException(status_code=401, detail="Invalid signature") print(f"Call started: {event.call_id}") # Process event return {"status": "received"} @app.post("/webhooks/call_ended") async def handle_call_ended(request: Request, event: CallEndedEvent): if not await verify_signature(request): raise HTTPException(status_code=401, detail="Invalid signature") print(f"Call ended: {event.call_id} (duration: {event.duration_ms}ms)") # Process event return {"status": "received"} ``` -------------------------------- ### Create Resource Method Pattern Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/INDEX.md Use this pattern for creating resources. It accepts required and optional parameters. The response typically includes the resource ID, creation timestamp, status, and metadata. ```python response = client.resource.create( required_param="value", optional_param="value" # Default: omitted ) # Common fields on most responses response.{resource}_id # Unique identifier response.created_at # Unix timestamp response.status # Current status response.metadata # Custom metadata (if provided) ``` -------------------------------- ### Flask Webhook Handler Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/webhooks-and-events.md Example of a Flask application to handle various Retell webhook events, including signature verification and event processing. ```python from flask import Flask, request import hmac import hashlib import json app = Flask(__name__) WEBHOOK_SECRET = "your-webhook-secret" # Store securely def verify_webhook_signature(payload_bytes, signature): """Verify webhook came from Retell""" expected = hmac.new( WEBHOOK_SECRET.encode(), payload_bytes, hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, expected) @app.route("/webhooks/call_started", methods=["POST"]) def on_call_started(): # Verify signature signature = request.headers.get("X-Retell-Signature") payload_bytes = request.get_data() if not verify_webhook_signature(payload_bytes, signature): return {"error": "Invalid signature"}, 401 data = request.get_json() # Process event call_id = data["call_id"] agent_id = data["agent_id"] phone = data["phone_number"] print(f"Call started: {call_id} from {phone}") # Your business logic here # e.g., log to database, notify other systems, etc. return {"status": "received"}, 200 @app.route("/webhooks/call_ended", methods=["POST"]) def on_call_ended(): signature = request.headers.get("X-Retell-Signature") payload_bytes = request.get_data() if not verify_webhook_signature(payload_bytes, signature): return {"error": "Invalid signature"}, 401 data = request.get_json() call_id = data["call_id"] duration = data["duration_ms"] print(f"Call ended: {call_id} (duration: {duration}ms)") # Your business logic here return {"status": "received"}, 200 @app.route("/webhooks/transcript", methods=["POST"]) def on_transcript(): signature = request.headers.get("X-Retell-Signature") payload_bytes = request.get_data() if not verify_webhook_signature(payload_bytes, signature): return {"error": "Invalid signature"}, 401 data = request.get_json() call_id = data["call_id"] transcript = data["transcript"] print(f"Transcript for {call_id}:") for msg in transcript: print(f" {msg['role'].upper()}: {msg['content']}") # Save transcript to database, send to analytics, etc. return {"status": "received"}, 200 @app.route("/webhooks/tool_use", methods=["POST"]) def on_tool_use(): signature = request.headers.get("X-Retell-Signature") payload_bytes = request.get_data() if not verify_webhook_signature(payload_bytes, signature): return {"error": "Invalid signature"}, 401 data = request.get_json() call_id = data["call_id"] tool_name = data["tool_name"] tool_input = data["tool_input"] tool_output = data["tool_output"] print(f"Tool used: {tool_name}") print(f" Input: {tool_input}") print(f" Output: {tool_output}") # Log tool usage, audit, etc. return {"status": "received"}, 200 if __name__ == "__main__": app.run(port=5000) ``` -------------------------------- ### Create LLM Configuration Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-llm-voice.md Use this method to create a new language model configuration. You can specify the base model, system prompt, and tools the LLM can use. Ensure the `llm_name` is provided. ```python llm = client.llm.create( llm_name="Customer Support LLM", llm_model="gpt-4-turbo", general_prompt_override="You are a helpful customer support agent for Acme Inc.", general_tools=[ { "name": "lookup_customer", "description": "Look up a customer by email or ID", "function": { "description": "Retrieve customer information", "parameters": { "type": "object", "properties": { "customer_id": { "type": "string", "description": "Customer ID" } }, "required": ["customer_id"] } } } ], temperature=0.7 ) print(f"LLM created: {llm.llm_id}") ``` -------------------------------- ### Enable Logging in Python Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/configuration-and-setup.md Configure Python's `logging` module to display SDK logs. Set the level to `DEBUG` for the most detailed output, including all requests and responses. ```python import logging logging.basicConfig(level=logging.DEBUG) # Now all SDK logs will be shown client = Retell(api_key="your-api-key") ``` -------------------------------- ### Retrieve a Specific Call Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/README.md Example of how to retrieve details for a specific call using its ID. This method accepts an optional timeout and extra headers. ```python # Retrieve a specific call call = client.call.retrieve("call_id") # Parameters: call_id (required), timeout (optional), extra headers # Returns: CallResponse with call details # Raises: NotFoundError if call doesn't exist ``` -------------------------------- ### Async Usage with aiohttp Source: https://github.com/retellai/retell-python-sdk/blob/main/README.md Demonstrates creating an agent using the asynchronous Retell client with aiohttp as the HTTP backend. Ensure the RETELL_API_KEY environment variable is set. ```python import os import asyncio from retell import DefaultAioHttpClient from retell import AsyncRetell async def main() -> None: async with AsyncRetell( api_key=os.environ.get("RETELL_API_KEY"), # This is the default and can be omitted http_client=DefaultAioHttpClient(), ) as client: agent_response = await client.agent.create( response_engine={ "llm_id": "llm_234sdertfsdsfsdf", "type": "retell-llm", }, voice_id="retell-Cimo", ) print(agent_response.agent_id) asyncio.run(main()) ``` -------------------------------- ### Get Test Case Definition Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Fetches a specific test case definition by its ID. Use this to review or retrieve test case details. ```python client.tests.get_test_case_definition(test_case_definition_id) -> TestCaseDefinitionResponse ``` -------------------------------- ### Synchronous Client Constructor Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/client-initialization.md Shows the parameters available for constructing a synchronous Retell client instance. This includes authentication, network configuration, and retry settings. ```python Retell( *, api_key: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, max_retries: int = 2, default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, http_client: httpx.Client | None = None, _strict_response_validation: bool = False, ) -> None ``` -------------------------------- ### List Knowledge Bases Source: https://github.com/retellai/retell-python-sdk/blob/main/api.md Lists all available knowledge bases. ```python client.knowledge_base.list() -> KnowledgeBaseListResponse ``` -------------------------------- ### WebhookConfig Configuration Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/types-reference.md Configures event webhooks for various call events. Specify URLs for call started, ended, transcript, and tool use events. ```python webhook_config = { "call_started": "https://example.com/webhooks/call_started", "call_ended": "https://example.com/webhooks/call_ended", "call_transcript": "https://example.com/webhooks/transcript", "tool_use": "https://example.com/webhooks/tool_use" } ``` -------------------------------- ### Get Total Call Count Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/api-reference-calls.md List calls while including the total count of matching records. This requires an additional aggregate query and is useful for reporting. ```python calls_with_total = client.call.list( filter_criteria={"agent_id": "agent_123"}, include_total=True ) print(f"Total calls: {calls_with_total.total}") ``` -------------------------------- ### Basic Async Usage with AsyncRetell Source: https://github.com/retellai/retell-python-sdk/blob/main/_autodocs/configuration-and-setup.md Demonstrates the basic usage of the asynchronous Retell client. Use `await` with asynchronous calls and run the main async function using `asyncio.run()`. ```python import asyncio from retell import AsyncRetell async def main(): client = AsyncRetell(api_key="your-api-key") # Use await with async calls agent = await client.agent.retrieve("agent_123") print(f"Agent: {agent.agent_name}") asyncio.run(main()) ```