169 lines
6.0 KiB
Python
169 lines
6.0 KiB
Python
"""The Anthropic client and `ask_json`: one prompt for bare JSON, one parsed reply.
|
|
|
|
The two exception types map to 502 and 503 in `main`. Never imports FastAPI.
|
|
"""
|
|
|
|
import functools
|
|
import logging
|
|
import os
|
|
from typing import Callable, Optional, TypeVar
|
|
|
|
import anthropic
|
|
from pydantic import BaseModel, ValidationError
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
T = TypeVar("T", bound=BaseModel)
|
|
|
|
# Read once at import; blank means the default. Unknown ids are passed
|
|
# through and treated as thinking models.
|
|
DEFAULT_MODEL = "claude-sonnet-5-5"
|
|
MODEL = os.environ.get("CLAUDE_MODEL", "").strip() or DEFAULT_MODEL
|
|
|
|
# Models that take no effort setting and don't think unless asked.
|
|
_NO_EFFORT_PREFIXES = ("claude-haiku-4-5",)
|
|
|
|
# Thinking counts against max_tokens, and callers size theirs for the reply.
|
|
THINKING_HEADROOM = 4000
|
|
|
|
# Set explicitly because the default differs between models.
|
|
EFFORT = "low"
|
|
|
|
# Per attempt; the SDK retries twice. The Go caller's timeout sits above that.
|
|
TIMEOUT_S = 30.0
|
|
|
|
|
|
class ReadError(Exception):
|
|
"""Claude could not produce the answer; the message is safe to show the admin."""
|
|
|
|
|
|
class NotConfigured(ReadError):
|
|
"""CLAUDE_API_KEY is not set in this container."""
|
|
|
|
|
|
@functools.lru_cache(maxsize=1)
|
|
def client() -> anthropic.Anthropic:
|
|
"""Build the Anthropic client on first use.
|
|
|
|
Lazy so that a missing key only breaks the Claude features: the hotel
|
|
finder must still boot without it. The key is passed explicitly because the
|
|
stack's variable is CLAUDE_API_KEY, not the ANTHROPIC_API_KEY the SDK looks
|
|
for.
|
|
"""
|
|
key = os.environ.get("CLAUDE_API_KEY", "")
|
|
if not key:
|
|
raise NotConfigured("CLAUDE_API_KEY is not set")
|
|
return anthropic.Anthropic(api_key=key, timeout=TIMEOUT_S)
|
|
|
|
|
|
def strip_markdown_fence(raw: str) -> str:
|
|
"""Remove a surrounding markdown code fence from a model's response.
|
|
|
|
The prompts ask for bare JSON and the model fences it anyway often enough
|
|
to matter. "```json" is tried before a plain "```", and unfenced input
|
|
comes back unchanged apart from surrounding whitespace. This is the only
|
|
copy: the Go backend had its own while it still called Claude itself, and
|
|
every Claude call now goes through this service.
|
|
"""
|
|
raw = raw.strip()
|
|
raw = raw.removeprefix("```json")
|
|
raw = raw.removeprefix("```")
|
|
raw = raw.removesuffix("```")
|
|
return raw.strip()
|
|
|
|
|
|
def _model_options(model: str, max_tokens: int) -> dict:
|
|
"""The parts of the request that depend on which model is configured.
|
|
|
|
`max_tokens` is the caller's ceiling on the reply. A model that thinks
|
|
gets THINKING_HEADROOM on top and an explicit effort level; Haiku 4.5
|
|
gets neither, because it rejects `output_config.effort` and does not think
|
|
unless a budget is requested, which nothing here does.
|
|
"""
|
|
if model.startswith(_NO_EFFORT_PREFIXES):
|
|
return {"max_tokens": max_tokens}
|
|
return {
|
|
"max_tokens": max_tokens + THINKING_HEADROOM,
|
|
"output_config": {"effort": EFFORT},
|
|
}
|
|
|
|
|
|
def ask_json(
|
|
model_cls: type[T],
|
|
*,
|
|
max_tokens: int,
|
|
messages: list,
|
|
system: Optional[str] = None,
|
|
failed: str,
|
|
empty: str,
|
|
unparseable: str,
|
|
get_client: Optional[Callable[[], anthropic.Anthropic]] = None,
|
|
) -> T:
|
|
"""Send one prompt that asks for a bare JSON object and validate the reply.
|
|
|
|
The three message arguments are what the caller's user ends up reading:
|
|
the Go backend relays a ReadError's text verbatim, so each caller words
|
|
its own and nothing from the API or the model's reply leaks into it. The
|
|
detail goes to the log instead.
|
|
|
|
Args:
|
|
model_cls: the pydantic model the reply must validate as; its field
|
|
names are the keys the caller's prompt asks for.
|
|
max_tokens: ceiling on the reply; see _model_options for what is
|
|
actually sent.
|
|
messages: the `messages` list, passed to the API as is.
|
|
system: the system prompt, left out of the request when None.
|
|
failed: ReadError text when the API call itself failed.
|
|
empty: ReadError text when the reply has no text block.
|
|
unparseable: ReadError text when the reply is not JSON, or is JSON
|
|
that `model_cls` rejects.
|
|
get_client: returns the Anthropic client. Callers pass their own
|
|
module-level `_client` so that a test can replace the client for
|
|
one module; resolved here, per call, when not given.
|
|
|
|
Raises:
|
|
NotConfigured: no API key.
|
|
ReadError: with one of the three messages above.
|
|
"""
|
|
request = {
|
|
"model": MODEL,
|
|
"messages": messages,
|
|
**_model_options(MODEL, max_tokens),
|
|
}
|
|
if system is not None:
|
|
request["system"] = system
|
|
|
|
# Outside the try so NotConfigured reaches `main` and becomes the 503.
|
|
api = (get_client or client)()
|
|
try:
|
|
message = api.messages.create(**request)
|
|
except anthropic.APIStatusError as e:
|
|
log.warning("Claude API error %s: %s", e.status_code, e.message)
|
|
raise ReadError(failed) from e
|
|
except anthropic.APIConnectionError as e:
|
|
log.warning("Claude API unreachable: %s", e)
|
|
raise ReadError(failed) from e
|
|
|
|
# A refusal is a 200; log it as such rather than as an unparseable reply.
|
|
if getattr(message, "stop_reason", None) == "refusal":
|
|
log.warning(
|
|
"Claude declined the request: %s", getattr(message, "stop_details", None)
|
|
)
|
|
raise ReadError(failed)
|
|
|
|
# By type: on a thinking model the first block may be a thinking block.
|
|
text = next((block.text for block in message.content if block.type == "text"), None)
|
|
if text is None:
|
|
if getattr(message, "stop_reason", None) == "max_tokens":
|
|
log.warning(
|
|
"Claude ran out of tokens before answering (max_tokens=%s)",
|
|
request["max_tokens"],
|
|
)
|
|
raise ReadError(empty)
|
|
|
|
try:
|
|
return model_cls.model_validate_json(strip_markdown_fence(text))
|
|
except ValidationError as e:
|
|
log.warning("unparseable model output %r: %s", text, e)
|
|
raise ReadError(unparseable) from e
|