|
| 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 | +class _StructuredOutputError(ValueError): |
| 13 | + """Raised when the model response does not match the requested schema.""" |
| 14 | + |
| 15 | + |
| 16 | +def _parse_json_payload(text: str) -> dict: |
| 17 | + text = text.strip() |
| 18 | + |
| 19 | + try: |
| 20 | + payload = json.loads(text) |
| 21 | + except json.JSONDecodeError: |
| 22 | + pass |
| 23 | + else: |
| 24 | + if not isinstance(payload, dict): |
| 25 | + raise _StructuredOutputError("Model response must be a JSON object") |
| 26 | + return payload |
| 27 | + |
| 28 | + fenced = re.search(r"```(?:json)?\s*(\{.*\})\s*```", text, flags=re.DOTALL | re.IGNORECASE) |
| 29 | + if fenced: |
| 30 | + payload = json.loads(fenced.group(1)) |
| 31 | + if not isinstance(payload, dict): |
| 32 | + raise _StructuredOutputError("Model response must be a JSON object") |
| 33 | + return payload |
| 34 | + |
| 35 | + start = text.find("{") |
| 36 | + end = text.rfind("}") |
| 37 | + if start != -1 and end != -1 and end > start: |
| 38 | + payload = json.loads(text[start : end + 1]) |
| 39 | + if not isinstance(payload, dict): |
| 40 | + raise _StructuredOutputError("Model response must be a JSON object") |
| 41 | + return payload |
| 42 | + |
| 43 | + raise json.JSONDecodeError("Could not find JSON object in model response", text, 0) |
| 44 | + |
| 45 | + |
| 46 | +def _coerce_text_payload(text: str, schema: Schema) -> dict | None: |
| 47 | + text = text.strip() |
| 48 | + if not text: |
| 49 | + return None |
| 50 | + if len(schema.required) != 1: |
| 51 | + return None |
| 52 | + |
| 53 | + field = schema.required[0] |
| 54 | + spec = schema.properties.get(field, {}) |
| 55 | + field_type = spec.get("type", "string") |
| 56 | + |
| 57 | + if field_type == "string": |
| 58 | + return {field: text} |
| 59 | + |
| 60 | + if field_type == "boolean": |
| 61 | + lowered = text.lower() |
| 62 | + if lowered == "true": |
| 63 | + return {field: True} |
| 64 | + if lowered == "false": |
| 65 | + return {field: False} |
| 66 | + |
| 67 | + return None |
| 68 | + |
| 69 | + |
| 70 | +def _validate_schema_payload(payload: dict, schema: Schema) -> dict: |
| 71 | + extra = sorted(set(payload) - set(schema.properties)) |
| 72 | + if extra: |
| 73 | + raise _StructuredOutputError(f"Model response included unsupported field(s): {', '.join(extra)}") |
| 74 | + |
| 75 | + missing = [field for field in schema.required if field not in payload] |
| 76 | + if missing: |
| 77 | + raise _StructuredOutputError(f"Model response omitted required field(s): {', '.join(missing)}") |
| 78 | + |
| 79 | + for field, value in payload.items(): |
| 80 | + spec = schema.properties.get(field, {}) |
| 81 | + expected_type = spec.get("type", "string") |
| 82 | + if expected_type == "string": |
| 83 | + valid = isinstance(value, str) |
| 84 | + elif expected_type == "boolean": |
| 85 | + valid = isinstance(value, bool) |
| 86 | + elif expected_type == "integer": |
| 87 | + valid = isinstance(value, int) and not isinstance(value, bool) |
| 88 | + elif expected_type == "number": |
| 89 | + valid = isinstance(value, (int, float)) and not isinstance(value, bool) |
| 90 | + elif expected_type == "array": |
| 91 | + valid = isinstance(value, list) |
| 92 | + elif expected_type == "object": |
| 93 | + valid = isinstance(value, dict) |
| 94 | + else: |
| 95 | + valid = True |
| 96 | + |
| 97 | + if not valid: |
| 98 | + raise _StructuredOutputError( |
| 99 | + f"Model response field '{field}' must be {expected_type}, got {type(value).__name__}" |
| 100 | + ) |
| 101 | + |
| 102 | + return payload |
| 103 | + |
| 104 | + |
| 105 | +class AnthropicLLM(LLM): |
| 106 | + def __init__(self, model: str | None = None): |
| 107 | + from anthropic import Anthropic |
| 108 | + |
| 109 | + api_key = os.environ.get("ANTHROPIC_API_KEY") |
| 110 | + if not api_key: |
| 111 | + raise RuntimeError("Anthropic provider requires ANTHROPIC_API_KEY") |
| 112 | + |
| 113 | + base_url = os.environ.get("ANTHROPIC_BASE_URL") |
| 114 | + self._client = Anthropic( |
| 115 | + api_key=api_key, |
| 116 | + base_url=base_url or None, |
| 117 | + max_retries=0, |
| 118 | + ) |
| 119 | + self._model = ( |
| 120 | + model |
| 121 | + or os.environ.get("ANTHROPIC_MODEL") |
| 122 | + or "claude-sonnet-4-5" |
| 123 | + ) |
| 124 | + |
| 125 | + @property |
| 126 | + def model_id(self) -> str: |
| 127 | + return f"anthropic:{self._model}" |
| 128 | + |
| 129 | + def generate(self, prompt: str, schema: Schema) -> dict: |
| 130 | + from anthropic import APIConnectionError, APIStatusError, RateLimitError |
| 131 | + |
| 132 | + schema_json = { |
| 133 | + "type": "object", |
| 134 | + "properties": schema.properties, |
| 135 | + "required": schema.required, |
| 136 | + "additionalProperties": False, |
| 137 | + } |
| 138 | + system_prompt = ( |
| 139 | + "Return only a valid JSON object matching this schema. " |
| 140 | + "Do not wrap JSON in markdown fences.\n\n" |
| 141 | + f"{json.dumps(schema_json, ensure_ascii=False)}" |
| 142 | + ) |
| 143 | + |
| 144 | + delay = _RETRY_BASE_DELAY |
| 145 | + last_exc = None |
| 146 | + |
| 147 | + for attempt in range(_MAX_RETRIES): |
| 148 | + try: |
| 149 | + response = self._client.messages.create( |
| 150 | + model=self._model, |
| 151 | + max_tokens=4096, |
| 152 | + temperature=0.0, |
| 153 | + system=system_prompt, |
| 154 | + messages=[{"role": "user", "content": prompt}], |
| 155 | + ) |
| 156 | + text = "".join(block.text for block in response.content if getattr(block, "type", None) == "text") |
| 157 | + try: |
| 158 | + payload = _parse_json_payload(text) |
| 159 | + except json.JSONDecodeError: |
| 160 | + coerced = _coerce_text_payload(text, schema) |
| 161 | + if coerced is None: |
| 162 | + raise _StructuredOutputError("Model response was not valid JSON") from None |
| 163 | + payload = coerced |
| 164 | + return _validate_schema_payload(payload, schema) |
| 165 | + except (RateLimitError, APIConnectionError) as e: |
| 166 | + last_exc = e |
| 167 | + except APIStatusError as e: |
| 168 | + last_exc = e |
| 169 | + if e.status_code not in (429, 500, 502, 503, 504): |
| 170 | + raise |
| 171 | + except _StructuredOutputError as e: |
| 172 | + last_exc = e |
| 173 | + except Exception as e: |
| 174 | + last_exc = e |
| 175 | + msg = str(e) |
| 176 | + if "429" not in msg and "rate" not in msg.lower(): |
| 177 | + raise |
| 178 | + |
| 179 | + if attempt < _MAX_RETRIES - 1: |
| 180 | + time.sleep(delay) |
| 181 | + delay *= 2 |
| 182 | + |
| 183 | + raise RuntimeError(f"Anthropic request failed after {_MAX_RETRIES} retries: {last_exc}") |
0 commit comments