# ChatRoutes Python SDK
[](https://pypi.org/project/chatroutes/)
[](https://pypi.org/project/chatroutes/)
[](https://colab.research.google.com/github/chatroutes/chatroutes-python-sdk/blob/main/chatroutes_quickstart.ipynb)
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.
## 🚀 Try It Now!
**Want to try ChatRoutes immediately?** Click the badge below to open an interactive notebook in Google Colab:
[](https://colab.research.google.com/github/chatroutes/chatroutes-python-sdk/blob/main/chatroutes_quickstart.ipynb)
No installation required - just run the cells and start experimenting!
## Installation
```bash
pip install chatroutes
```
## Getting Started
### 1. Get Your API Key
**IMPORTANT:** Before you can use ChatRoutes, you must obtain an API key:
1. **Visit** [chatroutes.com](https://chatroutes.com)
2. **Sign up** for a **free account**
3. **Go to Dashboard** → Navigate to the **API section**
4. **Generate** your API key
5. **Copy** and save your API key securely
### 2. Quick Start
```python
from chatroutes import ChatRoutes
client = ChatRoutes(api_key="your-api-key")
conversation = client.conversations.create({
'title': 'My First Conversation',
'model': 'gpt-5' # or 'claude-opus-4-1', 'claude-sonnet-4-5', etc.
})
response = client.messages.send(
conversation['id'],
{
'content': 'Hello, how are you?',
'model': 'gpt-5'
}
)
print(response['message']['content'])
```
## Supported Models
ChatRoutes currently supports the following AI models:
**OpenAI:**
- **`gpt-5`** (default) - OpenAI's GPT-5
**Anthropic Claude 4:**
- **`claude-opus-4-1`** - Claude Opus 4.1 (most capable)
- **`claude-opus-4`** - Claude Opus 4
- **`claude-opus-4-0`** - Claude Opus 4.0
- **`claude-sonnet-4-5`** - Claude Sonnet 4.5 (best for coding)
- **`claude-sonnet-4-0`** - Claude Sonnet 4.0
**Anthropic Claude 3:**
- **`claude-3-7-sonnet-latest`** - Claude 3.7 Sonnet (latest)
- **`claude-3-5-haiku-latest`** - Claude 3.5 Haiku (fastest)
**Important**: Use these exact model names. Other model names (e.g., `gpt-4o`, `gpt-4o-mini`, `claude-sonnet-4`) are not supported and will result in an error.
## 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
- **Checkpoint Management**: Save and restore conversation context at specific points
- **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
```python
conversation = client.conversations.create({
'title': 'Product Discussion',
'model': 'gpt-5'
})
```
### Sending Messages
```python
response = client.messages.send(
conversation_id='conv_123',
data={
'content': 'What are the key features?',
'model': 'gpt-5',
'temperature': 0.7
}
)
print(response['message']['content']) # AI response
print(f"Tokens used: {response['usage']['totalTokens']}")
```
### Streaming Responses
```python
def on_chunk(chunk):
if chunk.get('type') == 'content' and chunk.get('content'):
print(chunk['content'], end='', flush=True)
def on_complete(message):
print(f"\n\nMessage ID: {message['id']}")
client.messages.stream(
conversation_id='conv_123',
data={'content': 'Tell me a story'},
on_chunk=on_chunk,
on_complete=on_complete
)
```
### Working with Branches
```python
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
```python
result = client.conversations.list({
'page': 1,
'limit': 10,
'filter': 'all'
})
for conv in result['data']:
print(f"{conv['title']} - {conv['createdAt']}")
```
### Managing Checkpoints
Checkpoints allow you to save conversation context at specific points and manage long conversations efficiently:
```python
branches = client.branches.list(conversation_id='conv_123')
main_branch = next(b for b in branches if b['isMain'])
checkpoint = client.checkpoints.create(
conversation_id='conv_123',
branch_id=main_branch['id'],
anchor_message_id='msg_456'
)
print(f"Checkpoint created: {checkpoint['id']}")
print(f"Summary: {checkpoint['summary']}")
print(f"Token count: {checkpoint['token_count']}")
checkpoints = client.checkpoints.list('conv_123')
for cp in checkpoints:
print(f"{cp['id']}: {cp['summary']}")
response = client.messages.send(
conversation_id='conv_123',
data={'content': 'Continue the conversation'}
)
metadata = response['message'].get('metadata', {})
if metadata.get('checkpoint_used'):
print(f"Checkpoint was used for this response")
print(f"Context messages: {metadata.get('context_message_count')}")
```
## Error Handling
The SDK provides specific exception types for different error scenarios:
```python
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
```python
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`
### Checkpoints Resource
- `list(conversation_id: str, branch_id: Optional[str] = None) -> List[Checkpoint]`
- `create(conversation_id: str, branch_id: str, anchor_message_id: str) -> Checkpoint`
- `delete(checkpoint_id: str) -> None`
- `recreate(checkpoint_id: str) -> Checkpoint`
## Type Definitions
The SDK includes comprehensive type definitions using TypedDict:
- `Conversation`
- `Message`
- `MessageMetadata` (includes checkpoint-related fields)
- `Branch`
- `Checkpoint`
- `CreateConversationRequest`
- `SendMessageRequest`
- `SendMessageResponse`
- `CreateBranchRequest`
- `ForkConversationRequest`
- `CheckpointCreateRequest`
- `CheckpointListResponse`
- `ConversationTree`
- `TreeNode`
- `ListConversationsParams`
- `PaginatedResponse`
- `StreamChunk`
## Development
### Setup
```bash
git clone https://github.com/chatroutes/chatroutes-python-sdk.git
cd chatroutes-python-sdk
pip install -e ".[dev]"
```
### Running Tests
```bash
pytest
```
### Type Checking
```bash
mypy chatroutes
```
### Code Formatting
```bash
black chatroutes
```
## License
MIT License - see LICENSE file for details
## Support
- Documentation: https://docs.chatroutes.com
- API Reference: https://api.chatroutes.com/docs
- Email: support@chatroutes.com
- GitHub Issues: https://github.com/chatroutes/chatroutes-python-sdk/issues
Raw data
{
"_id": null,
"home_page": "https://github.com/chatroutes/chatroutes-python-sdk",
"name": "chatroutes",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "chatroutes, ai, chat, conversation, branching, multi-model, gpt, claude, api, sdk",
"author": "ChatRoutes",
"author_email": "ChatRoutes <support@chatroutes.com>",
"download_url": "https://files.pythonhosted.org/packages/4e/59/48a9dcc6c0cce0385a367fd395b57f42237441aff9a2afe840917816e267/chatroutes-0.2.0.tar.gz",
"platform": null,
"description": "# ChatRoutes Python SDK\r\n\r\n[](https://pypi.org/project/chatroutes/)\r\n[](https://pypi.org/project/chatroutes/)\r\n[](https://colab.research.google.com/github/chatroutes/chatroutes-python-sdk/blob/main/chatroutes_quickstart.ipynb)\r\n\r\nOfficial Python SDK for the ChatRoutes API - A powerful conversation management platform with advanced branching capabilities.\r\n\r\n> **\u26a0\ufe0f Beta Release**: ChatRoutes is currently in beta. The API may change without maintaining backward compatibility. Please use with caution in production environments.\r\n\r\n## \ud83d\ude80 Try It Now!\r\n\r\n**Want to try ChatRoutes immediately?** Click the badge below to open an interactive notebook in Google Colab:\r\n\r\n[](https://colab.research.google.com/github/chatroutes/chatroutes-python-sdk/blob/main/chatroutes_quickstart.ipynb)\r\n\r\nNo installation required - just run the cells and start experimenting!\r\n\r\n## Installation\r\n\r\n```bash\r\npip install chatroutes\r\n```\r\n\r\n## Getting Started\r\n\r\n### 1. Get Your API Key\r\n\r\n**IMPORTANT:** Before you can use ChatRoutes, you must obtain an API key:\r\n\r\n1. **Visit** [chatroutes.com](https://chatroutes.com)\r\n2. **Sign up** for a **free account**\r\n3. **Go to Dashboard** \u2192 Navigate to the **API section**\r\n4. **Generate** your API key\r\n5. **Copy** and save your API key securely\r\n\r\n### 2. Quick Start\r\n\r\n```python\r\nfrom chatroutes import ChatRoutes\r\n\r\nclient = ChatRoutes(api_key=\"your-api-key\")\r\n\r\nconversation = client.conversations.create({\r\n 'title': 'My First Conversation',\r\n 'model': 'gpt-5' # or 'claude-opus-4-1', 'claude-sonnet-4-5', etc.\r\n})\r\n\r\nresponse = client.messages.send(\r\n conversation['id'],\r\n {\r\n 'content': 'Hello, how are you?',\r\n 'model': 'gpt-5'\r\n }\r\n)\r\n\r\nprint(response['message']['content'])\r\n```\r\n\r\n## Supported Models\r\n\r\nChatRoutes currently supports the following AI models:\r\n\r\n**OpenAI:**\r\n- **`gpt-5`** (default) - OpenAI's GPT-5\r\n\r\n**Anthropic Claude 4:**\r\n- **`claude-opus-4-1`** - Claude Opus 4.1 (most capable)\r\n- **`claude-opus-4`** - Claude Opus 4\r\n- **`claude-opus-4-0`** - Claude Opus 4.0\r\n- **`claude-sonnet-4-5`** - Claude Sonnet 4.5 (best for coding)\r\n- **`claude-sonnet-4-0`** - Claude Sonnet 4.0\r\n\r\n**Anthropic Claude 3:**\r\n- **`claude-3-7-sonnet-latest`** - Claude 3.7 Sonnet (latest)\r\n- **`claude-3-5-haiku-latest`** - Claude 3.5 Haiku (fastest)\r\n\r\n**Important**: Use these exact model names. Other model names (e.g., `gpt-4o`, `gpt-4o-mini`, `claude-sonnet-4`) are not supported and will result in an error.\r\n\r\n## Features\r\n\r\n- **Conversation Management**: Create, list, update, and delete conversations\r\n- **Message Handling**: Send messages with support for streaming responses\r\n- **Branch Operations**: Create and manage conversation branches for exploring alternatives\r\n- **Checkpoint Management**: Save and restore conversation context at specific points\r\n- **Type Safety**: Full type hints using TypedDict for better IDE support\r\n- **Error Handling**: Comprehensive exception hierarchy for different error scenarios\r\n- **Retry Logic**: Built-in exponential backoff retry mechanism\r\n\r\n## Usage Examples\r\n\r\n### Creating a Conversation\r\n\r\n```python\r\nconversation = client.conversations.create({\r\n 'title': 'Product Discussion',\r\n 'model': 'gpt-5'\r\n})\r\n```\r\n\r\n### Sending Messages\r\n\r\n```python\r\nresponse = client.messages.send(\r\n conversation_id='conv_123',\r\n data={\r\n 'content': 'What are the key features?',\r\n 'model': 'gpt-5',\r\n 'temperature': 0.7\r\n }\r\n)\r\n\r\nprint(response['message']['content']) # AI response\r\nprint(f\"Tokens used: {response['usage']['totalTokens']}\")\r\n```\r\n\r\n### Streaming Responses\r\n\r\n```python\r\ndef on_chunk(chunk):\r\n if chunk.get('type') == 'content' and chunk.get('content'):\r\n print(chunk['content'], end='', flush=True)\r\n\r\ndef on_complete(message):\r\n print(f\"\\n\\nMessage ID: {message['id']}\")\r\n\r\nclient.messages.stream(\r\n conversation_id='conv_123',\r\n data={'content': 'Tell me a story'},\r\n on_chunk=on_chunk,\r\n on_complete=on_complete\r\n)\r\n```\r\n\r\n### Working with Branches\r\n\r\n```python\r\nbranch = client.branches.create(\r\n conversation_id='conv_123',\r\n data={\r\n 'title': 'Alternative Response',\r\n 'contextMode': 'FULL'\r\n }\r\n)\r\n\r\nfork = client.branches.fork(\r\n conversation_id='conv_123',\r\n data={\r\n 'forkPointMessageId': 'msg_456',\r\n 'title': 'Exploring Different Approach'\r\n }\r\n)\r\n```\r\n\r\n### Listing Conversations\r\n\r\n```python\r\nresult = client.conversations.list({\r\n 'page': 1,\r\n 'limit': 10,\r\n 'filter': 'all'\r\n})\r\n\r\nfor conv in result['data']:\r\n print(f\"{conv['title']} - {conv['createdAt']}\")\r\n```\r\n\r\n### Managing Checkpoints\r\n\r\nCheckpoints allow you to save conversation context at specific points and manage long conversations efficiently:\r\n\r\n```python\r\nbranches = client.branches.list(conversation_id='conv_123')\r\nmain_branch = next(b for b in branches if b['isMain'])\r\n\r\ncheckpoint = client.checkpoints.create(\r\n conversation_id='conv_123',\r\n branch_id=main_branch['id'],\r\n anchor_message_id='msg_456'\r\n)\r\n\r\nprint(f\"Checkpoint created: {checkpoint['id']}\")\r\nprint(f\"Summary: {checkpoint['summary']}\")\r\nprint(f\"Token count: {checkpoint['token_count']}\")\r\n\r\ncheckpoints = client.checkpoints.list('conv_123')\r\nfor cp in checkpoints:\r\n print(f\"{cp['id']}: {cp['summary']}\")\r\n\r\nresponse = client.messages.send(\r\n conversation_id='conv_123',\r\n data={'content': 'Continue the conversation'}\r\n)\r\n\r\nmetadata = response['message'].get('metadata', {})\r\nif metadata.get('checkpoint_used'):\r\n print(f\"Checkpoint was used for this response\")\r\n print(f\"Context messages: {metadata.get('context_message_count')}\")\r\n```\r\n\r\n## Error Handling\r\n\r\nThe SDK provides specific exception types for different error scenarios:\r\n\r\n```python\r\nfrom chatroutes import (\r\n ChatRoutesError,\r\n AuthenticationError,\r\n RateLimitError,\r\n ValidationError,\r\n NotFoundError,\r\n ServerError\r\n)\r\n\r\ntry:\r\n conversation = client.conversations.get('conv_123')\r\nexcept AuthenticationError:\r\n print(\"Invalid API key\")\r\nexcept NotFoundError:\r\n print(\"Conversation not found\")\r\nexcept RateLimitError as e:\r\n print(f\"Rate limited. Retry after {e.retry_after} seconds\")\r\nexcept ChatRoutesError as e:\r\n print(f\"Error: {e.message}\")\r\n```\r\n\r\n## API Reference\r\n\r\n### ChatRoutes Client\r\n\r\n```python\r\nclient = ChatRoutes(\r\n api_key=\"your-api-key\",\r\n base_url=\"https://api.chatroutes.com/api/v1\", # optional\r\n timeout=30, # optional, in seconds\r\n retry_attempts=3, # optional\r\n retry_delay=1.0 # optional, in seconds\r\n)\r\n```\r\n\r\n### Conversations Resource\r\n\r\n- `create(data: CreateConversationRequest) -> Conversation`\r\n- `list(params: ListConversationsParams) -> PaginatedResponse`\r\n- `get(conversation_id: str) -> Conversation`\r\n- `update(conversation_id: str, data: dict) -> Conversation`\r\n- `delete(conversation_id: str) -> None`\r\n- `get_tree(conversation_id: str) -> ConversationTree`\r\n\r\n### Messages Resource\r\n\r\n- `send(conversation_id: str, data: SendMessageRequest) -> SendMessageResponse`\r\n- `stream(conversation_id: str, data: SendMessageRequest, on_chunk: Callable, on_complete: Callable) -> None`\r\n- `list(conversation_id: str, branch_id: str) -> List[Message]`\r\n- `update(message_id: str, content: str) -> Message`\r\n- `delete(message_id: str) -> None`\r\n\r\n### Branches Resource\r\n\r\n- `list(conversation_id: str) -> List[Branch]`\r\n- `create(conversation_id: str, data: CreateBranchRequest) -> Branch`\r\n- `fork(conversation_id: str, data: ForkConversationRequest) -> Branch`\r\n- `update(conversation_id: str, branch_id: str, data: dict) -> Branch`\r\n- `delete(conversation_id: str, branch_id: str) -> None`\r\n- `get_messages(conversation_id: str, branch_id: str) -> List[Message]`\r\n- `merge(conversation_id: str, branch_id: str) -> Branch`\r\n\r\n### Checkpoints Resource\r\n\r\n- `list(conversation_id: str, branch_id: Optional[str] = None) -> List[Checkpoint]`\r\n- `create(conversation_id: str, branch_id: str, anchor_message_id: str) -> Checkpoint`\r\n- `delete(checkpoint_id: str) -> None`\r\n- `recreate(checkpoint_id: str) -> Checkpoint`\r\n\r\n## Type Definitions\r\n\r\nThe SDK includes comprehensive type definitions using TypedDict:\r\n\r\n- `Conversation`\r\n- `Message`\r\n- `MessageMetadata` (includes checkpoint-related fields)\r\n- `Branch`\r\n- `Checkpoint`\r\n- `CreateConversationRequest`\r\n- `SendMessageRequest`\r\n- `SendMessageResponse`\r\n- `CreateBranchRequest`\r\n- `ForkConversationRequest`\r\n- `CheckpointCreateRequest`\r\n- `CheckpointListResponse`\r\n- `ConversationTree`\r\n- `TreeNode`\r\n- `ListConversationsParams`\r\n- `PaginatedResponse`\r\n- `StreamChunk`\r\n\r\n## Development\r\n\r\n### Setup\r\n\r\n```bash\r\ngit clone https://github.com/chatroutes/chatroutes-python-sdk.git\r\ncd chatroutes-python-sdk\r\npip install -e \".[dev]\"\r\n```\r\n\r\n### Running Tests\r\n\r\n```bash\r\npytest\r\n```\r\n\r\n### Type Checking\r\n\r\n```bash\r\nmypy chatroutes\r\n```\r\n\r\n### Code Formatting\r\n\r\n```bash\r\nblack chatroutes\r\n```\r\n\r\n## License\r\n\r\nMIT License - see LICENSE file for details\r\n\r\n## Support\r\n\r\n- Documentation: https://docs.chatroutes.com\r\n- API Reference: https://api.chatroutes.com/docs\r\n- Email: support@chatroutes.com\r\n- GitHub Issues: https://github.com/chatroutes/chatroutes-python-sdk/issues\r\n",
"bugtrack_url": null,
"license": null,
"summary": "Official Python SDK for ChatRoutes API - Conversation branching and multi-model AI chat",
"version": "0.2.0",
"project_urls": {
"Bug Tracker": "https://github.com/chatroutes/chatroutes-python-sdk/issues",
"Documentation": "https://docs.chatroutes.com",
"Homepage": "https://chatroutes.com",
"Repository": "https://github.com/chatroutes/chatroutes-python-sdk"
},
"split_keywords": [
"chatroutes",
" ai",
" chat",
" conversation",
" branching",
" multi-model",
" gpt",
" claude",
" api",
" sdk"
],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "ef7f39b57a75ccb3047975a20ef1df76b9155b03f76d9313326be2dce27d7ba0",
"md5": "1315b69fced5805ee34444f30fb110d8",
"sha256": "7debe2059a59c494f85ab0f55d3b0261833674e55181778413dbddcfa1efe735"
},
"downloads": -1,
"filename": "chatroutes-0.2.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "1315b69fced5805ee34444f30fb110d8",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 13984,
"upload_time": "2025-10-11T03:34:40",
"upload_time_iso_8601": "2025-10-11T03:34:40.863443Z",
"url": "https://files.pythonhosted.org/packages/ef/7f/39b57a75ccb3047975a20ef1df76b9155b03f76d9313326be2dce27d7ba0/chatroutes-0.2.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "4e5948a9dcc6c0cce0385a367fd395b57f42237441aff9a2afe840917816e267",
"md5": "4451180410d9c34904c2a642ca8a1591",
"sha256": "39974c9a21e64594c264b6e3c6cb0dc6e9d110b1ae323009f40102a9b5dc6e79"
},
"downloads": -1,
"filename": "chatroutes-0.2.0.tar.gz",
"has_sig": false,
"md5_digest": "4451180410d9c34904c2a642ca8a1591",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 14371,
"upload_time": "2025-10-11T03:34:42",
"upload_time_iso_8601": "2025-10-11T03:34:42.008917Z",
"url": "https://files.pythonhosted.org/packages/4e/59/48a9dcc6c0cce0385a367fd395b57f42237441aff9a2afe840917816e267/chatroutes-0.2.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-10-11 03:34:42",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "chatroutes",
"github_project": "chatroutes-python-sdk",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"requirements": [
{
"name": "requests",
"specs": [
[
">=",
"2.31.0"
]
]
}
],
"lcname": "chatroutes"
}