File size: 6,489 Bytes
3f1068e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | """
Claude API Client with retry logic and error handling
"""
import os
import logging
from typing import Optional, List, Dict, Any
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
import anthropic
from anthropic import APIError, APITimeoutError
logger = logging.getLogger(__name__)
class ClaudeClient:
"""Wrapper for Claude API with retry logic and fallback handling"""
def __init__(self, api_key: Optional[str] = None, model: str = "claude-3-5-sonnet-20241022"):
"""
Initialize Claude client
Args:
api_key: Anthropic API key (if not provided, reads from env)
model: Model to use (default: claude-3-5-sonnet)
"""
self.api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
if not self.api_key:
raise ValueError("ANTHROPIC_API_KEY not found in environment variables")
self.client = anthropic.Anthropic(api_key=self.api_key)
self.model = model
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=4, max=10),
retry=retry_if_exception_type((APIError, APITimeoutError))
)
def query(self,
prompt: str,
system_prompt: Optional[str] = None,
max_tokens: int = 4096,
temperature: float = 0.7,
tools: Optional[List[Dict[str, Any]]] = None) -> str:
"""
Query Claude with retry logic
Args:
prompt: User prompt
system_prompt: System prompt for context
max_tokens: Maximum tokens in response
temperature: Sampling temperature
tools: Optional tools/functions to provide
Returns:
Model response as string
"""
try:
messages = [{"role": "user", "content": prompt}]
kwargs = {
"model": self.model,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature
}
if system_prompt:
kwargs["system"] = system_prompt
if tools:
kwargs["tools"] = tools
response = self.client.messages.create(**kwargs)
# Extract text from response
if response.content:
if isinstance(response.content, list):
# Handle list of content blocks
text_parts = []
for block in response.content:
if hasattr(block, 'text'):
text_parts.append(block.text)
return ' '.join(text_parts)
else:
return str(response.content)
return ""
except APITimeoutError as e:
logger.error(f"Claude API timeout: {e}")
raise
except APIError as e:
logger.error(f"Claude API error: {e}")
raise
except Exception as e:
logger.error(f"Unexpected error calling Claude: {e}")
raise
def query_with_images(self,
prompt: str,
images: List[str],
system_prompt: Optional[str] = None,
max_tokens: int = 4096) -> str:
"""
Query Claude with images
Args:
prompt: User prompt
images: List of base64 encoded images
system_prompt: System prompt
max_tokens: Maximum tokens in response
Returns:
Model response as string
"""
try:
# Build content with images
content = [{"type": "text", "text": prompt}]
for image in images:
content.append({
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": image
}
})
messages = [{"role": "user", "content": content}]
kwargs = {
"model": self.model,
"messages": messages,
"max_tokens": max_tokens,
}
if system_prompt:
kwargs["system"] = system_prompt
response = self.client.messages.create(**kwargs)
if response.content:
if isinstance(response.content, list):
text_parts = []
for block in response.content:
if hasattr(block, 'text'):
text_parts.append(block.text)
return ' '.join(text_parts)
else:
return str(response.content)
return ""
except Exception as e:
logger.error(f"Error in image query: {e}")
raise
def stream_query(self,
prompt: str,
system_prompt: Optional[str] = None,
max_tokens: int = 4096,
temperature: float = 0.7):
"""
Stream response from Claude
Args:
prompt: User prompt
system_prompt: System prompt
max_tokens: Maximum tokens
temperature: Sampling temperature
Yields:
Response chunks as they arrive
"""
try:
messages = [{"role": "user", "content": prompt}]
kwargs = {
"model": self.model,
"messages": messages,
"max_tokens": max_tokens,
"temperature": temperature,
}
if system_prompt:
kwargs["system"] = system_prompt
with self.client.messages.stream(**kwargs) as stream:
for chunk in stream:
if hasattr(chunk, 'delta') and hasattr(chunk.delta, 'text'):
yield chunk.delta.text
except Exception as e:
logger.error(f"Error in stream query: {e}")
raise |