Skip to main content

Official Python SDK for ChatRoutes API - Conversation branching and multi-model AI chat

Project description

ChatRoutes Python SDK

Official Python SDK for the ChatRoutes API - A powerful conversation management platform with advanced branching capabilities.

⚠️ Beta Release: ChatRoutes is currently in beta. The API may change without maintaining backward compatibility. Please use with caution in production environments.

Installation

pip install chatroutes

Getting Started

1. Get Your API Key

First, you need to obtain an API key:

  1. Visit chatroutes.com
  2. Sign up for a free account
  3. Navigate to your account settings
  4. Generate your API key

2. Quick Start

from chatroutes import ChatRoutes

client = ChatRoutes(api_key="your-api-key")

conversation = client.conversations.create({
    'title': 'My First Conversation',
    'model': 'gpt-4'
})

response = client.messages.send(
    conversation['id'],
    {
        'content': 'Hello, how are you?',
        'model': 'gpt-4'
    }
)

print(response['assistantMessage']['content'])

Features

  • Conversation Management: Create, list, update, and delete conversations
  • Message Handling: Send messages with support for streaming responses
  • Branch Operations: Create and manage conversation branches for exploring alternatives
  • Type Safety: Full type hints using TypedDict for better IDE support
  • Error Handling: Comprehensive exception hierarchy for different error scenarios
  • Retry Logic: Built-in exponential backoff retry mechanism

Usage Examples

Creating a Conversation

conversation = client.conversations.create({
    'title': 'Product Discussion',
    'model': 'gpt-4'
})

Sending Messages

response = client.messages.send(
    conversation_id='conv_123',
    data={
        'content': 'What are the key features?',
        'model': 'gpt-4',
        'temperature': 0.7
    }
)

Streaming Responses

def on_chunk(chunk):
    if chunk['choices'][0]['delta'].get('content'):
        print(chunk['choices'][0]['delta']['content'], end='', flush=True)

client.messages.stream(
    conversation_id='conv_123',
    data={'content': 'Tell me a story'},
    on_chunk=on_chunk
)

Working with Branches

branch = client.branches.create(
    conversation_id='conv_123',
    data={
        'title': 'Alternative Response',
        'contextMode': 'FULL'
    }
)

fork = client.branches.fork(
    conversation_id='conv_123',
    data={
        'forkPointMessageId': 'msg_456',
        'title': 'Exploring Different Approach'
    }
)

Listing Conversations

result = client.conversations.list({
    'page': 1,
    'limit': 10,
    'filter': 'all'
})

for conv in result['data']:
    print(f"{conv['title']} - {conv['createdAt']}")

Error Handling

The SDK provides specific exception types for different error scenarios:

from chatroutes import (
    ChatRoutesError,
    AuthenticationError,
    RateLimitError,
    ValidationError,
    NotFoundError,
    ServerError
)

try:
    conversation = client.conversations.get('conv_123')
except AuthenticationError:
    print("Invalid API key")
except NotFoundError:
    print("Conversation not found")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ChatRoutesError as e:
    print(f"Error: {e.message}")

API Reference

ChatRoutes Client

client = ChatRoutes(
    api_key="your-api-key",
    base_url="https://api.chatroutes.com/api/v1",  # optional
    timeout=30,  # optional, in seconds
    retry_attempts=3,  # optional
    retry_delay=1.0  # optional, in seconds
)

Conversations Resource

  • create(data: CreateConversationRequest) -> Conversation
  • list(params: ListConversationsParams) -> PaginatedResponse
  • get(conversation_id: str) -> Conversation
  • update(conversation_id: str, data: dict) -> Conversation
  • delete(conversation_id: str) -> None
  • get_tree(conversation_id: str) -> ConversationTree

Messages Resource

  • send(conversation_id: str, data: SendMessageRequest) -> SendMessageResponse
  • stream(conversation_id: str, data: SendMessageRequest, on_chunk: Callable, on_complete: Callable) -> None
  • list(conversation_id: str, branch_id: str) -> List[Message]
  • update(message_id: str, content: str) -> Message
  • delete(message_id: str) -> None

Branches Resource

  • list(conversation_id: str) -> List[Branch]
  • create(conversation_id: str, data: CreateBranchRequest) -> Branch
  • fork(conversation_id: str, data: ForkConversationRequest) -> Branch
  • update(conversation_id: str, branch_id: str, data: dict) -> Branch
  • delete(conversation_id: str, branch_id: str) -> None
  • get_messages(conversation_id: str, branch_id: str) -> List[Message]
  • merge(conversation_id: str, branch_id: str) -> Branch

Type Definitions

The SDK includes comprehensive type definitions using TypedDict:

  • Conversation
  • Message
  • Branch
  • CreateConversationRequest
  • SendMessageRequest
  • SendMessageResponse
  • CreateBranchRequest
  • ForkConversationRequest
  • ConversationTree
  • TreeNode
  • ListConversationsParams
  • PaginatedResponse
  • StreamChunk

Development

Setup

git clone https://github.com/chatroutes/chatroutes-python-sdk.git
cd chatroutes-python-sdk
pip install -e ".[dev]"

Running Tests

pytest

Type Checking

mypy chatroutes

Code Formatting

black chatroutes

License

MIT License - see LICENSE file for details

Support

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chatroutes-0.1.0.tar.gz (12.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chatroutes-0.1.0-py3-none-any.whl (12.0 kB view details)

Uploaded Python 3

File details

Details for the file chatroutes-0.1.0.tar.gz.

File metadata

  • Download URL: chatroutes-0.1.0.tar.gz
  • Upload date:
  • Size: 12.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for chatroutes-0.1.0.tar.gz
Algorithm Hash digest
SHA256 18b83edf5cfed1bb538142943f9f4ff9d98bfe87af74bf2c94711f5ad54b996b
MD5 1bf4ff446807e2055cad7bc65ec1e8c0
BLAKE2b-256 a873472db47da0106631d68a98fe082b25caa5c9c43d6de5e5e20d696467168a

See more details on using hashes here.

File details

Details for the file chatroutes-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: chatroutes-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 12.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.0

File hashes

Hashes for chatroutes-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e71aedc5af3fa2f9688ad55a7acf939b3009a1918e65455ebfdcfcea540a8038
MD5 3f437417749410d34e8cb891ab6db19e
BLAKE2b-256 d15188d9b746d4580575b6460e19e15a66903d25d418aa9dc8712e7f4c0a3ca6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page