Spaces:
Sleeping
Sleeping
Download agent/claude_client.py from maribiel/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 6.49 kB
-
https://huggingface.co/spaces/maribiel/Final_Assignment_Template/resolve/main/agent/claude_client.py
- Command line
-
hf download hf://spaces/maribiel/Final_Assignment_Template/agent/claude_client.py
-
curl -L -o claude_client.py https://huggingface.co/spaces/maribiel/Final_Assignment_Template/resolve/main/agent/claude_client.py
6.49 kB
| """ | |
| 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 | |
| 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 |