import requests
import json
from typing import Optional
def chat_with_fallback(
message: str,
primary_candidates: list[str],
fallback_model: str = "openai/gpt-4o"
) -> dict:
"""Chat with smart routing and fallback to fixed model on error."""
url = "https://api.edenai.run/v3/llm/chat/completions"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
# Try smart routing first
try:
payload = {
"model": "@edenai",
"router_candidates": primary_candidates,
"messages": [{"role": "user", "content": message}],
"stream": True
}
response = requests.post(url, headers=headers, json=payload, stream=True, timeout=30)
response.raise_for_status()
full_response = ""
for line in response.iter_lines():
if line:
line_str = line.decode('utf-8')
if line_str.startswith('data: ') and line_str != 'data: [DONE]':
data = json.loads(line_str[6:])
content = data.get('choices', [{}])[0].get('delta', {}).get('content', '')
full_response += content
return {
"response": full_response,
"method": "smart_routing",
"success": True
}
except Exception as e:
print(f"Smart routing failed: {e}")
print(f"Falling back to {fallback_model}")
# Fallback to fixed model
try:
payload = {
"model": fallback_model,
"messages": [{"role": "user", "content": message}],
"stream": True
}
response = requests.post(url, headers=headers, json=payload, stream=True, timeout=30)
response.raise_for_status()
full_response = ""
for line in response.iter_lines():
if line:
line_str = line.decode('utf-8')
if line_str.startswith('data: ') and line_str != 'data: [DONE]':
data = json.loads(line_str[6:])
content = data.get('choices', [{}])[0].get('delta', {}).get('content', '')
full_response += content
return {
"response": full_response,
"method": "fallback",
"fallback_model": fallback_model,
"success": True,
"original_error": str(e)
}
except Exception as fallback_error:
return {
"response": None,
"method": "failed",
"success": False,
"error": str(fallback_error)
}
# Usage
result = chat_with_fallback(
"Explain neural networks",
primary_candidates=["openai/gpt-4o", "anthropic/claude-sonnet-4-5"]
)
if result["success"]:
print(f"Response (via {result['method']}): {result['response']}")
else:
print(f"Failed: {result['error']}")