|
| 1 | +import json |
| 2 | +import os |
| 3 | +import re |
| 4 | +import time |
| 5 | + |
| 6 | +from .base import LLM, Schema |
| 7 | + |
| 8 | +_MAX_RETRIES = 6 |
| 9 | +_RETRY_BASE_DELAY = 5 |
| 10 | + |
| 11 | + |
| 12 | +def _parse_json_payload(text: str) -> dict: |
| 13 | + text = text.strip() |
| 14 | + |
| 15 | + try: |
| 16 | + return json.loads(text) |
| 17 | + except json.JSONDecodeError: |
| 18 | + pass |
| 19 | + |
| 20 | + fenced = re.search(r"```(?:json)?\s*(\{.*\})\s*```", text, flags=re.DOTALL | re.IGNORECASE) |
| 21 | + if fenced: |
| 22 | + return json.loads(fenced.group(1)) |
| 23 | + |
| 24 | + start = text.find("{") |
| 25 | + end = text.rfind("}") |
| 26 | + if start != -1 and end != -1 and end > start: |
| 27 | + return json.loads(text[start : end + 1]) |
| 28 | + |
| 29 | + raise json.JSONDecodeError("Could not find JSON object in model response", text, 0) |
| 30 | + |
| 31 | + |
| 32 | +def _coerce_text_payload(text: str, schema: Schema) -> dict | None: |
| 33 | + text = text.strip() |
| 34 | + if not text: |
| 35 | + return None |
| 36 | + |
| 37 | + result: dict = {} |
| 38 | + for field in schema.required: |
| 39 | + spec = schema.properties.get(field, {}) |
| 40 | + field_type = spec.get("type", "string") |
| 41 | + lowered = text.lower() |
| 42 | + |
| 43 | + if field_type == "string": |
| 44 | + result[field] = text |
| 45 | + continue |
| 46 | + |
| 47 | + if field_type == "boolean": |
| 48 | + if re.search(r"\btrue\b", lowered): |
| 49 | + result[field] = True |
| 50 | + continue |
| 51 | + if re.search(r"\bfalse\b", lowered): |
| 52 | + result[field] = False |
| 53 | + continue |
| 54 | + if re.search(r"\b(correct|yes)\b", lowered) and not re.search(r"\b(incorrect|wrong|no)\b", lowered): |
| 55 | + result[field] = True |
| 56 | + continue |
| 57 | + if re.search(r"\b(incorrect|wrong|no)\b", lowered): |
| 58 | + result[field] = False |
| 59 | + continue |
| 60 | + return None |
| 61 | + |
| 62 | + return None |
| 63 | + |
| 64 | + return result |
| 65 | + |
| 66 | + |
| 67 | +class AnthropicLLM(LLM): |
| 68 | + def __init__(self, model: str | None = None): |
| 69 | + from anthropic import Anthropic |
| 70 | + |
| 71 | + api_key = os.environ.get("ANTHROPIC_API_KEY") |
| 72 | + if not api_key: |
| 73 | + raise RuntimeError("Anthropic provider requires ANTHROPIC_API_KEY") |
| 74 | + |
| 75 | + base_url = os.environ.get("ANTHROPIC_BASE_URL") |
| 76 | + self._client = Anthropic( |
| 77 | + api_key=api_key, |
| 78 | + base_url=base_url or None, |
| 79 | + max_retries=0, |
| 80 | + ) |
| 81 | + self._model = ( |
| 82 | + model |
| 83 | + or os.environ.get("ANTHROPIC_MODEL") |
| 84 | + or "claude-sonnet-4-5" |
| 85 | + ) |
| 86 | + |
| 87 | + @property |
| 88 | + def model_id(self) -> str: |
| 89 | + return f"anthropic:{self._model}" |
| 90 | + |
| 91 | + def generate(self, prompt: str, schema: Schema) -> dict: |
| 92 | + from anthropic import APIConnectionError, APIStatusError, RateLimitError |
| 93 | + |
| 94 | + schema_json = { |
| 95 | + "type": "object", |
| 96 | + "properties": schema.properties, |
| 97 | + "required": schema.required, |
| 98 | + "additionalProperties": False, |
| 99 | + } |
| 100 | + system_prompt = ( |
| 101 | + "Return only a valid JSON object matching this schema. " |
| 102 | + "Do not wrap JSON in markdown fences.\n\n" |
| 103 | + f"{json.dumps(schema_json, ensure_ascii=False)}" |
| 104 | + ) |
| 105 | + |
| 106 | + delay = _RETRY_BASE_DELAY |
| 107 | + last_exc = None |
| 108 | + |
| 109 | + for attempt in range(_MAX_RETRIES): |
| 110 | + try: |
| 111 | + response = self._client.messages.create( |
| 112 | + model=self._model, |
| 113 | + max_tokens=4096, |
| 114 | + temperature=0.0, |
| 115 | + system=system_prompt, |
| 116 | + messages=[{"role": "user", "content": prompt}], |
| 117 | + ) |
| 118 | + text = "".join(block.text for block in response.content if getattr(block, "type", None) == "text") |
| 119 | + try: |
| 120 | + return _parse_json_payload(text) |
| 121 | + except json.JSONDecodeError: |
| 122 | + coerced = _coerce_text_payload(text, schema) |
| 123 | + if coerced is not None: |
| 124 | + return coerced |
| 125 | + raise |
| 126 | + except (RateLimitError, APIConnectionError) as e: |
| 127 | + last_exc = e |
| 128 | + except APIStatusError as e: |
| 129 | + last_exc = e |
| 130 | + if e.status_code not in (429, 500, 502, 503, 504): |
| 131 | + raise |
| 132 | + except Exception as e: |
| 133 | + last_exc = e |
| 134 | + msg = str(e) |
| 135 | + if "429" not in msg and "rate" not in msg.lower(): |
| 136 | + raise |
| 137 | + |
| 138 | + if attempt < _MAX_RETRIES - 1: |
| 139 | + time.sleep(delay) |
| 140 | + delay *= 2 |
| 141 | + |
| 142 | + raise RuntimeError(f"Anthropic request failed after {_MAX_RETRIES} retries: {last_exc}") |
0 commit comments