Spaces:
Running
Running
Implement image support in proxy with vision-aware routing
Browse files- Add Anthropic→OpenAI image block conversion with size validation
- Update ModelCapabilities with granular vision support fields
- Support base64-encoded images with memory optimization
- Add 20MB image size limit guard in conversion
- Clear base64 data from request blocks to reduce memory footprint
- Update mistral-large-3-675b model entry with vision capabilities
- Enable vision-aware model routing for image requests
Closes: image upload support in Claude Code proxy
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
Files changed (16)
- .claude/settings.local.json+5-1
- api/detection.py+10-1
- api/model_router.py+6-2
- api/web_tools/streaming.py+1
- config/__pycache__/settings.cpython-314.pyc
- core/__pycache__/rate_limit.cpython-314.pyc
- core/anthropic/conversion.py+60-10
- core/chain_engine.py+1-1
- core/model_capabilities.py+13-2
- core/task_detector.py+124-20
- providers/__pycache__/openai_compat.cpython-314.pyc
- providers/__pycache__/rate_limit.cpython-314.pyc
- providers/nvidia_nim/metrics.py+1
- providers/registry.py+3-1
- providers/zen/__init__.py+1-1
- providers/zen/client.py+1-1
13 unmodified lines14151617171819202122232413 unmodified lines "Bash(git commit *)", "Bash(dir \"C:\\\\Users\\\\yashw\\\\.gemini\\\\antigravity\\\\llm_wiki_v2\\\\wiki\\\\entities\")", "Bash(dir *)", "Bash(node -e ' *)" "Bash(node -e ' *)", "mcp__context7__resolve-library-id", "mcp__context7__query-docs", "Bash(git remote *)", "Bash(python *)" ] }, "enableAllProjectMcpServers": true,29 unmodified lines303132333334353637383940414243444529 unmodified lines # Single word or very short queries if len(text_lower) < 50: # "hi", "hello", "ok", "thanks", etc. if text_lower in ("hi", "hello", "ok", "thanks", "thank you", "yes", "no", "okay"): if text_lower in ( "hi", "hello", "ok", "thanks", "thank you", "yes", "no", "okay", ): return True, f"OK. {text}"
# Health/status checks89 unmodified lines90919293939495969798246 unmodified lines34534634734634834935035135235389 unmodified lines provider_id = Settings.parse_provider_type(cand) provider_model = Settings.parse_model_name(cand) if self._settings.provider_is_configured(provider_id): thinking_enabled = self._settings.resolve_thinking(claude_model_name) thinking_enabled = self._settings.resolve_thinking( claude_model_name ) return ResolvedModel( original_model=claude_model_name, provider_id=provider_id,246 unmodified lines and not requirements.requires_coding and not requirements.requires_reasoning ): logger.debug("Task-aware routing: low confidence, using load-based selection") logger.debug( "Task-aware routing: low confidence, using load-based selection" ) return candidates[0]
# Find best model matching required capabilities48 unmodified lines4950515253545548 unmodified lines hosted Anthropic citation or encrypted-content pipeline. """ from . import outbound
tool_name = forced_server_tool_name(request) if tool_name is None or not has_tool_named(request, tool_name): return431 unmodified lines43243343443543643743843943543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646739 unmodified lines507508509485486487488489510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542431 unmodified lines if block_type == "text": text_parts.append(get_block_attr(block, "text", "")) elif block_type == "image": raise OpenAIConversionError( "User message image blocks are not supported for OpenAI chat " "conversion; use a vision-capable native Anthropic provider or " "extend the converter." ) # Convert Anthropic image block to OpenAI image_url format source = get_block_attr(block, "source", {}) source_type = source.get("type", "base64")
if source_type == "base64": media_type = source.get("media_type", "image/png") data = source.get("data", "") # Size guard - check estimated decoded size estimated_size = len(data) * 4 // 3 # Use a reasonable default (20MB) as max image size max_image_bytes = 20 * 1024 * 1024 if estimated_size > max_image_bytes: raise OpenAIConversionError( f"Image size ({estimated_size/1024/1024:.1f}MB) exceeds limit " f"({max_image_bytes/1024/1024:.1f}MB)" ) image_url = f"data:{media_type};base64,{data}" result.append({ "type": "image_url", "image_url": {"url": image_url} }) elif source_type == "url": # Handle URL-based images url = source.get("url", "") result.append({ "type": "image_url", "image_url": {"url": url} }) else: logger.warning("Unsupported image source type: {}", source_type) elif block_type == "tool_result": flush_text() tool_content = get_block_attr(block, "content", "")39 unmodified lines if block_type == "text": text_parts.append(get_block_attr(block, "text", "")) elif block_type == "image": raise OpenAIConversionError( "User message image blocks are not supported for OpenAI chat " "conversion; use a vision-capable native Anthropic provider or " "extend the converter." ) # Convert Anthropic image block to OpenAI image_url format source = get_block_attr(block, "source", {}) source_type = source.get("type", "base64")
if source_type == "base64": media_type = source.get("media_type", "image/png") data = source.get("data", "") # Size guard - check estimated decoded size estimated_size = len(data) * 4 // 3 # Use a reasonable default (20MB) as max image size max_image_bytes = 20 * 1024 * 1024 if estimated_size > max_image_bytes: raise OpenAIConversionError( f"Image size ({estimated_size/1024/1024:.1f}MB) exceeds limit " f"({max_image_bytes/1024/1024:.1f}MB)" ) image_url = f"data:{media_type};base64,{data}" result.append({ "type": "image_url", "image_url": {"url": image_url} }) elif source_type == "url": # Handle URL-based images url = source.get("url", "") result.append({ "type": "image_url", "image_url": {"url": url} }) else: logger.warning("Unsupported image source type: {}", source_type) elif block_type == "tool_result": flush_text() tool_content = get_block_attr(block, "content", "")152 unmodified lines153154155156156152 unmodified lines return "".join(output_parts) except Exception as e: logger.error("Chain stage failed: {}", e) raise raise16 unmodified lines171819202122232425262746 unmodified lines74757677787980818283848586877788899091101 unmodified lines19319419518519616 unmodified lines model_id: str model_ref: str # provider/model format vision: bool = False # Can process images supports_base64_images: bool = False # Accepts data: URLs with base64 supports_remote_images: bool = False # Accepts http/https URLs supports_pdfs: bool = False # Can process PDF documents max_images: int = 0 # Max images per request (0 = unlimited) max_image_size_mb: float = 10.0 # Max size per image in MB coding: bool = False # Good at code generation/analysis reasoning: bool = False # Strong reasoning/thinking general_text: bool = True # General text generation46 unmodified lines provider_id="nvidia_nim", model_id="mistral-large-3-675b-instruct-2512", model_ref="nvidia_nim/mistralai/mistral-large-3-675b-instruct-2512", vision=True, supports_base64_images=True, supports_remote_images=False, max_images=16, max_image_size_mb=10.0, multimodal_input=True, coding=True, reasoning=True, general_text=True, max_tokens=32000, speed="slow", priority=85, priority=90, ), "nvidia_nim/abacusai/dracarys-llama-3.1-70b-instruct": ModelCapabilities( provider_id="nvidia_nim",101 unmodified lines Returns (matched_count, priority) for sorting. """ matched = sum(1 for cap in required if getattr(model_caps, cap, False)) return (matched, model_caps.priority) return (matched, model_caps.priority)12 unmodified lines1314151617181920212216171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667682627282930316970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810935363711011111211311411511611711811912012112212312412512612712812913013189 unmodified lines2212222231332242252262277 unmodified lines23523623714723823924024124224324424524624724824925025125225325425525625715425825926026132 unmodified lines29429529619329712 unmodified lines
# Keywords that indicate specific task typesCODING_KEYWORDS = { "python", "javascript", "typescript", "java", "c++", "cpp", "golang", "rust", "ruby", "php", "swift", "kotlin", "sql", "html", "css", "react", "vue", "angular", "node", "django", "flask", "fastapi", "spring", "function", "class", "method", "api", "endpoint", "database", "query", "algorithm", "debug", "error", "fix", "implement", "create", "write", "code", "programming", "script", "module", "import", "export", "def ", "const ", "let ", "var ", "function ", "async ", "await ", "python", "javascript", "typescript", "java", "c++", "cpp", "golang", "rust", "ruby", "php", "swift", "kotlin", "sql", "html", "css", "react", "vue", "angular", "node", "django", "flask", "fastapi", "spring", "function", "class", "method", "api", "endpoint", "database", "query", "algorithm", "debug", "error", "fix", "implement", "create", "write", "code", "programming", "script", "module", "import", "export", "def ", "const ", "let ", "var ", "function ", "async ", "await ",}
REASONING_KEYWORDS = { "analyze", "analysis", "reason", "why", "how", "explain", "compare", "contrast", "evaluate", "assess", "conclude", "deduce", "infer", "logic", "proof", "theorem", "hypothesis", "synthesize", "strategy", "think", "solve", "derive", "calculate", "compute", "math", "equation", "formula", "solution", "optimal", "best", "improve", "optimize", "design", "architecture", "system", "plan", "decision", "recommend", "analyze", "analysis", "reason", "why", "how", "explain", "compare", "contrast", "evaluate", "assess", "conclude", "deduce", "infer", "logic", "proof", "theorem", "hypothesis", "synthesize", "strategy", "think", "solve", "derive", "calculate", "compute", "math", "equation", "formula", "solution", "optimal", "best", "improve", "optimize", "design", "architecture", "system", "plan", "decision", "recommend",}
VISION_KEYWORDS = { "image", "picture", "photo", "screenshot", "diagram", "chart", "graph", "visual", "see", "look at", "describe what", "what's in", "identify", "recognize", "detect", "object", "scene", "face", "text in image", "image", "picture", "photo", "screenshot", "diagram", "chart", "graph", "visual", "see", "look at", "describe what", "what's in", "identify", "recognize", "detect", "object", "scene", "face", "text in image",}
89 unmodified lines def _detect_coding(self, text: str) -> bool: """Detect if request requires coding capabilities.""" # Check exact word matches first words = set(re.findall(r'\b\w+\b', text)) words = set(re.findall(r"\b\w+\b", text)) coding_matches = words & CODING_KEYWORDS if len(coding_matches) >= 2: return True7 unmodified lines if kw2 in remaining and kw2 != keyword: return True # Also check for programming patterns if any(pat in text for pat in ["def ", "function ", "class ", "import ", "const ", "let ", "var ", "()", "=>"]): if any( pat in text for pat in [ "def ", "function ", "class ", "import ", "const ", "let ", "var ", "()", "=>", ] ): return True
return False
def _detect_reasoning(self, text: str) -> bool: """Detect if request requires reasoning capabilities.""" words = set(re.findall(r'\b\w+\b', text)) words = set(re.findall(r"\b\w+\b", text)) reasoning_matches = words & REASONING_KEYWORDS if len(reasoning_matches) >= 1: return True32 unmodified lines return "coding" if requirements.requires_reasoning: return "reasoning" return "balanced" return "balanced"2 unmodified lines34567892 unmodified linesKeep metrics local to the process. Simple API for recording attempts,successes, and failures per candidate model."""
from __future__ import annotations
from threading import Lock320 unmodified lines321322323324324325326327328329320 unmodified lines if not tasks: return
logger.info("Starting model discovery for providers: {}", ", ".join(tasks.keys())) logger.info( "Starting model discovery for providers: {}", ", ".join(tasks.keys()) ) results = await asyncio.gather(*tasks.values(), return_exceptions=True) logger.info("Model discovery finished for all providers.") for (provider_id, _task), result in zip(tasks.items(), results, strict=True):3 unmodified lines456773 unmodified lines
from .client import ZenProvider
__all__ = ["ZEN_DEFAULT_BASE", "ZenProvider"]__all__ = ["ZEN_DEFAULT_BASE", "ZenProvider"]42 unmodified lines434445464642 unmodified lines return build_base_request_body( request, reasoning_replay=reasoning_replay, ) ).claude/settings.local.json+5-1
api/detection.py+10-1
api/model_router.py+6-2
api/web_tools/streaming.py+1
config/__pycache__/settings.cpython-314.pyc
core/__pycache__/rate_limit.cpython-314.pyc
core/anthropic/conversion.py+60-10
core/chain_engine.py+1-1
core/model_capabilities.py+13-2
core/task_detector.py+124-20
providers/__pycache__/openai_compat.cpython-314.pyc
providers/__pycache__/rate_limit.cpython-314.pyc
providers/nvidia_nim/metrics.py+1
providers/registry.py+3-1
providers/zen/__init__.py+1-1
providers/zen/client.py+1-1