Code Examples
Complete, production-ready code examples in Python, JavaScript, and cURL.
Python Examples
Basic Conversation
import requests
import time
API_BASE_URL = "<your-api-url>"
API_KEY = "<your-api-key>"
def create_conversation(message, model="claude-v4.6-sonnet"):
"""Create a new conversation"""
url = f"{API_BASE_URL}/conversation"
headers = {
"x-api-key": API_KEY,
"Content-Type": "application/json"
}
payload = {
"message": {
"role": "user",
"content": [
{
"content_type": "text",
"body": message
}
],
"model": model,
"parent_message_id": None
},
"inference_params": {
"temperature": 0.7,
"max_tokens": 2000
}
}
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
return response.json()["conversation_id"]
def get_conversation(conversation_id):
"""Retrieve conversation with adaptive polling"""
url = f"{API_BASE_URL}/conversation/{conversation_id}"
headers = {"x-api-key": API_KEY}
interval = 0.3
max_retries = 5
for attempt in range(max_retries):
time.sleep(interval)
response = requests.get(url, headers=headers)
if response.status_code == 200:
data = response.json()
if "message_map" in data:
return data
elif response.status_code == 404:
interval = min(interval * 1.5, 5.0)
continue
else:
response.raise_for_status()
raise Exception("Max retries exceeded")
# Example usage
conversation_id = create_conversation("Explain quantum computing in detail")
print(f"Created conversation: {conversation_id}")
conversation = get_conversation(conversation_id)
print(f"Response: {conversation['message_map']}")
Multi-Turn Conversation
def send_follow_up(conversation_id, message, parent_message_id,
model="claude-v4.6-sonnet"):
"""Send a follow-up message in existing conversation"""
url = f"{API_BASE_URL}/conversation"
headers = {
"x-api-key": API_KEY,
"Content-Type": "application/json"
}
payload = {
"conversation_id": conversation_id,
"message": {
"role": "user",
"content": [
{
"content_type": "text",
"body": message
}
],
"model": model,
"parent_message_id": parent_message_id
}
}
response = requests.post(url, headers=headers, json=payload)
response.raise_for_status()
return response.json()
# Multi-turn conversation example
conv_id = create_conversation("What is quantum computing?")
conv = get_conversation(conv_id)
# Get the last message ID (the assistant's response)
last_msg_id = conv["last_message_id"]
print(f"Last message ID: {last_msg_id}")
# Send follow-up question
send_follow_up(conv_id, "Can you explain quantum entanglement?", last_msg_id)
conv = get_conversation(conv_id)
# Print all messages
for msg_id, message in conv['message_map'].items():
role = message['role']
content = message['content'][0]['body']
print(f"{role} ({msg_id}): {content[:100]}...")
Complete Chat Session
def chat_session():
"""Complete example of a multi-turn conversation"""
# Start conversation
print("User: What is quantum computing?")
conv_id = create_conversation("What is quantum computing?")
conv = get_conversation(conv_id)
# Get assistant's response
last_msg_id = conv["last_message_id"]
assistant_msg = conv["message_map"][last_msg_id]
print(f"Assistant: {assistant_msg['content'][0]['body'][:200]}...")
# Follow-up 1
print("\nUser: Can you explain quantum entanglement?")
send_follow_up(conv_id, "Can you explain quantum entanglement?", last_msg_id)
conv = get_conversation(conv_id)
last_msg_id = conv["last_message_id"]
assistant_msg = conv["message_map"][last_msg_id]
print(f"Assistant: {assistant_msg['content'][0]['body'][:200]}...")
# Follow-up 2
print("\nUser: How is this used in quantum computers?")
send_follow_up(conv_id, "How is this used in quantum computers?", last_msg_id)
conv = get_conversation(conv_id)
last_msg_id = conv["last_message_id"]
assistant_msg = conv["message_map"][last_msg_id]
print(f"Assistant: {assistant_msg['content'][0]['body'][:200]}...")
# Show conversation structure
print(f"\nTotal messages: {len(conv['message_map'])}")
chat_session()
Token Usage Monitoring
def check_token_usage():
"""Monitor token usage"""
response = requests.get(
f"{API_BASE_URL}/token-usage",
headers={"x-api-key": API_KEY}
)
if response.status_code == 200:
usage = response.json()
remaining = usage["token_limit"] - usage["total_tokens"]
usage_percent = (usage["total_tokens"] / usage["token_limit"]) * 100
print(f"Token Usage: {usage['total_tokens']:,} / {usage['token_limit']:,}")
print(f"Remaining: {remaining:,} tokens ({100-usage_percent:.1f}%)")
if usage_percent > 80:
print("⚠️ Warning: Over 80% of monthly limit used")
return usage
# Check usage before making API calls
usage = check_token_usage()
JavaScript/Node.js Examples
Basic Conversation
const axios = require('axios');
const API_BASE_URL = '<your-api-url>';
const API_KEY = '<your-api-key>';
async function createConversation(message, model = 'claude-v4.6-sonnet') {
const response = await axios.post(
`${API_BASE_URL}/conversation`,
{
message: {
role: 'user',
content: [
{
content_type: 'text',
body: message
}
],
model: model,
parent_message_id: null
},
inference_params: {
temperature: 0.7,
max_tokens: 2000
}
},
{
headers: {
'x-api-key': API_KEY,
'Content-Type': 'application/json'
}
}
);
return response.data.conversation_id;
}
async function getConversation(conversationId) {
let interval = 0.3;
const maxRetries = 5;
for (let attempt = 0; attempt < maxRetries; attempt++) {
await new Promise(resolve => setTimeout(resolve, interval * 1000));
try {
const response = await axios.get(
`${API_BASE_URL}/conversation/${conversationId}`,
{
headers: { 'x-api-key': API_KEY }
}
);
if (response.data.message_map) {
return response.data;
}
} catch (error) {
if (error.response?.status === 404) {
interval = Math.min(interval * 1.5, 5.0);
continue;
}
throw error;
}
}
throw new Error('Max retries exceeded');
}
// Example usage
(async () => {
const conversationId = await createConversation('Explain quantum computing');
console.log(`Created conversation: ${conversationId}`);
const conversation = await getConversation(conversationId);
console.log('Response:', conversation.message_map);
})();
Multi-Turn Conversation
async function sendFollowUp(conversationId, message, parentMessageId,
model = 'claude-v4.6-sonnet') {
const response = await axios.post(
`${API_BASE_URL}/conversation`,
{
conversation_id: conversationId,
message: {
role: 'user',
content: [
{
content_type: 'text',
body: message
}
],
model: model,
parent_message_id: parentMessageId
}
},
{
headers: {
'x-api-key': API_KEY,
'Content-Type': 'application/json'
}
}
);
return response.data;
}
// Multi-turn conversation
(async () => {
const convId = await createConversation('What is quantum computing?');
let conv = await getConversation(convId);
const lastMsgId = conv.last_message_id;
console.log(`Last message: ${lastMsgId}`);
await sendFollowUp(convId, 'Can you explain quantum entanglement?', lastMsgId);
conv = await getConversation(convId);
// Print all messages
for (const [msgId, message] of Object.entries(conv.message_map)) {
console.log(`${message.role} (${msgId}): ${message.content[0].body.substring(0, 100)}...`);
}
})();
Error Handling
async function safeApiCall(conversationId) {
try {
const conversation = await getConversation(conversationId);
return conversation;
} catch (error) {
if (error.response) {
switch (error.response.status) {
case 400:
console.error('Bad request:', error.response.data);
break;
case 401:
console.error('Invalid API key');
break;
case 404:
console.error('Conversation not found');
break;
case 429:
console.error('Token limit exceeded');
break;
case 500:
console.error('Server error:', error.response.data);
break;
default:
console.error('Unknown error:', error.response.status);
}
} else if (error.request) {
console.error('No response received:', error.request);
} else {
console.error('Error:', error.message);
}
throw error;
}
}
cURL Examples
Create Conversation
curl -X POST <your-api-url>/conversation \
-H "x-api-key: <your-api-key>" \
-H "Content-Type: application/json" \
-d '{
"message": {
"role": "user",
"content": [
{
"content_type": "text",
"body": "Explain quantum computing in detail"
}
],
"model": "claude-v4.6-sonnet",
"parent_message_id": null
},
"inference_params": {
"temperature": 0.5,
"max_tokens": 2000
}
}'
Get Conversation
curl -X GET <your-api-url>/conversation/01KPPB65REFEQGM49YS9YWPAP0 \
-H "x-api-key: <your-api-key>"
List All Conversations
curl -X GET <your-api-url>/conversations \
-H "x-api-key: <your-api-key>"
Search Conversations
curl -X GET "<your-api-url>/conversations/search?query=quantum" \
-H "x-api-key: <your-api-key>"
Check Token Usage
curl -X GET <your-api-url>/token-usage \
-H "x-api-key: <your-api-key>"
Health Check
curl -X GET <your-api-url>/health
Advanced Examples
Using Different Models
# Python - Using different models for different tasks
# For complex analysis
response = create_conversation(
"Analyze this complex dataset...",
model="claude-v4.6-opus"
)
# For quick responses
response = create_conversation(
"What's the capital of France?",
model="claude-v4.5-haiku"
)
# For multilingual tasks
response = create_conversation(
"Traduire ce texte en anglais...",
model="qwen3-32b"
)
# For reasoning tasks
response = create_conversation(
"Solve this logic puzzle step by step...",
model="claude-v4.6-opus"
)
Custom Inference Parameters
# Python - Fine-tuning model behavior
# Precise, deterministic responses
create_conversation(
"What is 2+2?",
model="claude-v4.6-sonnet",
temperature=0.0,
max_tokens=100
)
# Creative writing
create_conversation(
"Write a creative story...",
model="claude-v4.6-sonnet",
temperature=0.9,
max_tokens=4096
)
# Balanced for general use
create_conversation(
"Explain machine learning",
model="claude-v4.6-sonnet",
temperature=0.7,
max_tokens=2000
)
With Reasoning Mode
# Python - Enable reasoning for complex problems
url = f"{API_BASE_URL}/conversation"
headers = {
"x-api-key": API_KEY,
"Content-Type": "application/json"
}
payload = {
"message": {
"role": "user",
"content": [
{
"content_type": "text",
"body": "Solve this complex math problem step by step..."
}
],
"model": "claude-v4.6-opus"
},
"enable_reasoning": True
}
response = requests.post(url, headers=headers, json=payload)
conv_id = response.json()["conversation_id"]
# Get conversation with reasoning
conv = get_conversation(conv_id)
for content in conv["message_map"][conv["last_message_id"]]["content"]:
if content["content_type"] == "reasoning":
print(f"Reasoning: {content['text']}")
elif content["content_type"] == "text":
print(f"Answer: {content['body']}")
Best Practices
- Always implement exponential backoff for polling (0.3s → 0.45s → 0.68s → 1.0s → 1.5s)
- Treat 404 as "still processing" during polling, not as an error
- Monitor token usage proactively to avoid 429 errors
- Use appropriate temperature settings for your use case
- Always use
parent_message_idfor follow-up messages - Log errors with context (conversation ID, model, message length)
- Store API keys securely using environment variables
- Implement proper error handling and retries