conversimple-sdk


Nameconversimple-sdk JSON
Version 0.2.0 PyPI version JSON
download
home_pagehttps://github.com/conversimple/conversimple-sdk
SummaryPython SDK for Conversimple Conversational AI Platform
upload_time2025-10-11 22:31:50
maintainerNone
docs_urlNone
authorConversimple
requires_python>=3.8
licenseNone
keywords conversational ai voice ai chatbot websocket sdk speech to text text to speech
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Conversimple SDK

Python client library for the Conversimple Conversational AI Platform.

This SDK enables customers to build and deploy AI agents that integrate with the Conversimple platform's WebRTC infrastructure and conversation management, providing real-time voice conversation capabilities with function calling support.

## Features

- **Real-time Voice Conversations**: Integrate with WebRTC-based voice conversations
- **Function Calling**: Define tools that can be executed during conversations
- **Event-Driven Architecture**: React to conversation lifecycle events  
- **Auto-Reconnection**: Fault-tolerant WebSocket connection with exponential backoff
- **Type Hints**: Full typing support for better development experience
- **Async/Await Support**: Both sync and async tool definitions

## Quick Start

### Installation

```bash
pip install conversimple-sdk
```

### Basic Usage

```python
import asyncio
from conversimple import ConversimpleAgent, tool

class MyAgent(ConversimpleAgent):
    @tool("Get current weather for a location")
    def get_weather(self, location: str) -> dict:
        return {"location": location, "temperature": 72, "condition": "sunny"}

    def on_conversation_started(self, conversation_id: str):
        print(f"Conversation started: {conversation_id}")

async def main():
    agent = MyAgent(
        api_key="your-api-key",
        customer_id="your-customer-id"
    )
    
    await agent.start()
    
    # Keep running
    while True:
        await asyncio.sleep(1)

if __name__ == "__main__":
    asyncio.run(main())
```

## Core Concepts

### Agent Session Model

Each `ConversimpleAgent` instance handles a single conversation session. For multiple concurrent conversations, create multiple agent instances:

```python
# Per-conversation agent instances
async def handle_conversation(conversation_id):
    agent = MyAgent(api_key=api_key, customer_id=customer_id)
    await agent.start(conversation_id=conversation_id)
```

### Tool Registration

Define tools using the `@tool` and `@tool_async` decorators:

```python
from conversimple import tool, tool_async

class BusinessAgent(ConversimpleAgent):
    @tool("Look up customer information")
    def lookup_customer(self, customer_id: str) -> dict:
        # Synchronous tool execution
        return customer_database.get(customer_id)
    
    @tool_async("Send email notification")
    async def send_email(self, email: str, subject: str, body: str) -> dict:
        # Asynchronous tool execution
        result = await email_service.send(email, subject, body)
        return {"sent": True, "message_id": result.id}
```

### Event Callbacks

Handle conversation lifecycle events:

```python
class MyAgent(ConversimpleAgent):
    def on_conversation_started(self, conversation_id: str):
        print(f"🎤 Conversation started: {conversation_id}")
    
    def on_conversation_ended(self, conversation_id: str):
        print(f"📞 Conversation ended: {conversation_id}")
    
    def on_tool_called(self, tool_call):
        print(f"🔧 Executing tool: {tool_call.tool_name}")
    
    def on_error(self, error_type: str, message: str, details: dict):
        print(f"❌ Error ({error_type}): {message}")
```

## Configuration

### Environment Variables

```bash
export CONVERSIMPLE_API_KEY="your-api-key"
export CONVERSIMPLE_CUSTOMER_ID="your-customer-id"
export CONVERSIMPLE_PLATFORM_URL="ws://localhost:4000/sdk/websocket"
export CONVERSIMPLE_LOG_LEVEL="INFO"
```

### Basic Configuration

```python
# Simple production setup (recommended)
agent = ConversimpleAgent(
    api_key="your-api-key",
    customer_id="your-customer-id",
    platform_url="wss://platform.conversimple.com/sdk/websocket"
)
# Uses infinite retry with circuit breaker (production defaults)
```

### Advanced Connection Configuration

Control reconnection behavior, timeouts, and circuit breaker:

```python
agent = ConversimpleAgent(
    api_key="your-api-key",
    customer_id="your-customer-id",
    platform_url="wss://platform.conversimple.com/sdk/websocket",

    # Retry configuration
    max_reconnect_attempts=None,      # None = infinite retries (default)
                                      # Set to number for limited retries
    reconnect_backoff=2.0,            # Exponential backoff multiplier (default: 2.0)
    max_backoff=300.0,                # Max wait between retries: 5 minutes (default)
    total_retry_duration=None,        # None = no time limit (default)
                                      # Set to seconds for max retry duration

    # Circuit breaker (stops retrying on permanent failures)
    enable_circuit_breaker=True       # Default: True (recommended)
)
```

### Configuration Examples

#### Production: Infinite Retry with Circuit Breaker
```python
# Recommended for production - never gives up on transient failures
agent = ConversimpleAgent(
    api_key=os.getenv("CONVERSIMPLE_API_KEY"),
    platform_url="wss://platform.conversimple.com/sdk/websocket",
    max_reconnect_attempts=None,      # Infinite retries
    enable_circuit_breaker=True       # Stop on auth failures
)
```

#### Development: Fast Failure
```python
# Good for testing - fails quickly
agent = ConversimpleAgent(
    api_key="test-key",
    platform_url="ws://localhost:4000/sdk/websocket",
    max_reconnect_attempts=5,         # Only 5 attempts
    reconnect_backoff=1.5,            # Faster backoff
    max_backoff=30,                   # Max 30 seconds between retries
    total_retry_duration=120          # Give up after 2 minutes
)
```

#### Aggressive Retry (Long-Running Services)
```python
# For services that must stay connected
agent = ConversimpleAgent(
    api_key=os.getenv("CONVERSIMPLE_API_KEY"),
    max_reconnect_attempts=None,      # Never give up
    max_backoff=600,                  # Max 10 minutes between retries
    enable_circuit_breaker=True       # Still stop on permanent failures
)
```

#### Debugging: Disable Circuit Breaker
```python
# WARNING: Only for debugging - will retry even on auth failures
agent = ConversimpleAgent(
    api_key="invalid-key",
    max_reconnect_attempts=10,
    enable_circuit_breaker=False      # Retry all errors (not recommended)
)
```

## Examples

The SDK includes several example implementations:

### Simple Weather Agent
```bash
python examples/simple_agent.py
```

A basic agent that provides weather information, demonstrating:
- Tool registration with `@tool` decorator
- Conversation lifecycle callbacks
- Basic agent structure

### Customer Service Agent  
```bash
python examples/customer_service.py
```

Advanced customer service agent with multiple tools:
- Customer lookup and account management
- Support ticket creation
- Email notifications
- Refund processing
- Async tool execution

### Multi-Step Booking Agent
```bash  
python examples/booking_agent.py
```

Complex booking workflow demonstrating:
- Multi-turn conversation state management
- Booking creation, confirmation, and cancellation
- Business rule validation
- Transaction-like processes

## API Reference

### ConversimpleAgent

Main agent class for platform integration.

#### Constructor

```python
ConversimpleAgent(
    api_key: str,
    customer_id: Optional[str] = None,
    platform_url: str = "ws://localhost:4000/sdk/websocket",
    max_reconnect_attempts: Optional[int] = None,
    reconnect_backoff: float = 2.0,
    max_backoff: float = 300.0,
    total_retry_duration: Optional[float] = None,
    enable_circuit_breaker: bool = True
)
```

**Parameters:**
- `api_key` (str): Customer API key for authentication
- `customer_id` (str, optional): Customer identifier (derived from API key if not provided)
- `platform_url` (str): WebSocket URL for platform connection
- `max_reconnect_attempts` (int, optional): Maximum reconnection attempts (None = infinite)
- `reconnect_backoff` (float): Exponential backoff multiplier (default: 2.0)
- `max_backoff` (float): Maximum backoff time in seconds (default: 300s)
- `total_retry_duration` (float, optional): Maximum total retry time (None = no limit)
- `enable_circuit_breaker` (bool): Enable circuit breaker for permanent failures (default: True)

#### Methods

- `async start(conversation_id=None)` - Start agent and connect to platform
- `async stop()` - Stop agent and disconnect
- `on_conversation_started(conversation_id)` - Conversation started callback
- `on_conversation_ended(conversation_id)` - Conversation ended callback
- `on_tool_called(tool_call)` - Tool execution callback
- `on_tool_completed(call_id, result)` - Tool completion callback
- `on_error(error_type, message, details)` - Error handling callback

### Tool Decorators

#### @tool(description)
Register synchronous tool function.

```python
@tool("Description of what this tool does")
def my_tool(self, param1: str, param2: int = 10) -> dict:
    return {"result": "success"}
```

#### @tool_async(description)  
Register asynchronous tool function.

```python
@tool_async("Description of async tool")
async def my_async_tool(self, param: str) -> dict:
    await asyncio.sleep(0.1)  # Async operation
    return {"result": "success"}
```

### Type Hints

The SDK automatically generates JSON schemas from Python type hints:

- `str` → `"type": "string"`
- `int` → `"type": "integer"`  
- `float` → `"type": "number"`
- `bool` → `"type": "boolean"`
- `list` → `"type": "array"`
- `dict` → `"type": "object"`
- `Optional[T]` → Same as T (nullable)

## Protocol Details

### WebSocket Messages

The SDK communicates with the platform using these message types:

#### Outgoing (SDK → Platform)
- `register_conversation_tools` - Register available tools
- `tool_call_response` - Tool execution results
- `tool_call_error` - Tool execution failures  
- `heartbeat` - Connection keepalive

#### Incoming (Platform → SDK)
- `tool_call_request` - Tool execution requests
- `conversation_lifecycle` - Conversation started/ended
- `config_update` - Configuration updates
- `analytics_update` - Usage analytics

### Message Format

Tool registration:
```json
{
  "conversation_id": "conv_123",
  "tools": [
    {
      "name": "get_weather",
      "description": "Get weather for location", 
      "parameters": {
        "type": "object",
        "properties": {
          "location": {"type": "string"}
        },
        "required": ["location"]
      }
    }
  ]
}
```

Tool execution:
```json
{
  "call_id": "call_abc123",
  "result": {"temperature": 22, "condition": "sunny"}
}
```

## Error Handling

The SDK provides comprehensive error handling with intelligent retry logic:

### Connection Errors

#### Automatic Reconnection
- **Exponential backoff** with jitter to prevent thundering herd
- **Infinite retries** by default for transient failures (network issues, server restarts)
- **Circuit breaker** stops retrying on permanent failures (invalid credentials, suspended accounts)

#### Circuit Breaker Behavior

The circuit breaker detects **permanent errors** and stops retrying immediately:

**Permanent Errors (No Retry):**
- Authentication failures (invalid API key, expired credentials)
- Authorization errors (customer suspended, account inactive)
- HTTP 401, 403, 400 status codes
- Missing required credentials

**Transient Errors (Auto Retry):**
- Network timeouts and connection refused
- Server temporarily unavailable
- WebSocket connection drops
- Database connection issues

#### Connection Event Handling

```python
class MyAgent(ConversimpleAgent):
    def on_error(self, error_type: str, message: str, details: dict):
        if error_type == "AUTH_FAILED":
            # Circuit breaker opened - permanent failure
            print(f"🚫 Authentication failed: {message}")
            print("🔑 Check your API key and try again")
            # Do NOT retry - fix credentials first

        elif error_type == "CUSTOMER_SUSPENDED":
            # Circuit breaker opened - account issue
            print(f"⛔ Account suspended: {message}")
            print("📧 Contact support to reactivate account")

        else:
            # Transient error - will auto-retry
            print(f"⚠️  Temporary error: {message}")
            print("🔄 Will reconnect automatically")
```

#### Retry Behavior Examples

```python
# Default: Infinite retry with circuit breaker (recommended)
agent = ConversimpleAgent(api_key="valid-key")
# Network issue → Retries: 2s, 4s, 8s, 16s, ... up to 300s, forever
# Invalid key → Circuit breaker opens immediately, no retries

# Limited retries for testing
agent = ConversimpleAgent(
    api_key="test-key",
    max_reconnect_attempts=5,
    total_retry_duration=120  # Give up after 2 minutes
)
# Network issue → Retries: 2s, 4s, 8s, 16s, 32s, then gives up
# Invalid key → Circuit breaker opens immediately

# Aggressive retry for critical services
agent = ConversimpleAgent(
    api_key="prod-key",
    max_backoff=600,  # Max 10 minutes between retries
    enable_circuit_breaker=True
)
# Network issue → Retries forever, up to 10 min between attempts
# Invalid key → Still stops immediately (circuit breaker)
```

### Tool Execution Errors
- Automatic error reporting to platform
- Exception wrapping and formatting
- Timeout handling (configurable per tool call)

### Logging

```python
import logging

# Configure SDK logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# SDK logger
logger = logging.getLogger("conversimple")
logger.setLevel(logging.DEBUG)  # Detailed connection logs

# Connection-specific logging
connection_logger = logging.getLogger("conversimple.connection")
connection_logger.setLevel(logging.INFO)  # Less verbose
```

**Log Levels:**
- `DEBUG`: Detailed connection events, retry attempts, backoff calculations
- `INFO`: Connection status, tool calls, conversation events
- `WARNING`: Connection warnings, approaching timeouts
- `ERROR`: Connection failures, tool errors, permanent failures

## Development

### Setup Development Environment

```bash
git clone https://github.com/conversimple/conversimple-sdk
cd conversimple-sdk

# Create virtual environment  
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install -r requirements.txt -r requirements-dev.txt

# Install in editable mode
pip install -e .
```

### Running Tests

```bash
pytest tests/
```

### Code Formatting

```bash
black conversimple/
flake8 conversimple/
mypy conversimple/
```

## License

This project is licensed under the MIT License - see the LICENSE file for details.

## Support

- **Documentation**: https://docs.conversimple.com/sdk
- **GitHub Issues**: https://github.com/conversimple/conversimple-sdk/issues  
- **Email Support**: support@conversimple.com
- **Community**: https://community.conversimple.com

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/conversimple/conversimple-sdk",
    "name": "conversimple-sdk",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "conversational ai, voice ai, chatbot, websocket, sdk, speech to text, text to speech",
    "author": "Conversimple",
    "author_email": "support@conversimple.com",
    "download_url": "https://files.pythonhosted.org/packages/e0/d7/016998c5dd165e026e1bddf0b57a2e68b323a92ed3d6f7c33fa825eadc68/conversimple_sdk-0.2.0.tar.gz",
    "platform": null,
    "description": "# Conversimple SDK\n\nPython client library for the Conversimple Conversational AI Platform.\n\nThis SDK enables customers to build and deploy AI agents that integrate with the Conversimple platform's WebRTC infrastructure and conversation management, providing real-time voice conversation capabilities with function calling support.\n\n## Features\n\n- **Real-time Voice Conversations**: Integrate with WebRTC-based voice conversations\n- **Function Calling**: Define tools that can be executed during conversations\n- **Event-Driven Architecture**: React to conversation lifecycle events  \n- **Auto-Reconnection**: Fault-tolerant WebSocket connection with exponential backoff\n- **Type Hints**: Full typing support for better development experience\n- **Async/Await Support**: Both sync and async tool definitions\n\n## Quick Start\n\n### Installation\n\n```bash\npip install conversimple-sdk\n```\n\n### Basic Usage\n\n```python\nimport asyncio\nfrom conversimple import ConversimpleAgent, tool\n\nclass MyAgent(ConversimpleAgent):\n    @tool(\"Get current weather for a location\")\n    def get_weather(self, location: str) -> dict:\n        return {\"location\": location, \"temperature\": 72, \"condition\": \"sunny\"}\n\n    def on_conversation_started(self, conversation_id: str):\n        print(f\"Conversation started: {conversation_id}\")\n\nasync def main():\n    agent = MyAgent(\n        api_key=\"your-api-key\",\n        customer_id=\"your-customer-id\"\n    )\n    \n    await agent.start()\n    \n    # Keep running\n    while True:\n        await asyncio.sleep(1)\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n## Core Concepts\n\n### Agent Session Model\n\nEach `ConversimpleAgent` instance handles a single conversation session. For multiple concurrent conversations, create multiple agent instances:\n\n```python\n# Per-conversation agent instances\nasync def handle_conversation(conversation_id):\n    agent = MyAgent(api_key=api_key, customer_id=customer_id)\n    await agent.start(conversation_id=conversation_id)\n```\n\n### Tool Registration\n\nDefine tools using the `@tool` and `@tool_async` decorators:\n\n```python\nfrom conversimple import tool, tool_async\n\nclass BusinessAgent(ConversimpleAgent):\n    @tool(\"Look up customer information\")\n    def lookup_customer(self, customer_id: str) -> dict:\n        # Synchronous tool execution\n        return customer_database.get(customer_id)\n    \n    @tool_async(\"Send email notification\")\n    async def send_email(self, email: str, subject: str, body: str) -> dict:\n        # Asynchronous tool execution\n        result = await email_service.send(email, subject, body)\n        return {\"sent\": True, \"message_id\": result.id}\n```\n\n### Event Callbacks\n\nHandle conversation lifecycle events:\n\n```python\nclass MyAgent(ConversimpleAgent):\n    def on_conversation_started(self, conversation_id: str):\n        print(f\"\ud83c\udfa4 Conversation started: {conversation_id}\")\n    \n    def on_conversation_ended(self, conversation_id: str):\n        print(f\"\ud83d\udcde Conversation ended: {conversation_id}\")\n    \n    def on_tool_called(self, tool_call):\n        print(f\"\ud83d\udd27 Executing tool: {tool_call.tool_name}\")\n    \n    def on_error(self, error_type: str, message: str, details: dict):\n        print(f\"\u274c Error ({error_type}): {message}\")\n```\n\n## Configuration\n\n### Environment Variables\n\n```bash\nexport CONVERSIMPLE_API_KEY=\"your-api-key\"\nexport CONVERSIMPLE_CUSTOMER_ID=\"your-customer-id\"\nexport CONVERSIMPLE_PLATFORM_URL=\"ws://localhost:4000/sdk/websocket\"\nexport CONVERSIMPLE_LOG_LEVEL=\"INFO\"\n```\n\n### Basic Configuration\n\n```python\n# Simple production setup (recommended)\nagent = ConversimpleAgent(\n    api_key=\"your-api-key\",\n    customer_id=\"your-customer-id\",\n    platform_url=\"wss://platform.conversimple.com/sdk/websocket\"\n)\n# Uses infinite retry with circuit breaker (production defaults)\n```\n\n### Advanced Connection Configuration\n\nControl reconnection behavior, timeouts, and circuit breaker:\n\n```python\nagent = ConversimpleAgent(\n    api_key=\"your-api-key\",\n    customer_id=\"your-customer-id\",\n    platform_url=\"wss://platform.conversimple.com/sdk/websocket\",\n\n    # Retry configuration\n    max_reconnect_attempts=None,      # None = infinite retries (default)\n                                      # Set to number for limited retries\n    reconnect_backoff=2.0,            # Exponential backoff multiplier (default: 2.0)\n    max_backoff=300.0,                # Max wait between retries: 5 minutes (default)\n    total_retry_duration=None,        # None = no time limit (default)\n                                      # Set to seconds for max retry duration\n\n    # Circuit breaker (stops retrying on permanent failures)\n    enable_circuit_breaker=True       # Default: True (recommended)\n)\n```\n\n### Configuration Examples\n\n#### Production: Infinite Retry with Circuit Breaker\n```python\n# Recommended for production - never gives up on transient failures\nagent = ConversimpleAgent(\n    api_key=os.getenv(\"CONVERSIMPLE_API_KEY\"),\n    platform_url=\"wss://platform.conversimple.com/sdk/websocket\",\n    max_reconnect_attempts=None,      # Infinite retries\n    enable_circuit_breaker=True       # Stop on auth failures\n)\n```\n\n#### Development: Fast Failure\n```python\n# Good for testing - fails quickly\nagent = ConversimpleAgent(\n    api_key=\"test-key\",\n    platform_url=\"ws://localhost:4000/sdk/websocket\",\n    max_reconnect_attempts=5,         # Only 5 attempts\n    reconnect_backoff=1.5,            # Faster backoff\n    max_backoff=30,                   # Max 30 seconds between retries\n    total_retry_duration=120          # Give up after 2 minutes\n)\n```\n\n#### Aggressive Retry (Long-Running Services)\n```python\n# For services that must stay connected\nagent = ConversimpleAgent(\n    api_key=os.getenv(\"CONVERSIMPLE_API_KEY\"),\n    max_reconnect_attempts=None,      # Never give up\n    max_backoff=600,                  # Max 10 minutes between retries\n    enable_circuit_breaker=True       # Still stop on permanent failures\n)\n```\n\n#### Debugging: Disable Circuit Breaker\n```python\n# WARNING: Only for debugging - will retry even on auth failures\nagent = ConversimpleAgent(\n    api_key=\"invalid-key\",\n    max_reconnect_attempts=10,\n    enable_circuit_breaker=False      # Retry all errors (not recommended)\n)\n```\n\n## Examples\n\nThe SDK includes several example implementations:\n\n### Simple Weather Agent\n```bash\npython examples/simple_agent.py\n```\n\nA basic agent that provides weather information, demonstrating:\n- Tool registration with `@tool` decorator\n- Conversation lifecycle callbacks\n- Basic agent structure\n\n### Customer Service Agent  \n```bash\npython examples/customer_service.py\n```\n\nAdvanced customer service agent with multiple tools:\n- Customer lookup and account management\n- Support ticket creation\n- Email notifications\n- Refund processing\n- Async tool execution\n\n### Multi-Step Booking Agent\n```bash  \npython examples/booking_agent.py\n```\n\nComplex booking workflow demonstrating:\n- Multi-turn conversation state management\n- Booking creation, confirmation, and cancellation\n- Business rule validation\n- Transaction-like processes\n\n## API Reference\n\n### ConversimpleAgent\n\nMain agent class for platform integration.\n\n#### Constructor\n\n```python\nConversimpleAgent(\n    api_key: str,\n    customer_id: Optional[str] = None,\n    platform_url: str = \"ws://localhost:4000/sdk/websocket\",\n    max_reconnect_attempts: Optional[int] = None,\n    reconnect_backoff: float = 2.0,\n    max_backoff: float = 300.0,\n    total_retry_duration: Optional[float] = None,\n    enable_circuit_breaker: bool = True\n)\n```\n\n**Parameters:**\n- `api_key` (str): Customer API key for authentication\n- `customer_id` (str, optional): Customer identifier (derived from API key if not provided)\n- `platform_url` (str): WebSocket URL for platform connection\n- `max_reconnect_attempts` (int, optional): Maximum reconnection attempts (None = infinite)\n- `reconnect_backoff` (float): Exponential backoff multiplier (default: 2.0)\n- `max_backoff` (float): Maximum backoff time in seconds (default: 300s)\n- `total_retry_duration` (float, optional): Maximum total retry time (None = no limit)\n- `enable_circuit_breaker` (bool): Enable circuit breaker for permanent failures (default: True)\n\n#### Methods\n\n- `async start(conversation_id=None)` - Start agent and connect to platform\n- `async stop()` - Stop agent and disconnect\n- `on_conversation_started(conversation_id)` - Conversation started callback\n- `on_conversation_ended(conversation_id)` - Conversation ended callback\n- `on_tool_called(tool_call)` - Tool execution callback\n- `on_tool_completed(call_id, result)` - Tool completion callback\n- `on_error(error_type, message, details)` - Error handling callback\n\n### Tool Decorators\n\n#### @tool(description)\nRegister synchronous tool function.\n\n```python\n@tool(\"Description of what this tool does\")\ndef my_tool(self, param1: str, param2: int = 10) -> dict:\n    return {\"result\": \"success\"}\n```\n\n#### @tool_async(description)  \nRegister asynchronous tool function.\n\n```python\n@tool_async(\"Description of async tool\")\nasync def my_async_tool(self, param: str) -> dict:\n    await asyncio.sleep(0.1)  # Async operation\n    return {\"result\": \"success\"}\n```\n\n### Type Hints\n\nThe SDK automatically generates JSON schemas from Python type hints:\n\n- `str` \u2192 `\"type\": \"string\"`\n- `int` \u2192 `\"type\": \"integer\"`  \n- `float` \u2192 `\"type\": \"number\"`\n- `bool` \u2192 `\"type\": \"boolean\"`\n- `list` \u2192 `\"type\": \"array\"`\n- `dict` \u2192 `\"type\": \"object\"`\n- `Optional[T]` \u2192 Same as T (nullable)\n\n## Protocol Details\n\n### WebSocket Messages\n\nThe SDK communicates with the platform using these message types:\n\n#### Outgoing (SDK \u2192 Platform)\n- `register_conversation_tools` - Register available tools\n- `tool_call_response` - Tool execution results\n- `tool_call_error` - Tool execution failures  \n- `heartbeat` - Connection keepalive\n\n#### Incoming (Platform \u2192 SDK)\n- `tool_call_request` - Tool execution requests\n- `conversation_lifecycle` - Conversation started/ended\n- `config_update` - Configuration updates\n- `analytics_update` - Usage analytics\n\n### Message Format\n\nTool registration:\n```json\n{\n  \"conversation_id\": \"conv_123\",\n  \"tools\": [\n    {\n      \"name\": \"get_weather\",\n      \"description\": \"Get weather for location\", \n      \"parameters\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"location\": {\"type\": \"string\"}\n        },\n        \"required\": [\"location\"]\n      }\n    }\n  ]\n}\n```\n\nTool execution:\n```json\n{\n  \"call_id\": \"call_abc123\",\n  \"result\": {\"temperature\": 22, \"condition\": \"sunny\"}\n}\n```\n\n## Error Handling\n\nThe SDK provides comprehensive error handling with intelligent retry logic:\n\n### Connection Errors\n\n#### Automatic Reconnection\n- **Exponential backoff** with jitter to prevent thundering herd\n- **Infinite retries** by default for transient failures (network issues, server restarts)\n- **Circuit breaker** stops retrying on permanent failures (invalid credentials, suspended accounts)\n\n#### Circuit Breaker Behavior\n\nThe circuit breaker detects **permanent errors** and stops retrying immediately:\n\n**Permanent Errors (No Retry):**\n- Authentication failures (invalid API key, expired credentials)\n- Authorization errors (customer suspended, account inactive)\n- HTTP 401, 403, 400 status codes\n- Missing required credentials\n\n**Transient Errors (Auto Retry):**\n- Network timeouts and connection refused\n- Server temporarily unavailable\n- WebSocket connection drops\n- Database connection issues\n\n#### Connection Event Handling\n\n```python\nclass MyAgent(ConversimpleAgent):\n    def on_error(self, error_type: str, message: str, details: dict):\n        if error_type == \"AUTH_FAILED\":\n            # Circuit breaker opened - permanent failure\n            print(f\"\ud83d\udeab Authentication failed: {message}\")\n            print(\"\ud83d\udd11 Check your API key and try again\")\n            # Do NOT retry - fix credentials first\n\n        elif error_type == \"CUSTOMER_SUSPENDED\":\n            # Circuit breaker opened - account issue\n            print(f\"\u26d4 Account suspended: {message}\")\n            print(\"\ud83d\udce7 Contact support to reactivate account\")\n\n        else:\n            # Transient error - will auto-retry\n            print(f\"\u26a0\ufe0f  Temporary error: {message}\")\n            print(\"\ud83d\udd04 Will reconnect automatically\")\n```\n\n#### Retry Behavior Examples\n\n```python\n# Default: Infinite retry with circuit breaker (recommended)\nagent = ConversimpleAgent(api_key=\"valid-key\")\n# Network issue \u2192 Retries: 2s, 4s, 8s, 16s, ... up to 300s, forever\n# Invalid key \u2192 Circuit breaker opens immediately, no retries\n\n# Limited retries for testing\nagent = ConversimpleAgent(\n    api_key=\"test-key\",\n    max_reconnect_attempts=5,\n    total_retry_duration=120  # Give up after 2 minutes\n)\n# Network issue \u2192 Retries: 2s, 4s, 8s, 16s, 32s, then gives up\n# Invalid key \u2192 Circuit breaker opens immediately\n\n# Aggressive retry for critical services\nagent = ConversimpleAgent(\n    api_key=\"prod-key\",\n    max_backoff=600,  # Max 10 minutes between retries\n    enable_circuit_breaker=True\n)\n# Network issue \u2192 Retries forever, up to 10 min between attempts\n# Invalid key \u2192 Still stops immediately (circuit breaker)\n```\n\n### Tool Execution Errors\n- Automatic error reporting to platform\n- Exception wrapping and formatting\n- Timeout handling (configurable per tool call)\n\n### Logging\n\n```python\nimport logging\n\n# Configure SDK logging\nlogging.basicConfig(\n    level=logging.INFO,\n    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n)\n\n# SDK logger\nlogger = logging.getLogger(\"conversimple\")\nlogger.setLevel(logging.DEBUG)  # Detailed connection logs\n\n# Connection-specific logging\nconnection_logger = logging.getLogger(\"conversimple.connection\")\nconnection_logger.setLevel(logging.INFO)  # Less verbose\n```\n\n**Log Levels:**\n- `DEBUG`: Detailed connection events, retry attempts, backoff calculations\n- `INFO`: Connection status, tool calls, conversation events\n- `WARNING`: Connection warnings, approaching timeouts\n- `ERROR`: Connection failures, tool errors, permanent failures\n\n## Development\n\n### Setup Development Environment\n\n```bash\ngit clone https://github.com/conversimple/conversimple-sdk\ncd conversimple-sdk\n\n# Create virtual environment  \npython -m venv venv\nsource venv/bin/activate  # On Windows: venv\\Scripts\\activate\n\n# Install dependencies\npip install -r requirements.txt -r requirements-dev.txt\n\n# Install in editable mode\npip install -e .\n```\n\n### Running Tests\n\n```bash\npytest tests/\n```\n\n### Code Formatting\n\n```bash\nblack conversimple/\nflake8 conversimple/\nmypy conversimple/\n```\n\n## License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## Support\n\n- **Documentation**: https://docs.conversimple.com/sdk\n- **GitHub Issues**: https://github.com/conversimple/conversimple-sdk/issues  \n- **Email Support**: support@conversimple.com\n- **Community**: https://community.conversimple.com\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Python SDK for Conversimple Conversational AI Platform",
    "version": "0.2.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/conversimple/conversimple-sdk/issues",
        "Documentation": "https://docs.conversimple.com/sdk",
        "Homepage": "https://github.com/conversimple/conversimple-sdk",
        "Platform": "https://platform.conversimple.com"
    },
    "split_keywords": [
        "conversational ai",
        " voice ai",
        " chatbot",
        " websocket",
        " sdk",
        " speech to text",
        " text to speech"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "20a342331cd52e1145bca90d2f98e3edd0944d3814852696420a8a192bcb731a",
                "md5": "97813cac6e6491d65281fd2100b82a71",
                "sha256": "ed24b7098a65efcf2ffa385e159426d515e19e5adc1bd7f41c83265d16b3d830"
            },
            "downloads": -1,
            "filename": "conversimple_sdk-0.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "97813cac6e6491d65281fd2100b82a71",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 21605,
            "upload_time": "2025-10-11T22:31:49",
            "upload_time_iso_8601": "2025-10-11T22:31:49.159045Z",
            "url": "https://files.pythonhosted.org/packages/20/a3/42331cd52e1145bca90d2f98e3edd0944d3814852696420a8a192bcb731a/conversimple_sdk-0.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "e0d7016998c5dd165e026e1bddf0b57a2e68b323a92ed3d6f7c33fa825eadc68",
                "md5": "4bbeab84e7a4239561439dd8a1b4a419",
                "sha256": "6ae3c39a40d43a77698dae47094fbf091f5f94df6be564888386f567b666d2b4"
            },
            "downloads": -1,
            "filename": "conversimple_sdk-0.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "4bbeab84e7a4239561439dd8a1b4a419",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 23739,
            "upload_time": "2025-10-11T22:31:50",
            "upload_time_iso_8601": "2025-10-11T22:31:50.529161Z",
            "url": "https://files.pythonhosted.org/packages/e0/d7/016998c5dd165e026e1bddf0b57a2e68b323a92ed3d6f7c33fa825eadc68/conversimple_sdk-0.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-11 22:31:50",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "conversimple",
    "github_project": "conversimple-sdk",
    "github_not_found": true,
    "lcname": "conversimple-sdk"
}
        
Elapsed time: 2.58956s