Spaces:
Sleeping
Sleeping
Download scripts/lib/chat/llm_client.py from defenestrate/asa: direct link, hf CLI and curl.
- Browser
- Download file 9.94 kB
-
https://huggingface.co/spaces/defenestrate/asa/resolve/main/scripts/lib/chat/llm_client.py
- Command line
-
hf download hf://spaces/defenestrate/asa/scripts/lib/chat/llm_client.py
-
curl -L -o llm_client.py https://huggingface.co/spaces/defenestrate/asa/resolve/main/scripts/lib/chat/llm_client.py
9.94 kB
| """Anthropic SDK wrappers: ClaudeClient (the default Sonnet, streaming) + | |
| HaikuClient (Haiku 4.5, complete()). | |
| Both read ANTHROPIC_API_KEY from env. The default Sonnet has a 1M-token | |
| context window without a beta header. | |
| """ | |
| from __future__ import annotations | |
| import os | |
| from typing import Iterator | |
| from scripts.lib.runtime_config import DEFAULT_CLAUDE_EFFORT, DEFAULT_CLAUDE_MODEL | |
| class MissingAnthropicKeyError(RuntimeError): | |
| """ANTHROPIC_API_KEY not in env.""" | |
| class ClaudeApiError(RuntimeError): | |
| """Claude API call failed after retries.""" | |
| _DEFAULT_CLAUDE_MODEL = DEFAULT_CLAUDE_MODEL | |
| _DEFAULT_HAIKU_MODEL = "claude-haiku-4-5" | |
| _ANSWER_MAX_TOKENS = 16000 # thinking counts toward this, so leave room | |
| class ClaudeClient: | |
| """Streaming Anthropic SDK wrapper. Used for the main chat LLM.""" | |
| def __init__(self, model: str | None = None) -> None: | |
| if not os.environ.get("ANTHROPIC_API_KEY"): | |
| raise MissingAnthropicKeyError( | |
| "ANTHROPIC_API_KEY not set. The chat application requires it. " | |
| "Set ANTHROPIC_API_KEY (see `me-hub-bootstrap`)." | |
| ) | |
| self.model = model or os.environ.get("CLAUDE_MODEL") or _DEFAULT_CLAUDE_MODEL | |
| # Populated after each stream() completes with real Anthropic usage | |
| # (input_tokens, output_tokens, cache_creation_input_tokens, | |
| # cache_read_input_tokens). Stateful but scoped per-instance — | |
| # concurrent streams on the same client would race; v0 chat is | |
| # single-session-per-client so this is fine. | |
| self.last_usage: dict | None = None | |
| def stream( | |
| self, | |
| system: str, | |
| messages: list[dict], | |
| *, | |
| session_core_block: str | None = None, | |
| ) -> Iterator[str]: | |
| """Yield streamed token chunks from Claude. | |
| Cache breakpoints: | |
| 1. The system prompt (5-min ephemeral; ~870 tokens, may not hit | |
| on its own due to Sonnet's 1024-token minimum, but harmless). | |
| 2. The optional session_core_block as a second `system` text | |
| block (1-hour extended TTL; the high-leverage breakpoint). | |
| 3. The most recent assistant message (5-min ephemeral; caches | |
| the conversation prefix through that turn). | |
| Raises ClaudeApiError on persistent API failure (after SDK retries). | |
| """ | |
| try: | |
| import anthropic | |
| except ImportError as e: | |
| raise ClaudeApiError( | |
| "anthropic SDK not installed; run `pip install -r requirements.txt`" | |
| ) from e | |
| kwargs: dict = {} | |
| extra_headers: dict[str, str] = {} | |
| # Anthropic requires longer-TTL cache_control blocks to come BEFORE | |
| # shorter-TTL ones in the system field. So when present, the 1h | |
| # session_core_block goes first; the 5m system prompt follows. | |
| system_blocks: list[dict] = [] | |
| if session_core_block: | |
| system_blocks.append({ | |
| "type": "text", "text": session_core_block, | |
| "cache_control": {"type": "ephemeral", "ttl": "1h"}, | |
| }) | |
| beta = extra_headers.get("anthropic-beta", "") | |
| extra = "extended-cache-ttl-2025-04-11" | |
| extra_headers["anthropic-beta"] = ( | |
| f"{beta},{extra}" if beta else extra | |
| ) | |
| system_blocks.append( | |
| {"type": "text", "text": system, | |
| "cache_control": {"type": "ephemeral"}} | |
| ) | |
| if extra_headers: | |
| kwargs["extra_headers"] = extra_headers | |
| cached_messages = _add_history_cache_marker(messages) | |
| client = anthropic.Anthropic() | |
| used_fallback = False | |
| def _open_stream(system_blocks_arg, extra_headers_arg): | |
| inner_kwargs = dict(kwargs) | |
| if extra_headers_arg: | |
| inner_kwargs["extra_headers"] = extra_headers_arg | |
| else: | |
| inner_kwargs.pop("extra_headers", None) | |
| return client.messages.stream( | |
| model=self.model, | |
| max_tokens=_ANSWER_MAX_TOKENS, | |
| system=system_blocks_arg, | |
| messages=cached_messages, | |
| # extra_body, so older SDK pins still send the effort setting. | |
| extra_body={"output_config": {"effort": DEFAULT_CLAUDE_EFFORT}}, | |
| **inner_kwargs, | |
| ) | |
| def _is_extended_cache_error(err: BaseException) -> bool: | |
| msg = str(err).lower() | |
| return ( | |
| "extended-cache-ttl" in msg | |
| or ("ttl" in msg and "1h" in msg) | |
| or ("extended-cache" in msg and "beta" in msg) | |
| ) | |
| def _capture_usage(stream) -> None: | |
| final_msg = stream.get_final_message() | |
| u = final_msg.usage | |
| self.last_usage = { | |
| "input_tokens": getattr(u, "input_tokens", 0) or 0, | |
| "output_tokens": getattr(u, "output_tokens", 0) or 0, | |
| "cache_creation_input_tokens": getattr(u, "cache_creation_input_tokens", 0) or 0, | |
| "cache_read_input_tokens": getattr(u, "cache_read_input_tokens", 0) or 0, | |
| "cache_ttl_fallback": used_fallback, | |
| } | |
| # The Anthropic SDK's messages.stream() returns a context manager that | |
| # only fires the HTTP request on __enter__. So errors from the API | |
| # surface inside `with stream_cm as stream:`, not during construction. | |
| # We catch APIError around the with-block and retry once on the | |
| # fallback path if the error matches the extended-cache heuristic. | |
| try: | |
| with _open_stream(system_blocks, extra_headers) as stream: | |
| for text in stream.text_stream: | |
| yield text | |
| _capture_usage(stream) | |
| except anthropic.APIError as e: | |
| if session_core_block and _is_extended_cache_error(e): | |
| # Fallback: drop the 1h ttl on the session_core_block (now | |
| # index 0) + the extended-cache beta header. | |
| fallback_blocks = [dict(b) for b in system_blocks] | |
| fallback_blocks[0]["cache_control"] = {"type": "ephemeral"} | |
| fallback_headers = dict(extra_headers) | |
| beta = fallback_headers.get("anthropic-beta", "") | |
| fallback_headers["anthropic-beta"] = ",".join( | |
| h for h in beta.split(",") | |
| if h and "extended-cache-ttl" not in h | |
| ) | |
| if not fallback_headers["anthropic-beta"]: | |
| fallback_headers.pop("anthropic-beta", None) | |
| used_fallback = True | |
| try: | |
| with _open_stream(fallback_blocks, fallback_headers) as stream: | |
| for text in stream.text_stream: | |
| yield text | |
| _capture_usage(stream) | |
| except anthropic.APIError as e2: | |
| raise ClaudeApiError(f"Anthropic API call failed: {e2}") from e2 | |
| else: | |
| raise ClaudeApiError(f"Anthropic API call failed: {e}") from e | |
| def _add_history_cache_marker(messages: list[dict]) -> list[dict]: | |
| """Return a copy of messages with cache_control on the most recent | |
| assistant message's content block. | |
| Caches the entire conversation prefix up through that message. The newest | |
| user message (last in the list) is unmarked, so it pays full input rate; | |
| everything before it bills at the cached-read rate (~10% of input) on | |
| subsequent calls within the cache TTL (5 minutes default). | |
| No-op on the first turn (no assistant message yet). | |
| """ | |
| last_assistant_idx = -1 | |
| for i, msg in enumerate(messages): | |
| if msg.get("role") == "assistant": | |
| last_assistant_idx = i | |
| if last_assistant_idx < 0: | |
| return list(messages) | |
| out: list[dict] = [] | |
| for i, msg in enumerate(messages): | |
| if i != last_assistant_idx: | |
| out.append(msg) | |
| continue | |
| content = msg.get("content", "") | |
| if isinstance(content, str): | |
| blocks = [ | |
| {"type": "text", "text": content, | |
| "cache_control": {"type": "ephemeral"}} | |
| ] | |
| else: | |
| # Already a list of blocks; copy and add cache_control to the last. | |
| blocks = [dict(b) for b in content] | |
| if blocks: | |
| blocks[-1]["cache_control"] = {"type": "ephemeral"} | |
| out.append({**msg, "content": blocks}) | |
| return out | |
| class HaikuClient: | |
| """Non-streaming Anthropic SDK wrapper for short utility calls (QueryPlanner).""" | |
| def __init__(self, model: str | None = None) -> None: | |
| if not os.environ.get("ANTHROPIC_API_KEY"): | |
| raise MissingAnthropicKeyError( | |
| "ANTHROPIC_API_KEY not set. The chat application requires it. " | |
| "Set ANTHROPIC_API_KEY (see `me-hub-bootstrap`)." | |
| ) | |
| self.model = ( | |
| model | |
| or os.environ.get("CLAUDE_QUERY_PLANNER_MODEL") | |
| or _DEFAULT_HAIKU_MODEL | |
| ) | |
| def complete(self, system: str, prompt: str) -> str: | |
| """Return the full text response. Raises ClaudeApiError on failure.""" | |
| try: | |
| import anthropic | |
| except ImportError as e: | |
| raise ClaudeApiError( | |
| "anthropic SDK not installed; run `pip install -r requirements.txt`" | |
| ) from e | |
| client = anthropic.Anthropic() | |
| try: | |
| resp = client.messages.create( | |
| model=self.model, | |
| max_tokens=512, | |
| system=system, | |
| messages=[{"role": "user", "content": prompt}], | |
| ) | |
| return "".join(b.text for b in resp.content if hasattr(b, "text")) | |
| except anthropic.APIError as e: | |
| raise ClaudeApiError(f"Anthropic API call failed: {e}") from e | |