| """Provider abstraction for eval scripts. |
| |
| Defaults to HuggingFace Inference API using the HF_TOKEN from .env. |
| Override via environment variables if needed: |
| |
| PROVIDER=anthropic → direct Anthropic SDK |
| PROVIDER=openrouter → OpenRouter (Claude, GPT-4V, Gemini, ...) |
| PROVIDER=hf → HuggingFace Inference API (default) |
| |
| EVAL_MODEL=<model_id> → override the default model for any provider |
| """ |
|
|
| import base64 |
| import io |
| import os |
| from pathlib import Path |
|
|
| from PIL import Image |
|
|
| |
| _env_path = Path(__file__).resolve().parents[2] / ".env" |
| if _env_path.exists(): |
| from dotenv import load_dotenv |
| load_dotenv(_env_path, override=False) |
|
|
| |
|
|
| |
| |
| |
| |
| |
| |
| HF_BACKEND = os.environ.get("HF_BACKEND", "together") |
| HF_MODEL = "google/gemma-4-31B-it" |
|
|
| DEFAULTS = { |
| "anthropic": "claude-opus-4-5", |
| "openrouter": "anthropic/claude-opus-4-5", |
| "hf": HF_MODEL, |
| } |
|
|
| |
| def _default_provider() -> str: |
| if os.environ.get("ANTHROPIC_API_KEY"): |
| return "anthropic" |
| if os.environ.get("OPENROUTER_API_KEY"): |
| return "openrouter" |
| return "hf" |
|
|
|
|
| def get_provider() -> str: |
| return os.environ.get("PROVIDER", _default_provider()).lower() |
|
|
|
|
| def get_model() -> str: |
| return os.environ.get("EVAL_MODEL", DEFAULTS[get_provider()]) |
|
|
|
|
| def get_client(): |
| """Return a client for the configured provider.""" |
| provider = get_provider() |
| print(f"[provider] {provider} / {get_model()}") |
|
|
| if provider == "anthropic": |
| import anthropic |
| return _AnthropicWrapper( |
| anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) |
| ) |
|
|
| from openai import OpenAI |
|
|
| if provider == "openrouter": |
| return OpenAI( |
| base_url="https://openrouter.ai/api/v1", |
| api_key=os.environ["OPENROUTER_API_KEY"], |
| default_headers={ |
| "HTTP-Referer": "https://github.com/midah/patent-wireframes", |
| "X-Title": "patent-wireframes-eval", |
| }, |
| ) |
|
|
| if provider == "hf": |
| token = os.environ.get("HF_TOKEN") |
| if not token: |
| raise RuntimeError("HF_TOKEN not set. Add it to .env or export it.") |
| backend = os.environ.get("HF_BACKEND", HF_BACKEND) |
| return OpenAI( |
| base_url=f"https://router.huggingface.co/{backend}/v1", |
| api_key=token, |
| ) |
|
|
| raise ValueError(f"Unknown PROVIDER={provider!r}. Choose: anthropic, openrouter, hf") |
|
|
|
|
| |
|
|
| def encode_image(path: Path, max_long_edge: int = 1024) -> tuple[str, str]: |
| """Return (base64_str, media_type) for an image file, resized to fit.""" |
| img = Image.open(path).convert("RGB") |
| w, h = img.size |
| scale = min(max_long_edge / max(w, h), 1.0) |
| if scale < 1.0: |
| img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS) |
| buf = io.BytesIO() |
| img.save(buf, format="JPEG", quality=85) |
| return base64.standard_b64encode(buf.getvalue()).decode(), "image/jpeg" |
|
|
|
|
| |
|
|
| _NOTHINK_PREFIX = "/nothink\n" |
|
|
| def _inject_nothink(messages: list[dict]) -> list[dict]: |
| """Prepend /nothink to any text block so thinking models skip CoT.""" |
| if get_provider() != "hf" or "gemma" not in get_model().lower(): |
| return messages |
| import copy |
| msgs = copy.deepcopy(messages) |
| content = msgs[0].get("content", "") |
|
|
| |
| if isinstance(content, str): |
| if not content.startswith("/nothink"): |
| msgs[0]["content"] = _NOTHINK_PREFIX + content |
| return msgs |
|
|
| |
| for block in content: |
| if isinstance(block, dict) and block.get("type") == "text" and block.get("text", "").strip(): |
| if not block["text"].startswith("/nothink"): |
| block["text"] = _NOTHINK_PREFIX + block["text"] |
| return msgs |
|
|
| |
| content.append({"type": "text", "text": _NOTHINK_PREFIX}) |
| return msgs |
|
|
|
|
| def chat(client, messages: list[dict], max_tokens: int = 200) -> str: |
| """Send messages and return the text response. |
| |
| Works with both the Anthropic wrapper and OpenAI-compatible clients. |
| """ |
| if isinstance(client, _AnthropicWrapper): |
| return client.chat(messages, max_tokens) |
|
|
| |
| import time |
| messages = _inject_nothink(messages) |
| for attempt in range(4): |
| try: |
| resp = client.chat.completions.create( |
| model=get_model(), |
| messages=messages, |
| max_tokens=max(max_tokens, 600), |
| ) |
| return (resp.choices[0].message.content or "").strip() |
| except Exception as e: |
| if "429" in str(e) or "rate" in str(e).lower(): |
| wait = 4 ** attempt |
| print(f" Rate limit, retrying in {wait}s...") |
| time.sleep(wait) |
| else: |
| raise |
| return "" |
|
|
|
|
| def image_message(b64: str, media_type: str, text: str) -> list[dict]: |
| """Build a user message with one image + text, in OpenAI vision format.""" |
| return [{ |
| "role": "user", |
| "content": [ |
| {"type": "image_url", |
| "image_url": {"url": f"data:{media_type};base64,{b64}"}}, |
| {"type": "text", "text": text}, |
| ], |
| }] |
|
|
|
|
| def multi_image_message( |
| images: list[tuple[str, str]], |
| text_before: str = "", |
| text_after: str = "", |
| labels: list[str] | None = None, |
| ) -> list[dict]: |
| """Build a user message with multiple images, interleaved with labels.""" |
| content = [] |
| if text_before: |
| content.append({"type": "text", "text": text_before}) |
| for i, (b64, media_type) in enumerate(images): |
| if labels: |
| content.append({"type": "text", "text": labels[i]}) |
| content.append({"type": "image_url", |
| "image_url": {"url": f"data:{media_type};base64,{b64}"}}) |
| if text_after: |
| content.append({"type": "text", "text": text_after}) |
| return [{"role": "user", "content": content}] |
|
|
|
|
| |
|
|
| class _AnthropicWrapper: |
| """Wraps anthropic.Anthropic to accept OpenAI-format image_url content.""" |
|
|
| def __init__(self, client): |
| self._client = client |
|
|
| def chat(self, messages: list[dict], max_tokens: int) -> str: |
| converted = self._convert_messages(messages) |
| resp = self._client.messages.create( |
| model=get_model(), |
| max_tokens=max_tokens, |
| messages=converted, |
| ) |
| return resp.content[0].text.strip() |
|
|
| @staticmethod |
| def _convert_messages(messages: list[dict]) -> list[dict]: |
| """Convert OpenAI image_url format → Anthropic base64 format.""" |
| out = [] |
| for msg in messages: |
| role = msg["role"] |
| content = msg["content"] |
| if isinstance(content, str): |
| out.append({"role": role, "content": content}) |
| continue |
| new_content = [] |
| for block in content: |
| if block["type"] == "image_url": |
| url = block["image_url"]["url"] |
| |
| if url.startswith("data:"): |
| meta, data = url.split(",", 1) |
| media_type = meta.split(":")[1].split(";")[0] |
| new_content.append({ |
| "type": "image", |
| "source": { |
| "type": "base64", |
| "media_type": media_type, |
| "data": data, |
| }, |
| }) |
| else: |
| new_content.append({ |
| "type": "image", |
| "source": {"type": "url", "url": url}, |
| }) |
| else: |
| new_content.append(block) |
| out.append({"role": role, "content": new_content}) |
| return out |
|
|