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 lines1415161718192013 unmodified lines"Bash(git commit *)","Bash(dir \"C:\\\\Users\\\\yashw\\\\.gemini\\\\antigravity\\\\llm_wiki_v2\\\\wiki\\\\entities\")","Bash(dir *)","Bash(node -e ' *)"]},"enableAllProjectMcpServers": true,13 unmodified lines141516171819202122232413 unmodified lines"Bash(git commit *)","Bash(dir \"C:\\\\Users\\\\yashw\\\\.gemini\\\\antigravity\\\\llm_wiki_v2\\\\wiki\\\\entities\")","Bash(dir *)","Bash(node -e ' *)","mcp__context7__resolve-library-id","mcp__context7__query-docs","Bash(git remote *)","Bash(python *)"]},"enableAllProjectMcpServers": true,
29 unmodified lines3031323334353629 unmodified lines# Single word or very short queriesif len(text_lower) < 50:# "hi", "hello", "ok", "thanks", etc.if text_lower in ("hi", "hello", "ok", "thanks", "thank you", "yes", "no", "okay"):return True, f"OK. {text}"# Health/status checks29 unmodified lines3031323334353637383940414243444529 unmodified lines# Single word or very short queriesif len(text_lower) < 50:# "hi", "hello", "ok", "thanks", etc.if text_lower in ("hi","hello","ok","thanks","thank you","yes","no","okay",):return True, f"OK. {text}"# Health/status checks
89 unmodified lines90919293949596246 unmodified lines34334434534634734834989 unmodified linesprovider_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)return ResolvedModel(original_model=claude_model_name,provider_id=provider_id,246 unmodified linesand not requirements.requires_codingand not requirements.requires_reasoning):logger.debug("Task-aware routing: low confidence, using load-based selection")return candidates[0]# Find best model matching required capabilities89 unmodified lines909192939495969798246 unmodified lines34534634734834935035135235389 unmodified linesprovider_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)return ResolvedModel(original_model=claude_model_name,provider_id=provider_id,246 unmodified linesand not requirements.requires_codingand not requirements.requires_reasoning):logger.debug("Task-aware routing: low confidence, using load-based selection")return candidates[0]# Find best model matching required capabilities
48 unmodified lines49505152535448 unmodified lineshosted Anthropic citation or encrypted-content pipeline."""from . import outboundtool_name = forced_server_tool_name(request)if tool_name is None or not has_tool_named(request, tool_name):return48 unmodified lines4950515253545548 unmodified lineshosted Anthropic citation or encrypted-content pipeline."""from . import outboundtool_name = forced_server_tool_name(request)if tool_name is None or not has_tool_named(request, tool_name):return
431 unmodified lines43243343443543643743843944044144239 unmodified lines482483484485486487488489490491492431 unmodified linesif 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.")elif block_type == "tool_result":flush_text()tool_content = get_block_attr(block, "content", "")39 unmodified linesif 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.")elif block_type == "tool_result":flush_text()tool_content = get_block_attr(block, "content", "")431 unmodified lines43243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646739 unmodified lines507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542431 unmodified linesif block_type == "text":text_parts.append(get_block_attr(block, "text", ""))elif block_type == "image":# Convert Anthropic image block to OpenAI image_url formatsource = 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 sizeestimated_size = len(data) * 4 // 3# Use a reasonable default (20MB) as max image sizemax_image_bytes = 20 * 1024 * 1024if 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 imagesurl = 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 linesif block_type == "text":text_parts.append(get_block_attr(block, "text", ""))elif block_type == "image":# Convert Anthropic image block to OpenAI image_url formatsource = 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 sizeestimated_size = len(data) * 4 // 3# Use a reasonable default (20MB) as max image sizemax_image_bytes = 20 * 1024 * 1024if 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 imagesurl = 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 lines153154155156152 unmodified linesreturn "".join(output_parts)except Exception as e:logger.error("Chain stage failed: {}", e)raise152 unmodified lines153154155156152 unmodified linesreturn "".join(output_parts)except Exception as e:logger.error("Chain stage failed: {}", e)raise
16 unmodified lines17181920212246 unmodified lines697071727374757677787980101 unmodified lines18218318418516 unmodified linesmodel_id: strmodel_ref: str # provider/model formatvision: bool = False # Can process imagescoding: bool = False # Good at code generation/analysisreasoning: bool = False # Strong reasoning/thinkinggeneral_text: bool = True # General text generation46 unmodified linesprovider_id="nvidia_nim",model_id="mistral-large-3-675b-instruct-2512",model_ref="nvidia_nim/mistralai/mistral-large-3-675b-instruct-2512",coding=True,reasoning=True,general_text=True,max_tokens=32000,speed="slow",priority=85,),"nvidia_nim/abacusai/dracarys-llama-3.1-70b-instruct": ModelCapabilities(provider_id="nvidia_nim",101 unmodified linesReturns (matched_count, priority) for sorting."""matched = sum(1 for cap in required if getattr(model_caps, cap, False))return (matched, model_caps.priority)16 unmodified lines171819202122232425262746 unmodified lines747576777879808182838485868788899091101 unmodified lines19319419519616 unmodified linesmodel_id: strmodel_ref: str # provider/model formatvision: bool = False # Can process imagessupports_base64_images: bool = False # Accepts data: URLs with base64supports_remote_images: bool = False # Accepts http/https URLssupports_pdfs: bool = False # Can process PDF documentsmax_images: int = 0 # Max images per request (0 = unlimited)max_image_size_mb: float = 10.0 # Max size per image in MBcoding: bool = False # Good at code generation/analysisreasoning: bool = False # Strong reasoning/thinkinggeneral_text: bool = True # General text generation46 unmodified linesprovider_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=90,),"nvidia_nim/abacusai/dracarys-llama-3.1-70b-instruct": ModelCapabilities(provider_id="nvidia_nim",101 unmodified linesReturns (matched_count, priority) for sorting."""matched = sum(1 for cap in required if getattr(model_caps, cap, False))return (matched, model_caps.priority)
12 unmodified lines1314151617181920212223242526272829303132333435363738394089 unmodified lines1301311321331341351367 unmodified lines14414514614714814915015115215315415515615732 unmodified lines19019119219312 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 ",}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",}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",}89 unmodified linesdef _detect_coding(self, text: str) -> bool:"""Detect if request requires coding capabilities."""# Check exact word matches firstwords = set(re.findall(r'\b\w+\b', text))coding_matches = words & CODING_KEYWORDSif len(coding_matches) >= 2:return True7 unmodified linesif kw2 in remaining and kw2 != keyword:return True# Also check for programming patternsif any(pat in text for pat in ["def ", "function ", "class ", "import ", "const ", "let ", "var ", "()", "=>"]):return Truereturn Falsedef _detect_reasoning(self, text: str) -> bool:"""Detect if request requires reasoning capabilities."""words = set(re.findall(r'\b\w+\b', text))reasoning_matches = words & REASONING_KEYWORDSif len(reasoning_matches) >= 1:return True32 unmodified linesreturn "coding"if requirements.requires_reasoning:return "reasoning"return "balanced"12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013189 unmodified lines2212222232242252262277 unmodified lines23523623723823924024124224324424524624724824925025125225325425525625725825926026132 unmodified lines29429529629712 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 ",}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",}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",}89 unmodified linesdef _detect_coding(self, text: str) -> bool:"""Detect if request requires coding capabilities."""# Check exact word matches firstwords = set(re.findall(r"\b\w+\b", text))coding_matches = words & CODING_KEYWORDSif len(coding_matches) >= 2:return True7 unmodified linesif kw2 in remaining and kw2 != keyword:return True# Also check for programming patternsif any(pat in textfor pat in ["def ","function ","class ","import ","const ","let ","var ","()","=>",]):return Truereturn Falsedef _detect_reasoning(self, text: str) -> bool:"""Detect if request requires reasoning capabilities."""words = set(re.findall(r"\b\w+\b", text))reasoning_matches = words & REASONING_KEYWORDSif len(reasoning_matches) >= 1:return True32 unmodified linesreturn "coding"if requirements.requires_reasoning:return "reasoning"return "balanced"
2 unmodified lines3456782 unmodified linesKeep metrics local to the process. Simple API for recording attempts,successes, and failures per candidate model."""from __future__ import annotationsfrom threading import Lock2 unmodified lines34567892 unmodified linesKeep metrics local to the process. Simple API for recording attempts,successes, and failures per candidate model."""from __future__ import annotationsfrom threading import Lock
320 unmodified lines321322323324325326327320 unmodified linesif not tasks:returnlogger.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):320 unmodified lines321322323324325326327328329320 unmodified linesif not tasks:returnlogger.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 lines45673 unmodified linesfrom .client import ZenProvider__all__ = ["ZEN_DEFAULT_BASE", "ZenProvider"]3 unmodified lines45673 unmodified linesfrom .client import ZenProvider__all__ = ["ZEN_DEFAULT_BASE", "ZenProvider"]
42 unmodified lines4344454642 unmodified linesreturn build_base_request_body(request,reasoning_replay=reasoning_replay,)42 unmodified lines4344454642 unmodified linesreturn 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