Skip to content

Self-improving AI Employees for everyone

21.3 KB
Raw Blame
"""Anthropic native provider using the official `anthropic` Python SDK."""

from __future__ import annotations

from typing import Any, Dict, List, Mapping, Optional

from core.logging import get_logger
from services.llm.observation import observe_response, observe_sdk_request, observe_stage
from services.llm.protocol import (
    ContentBlock,
    decode_binary_state,
    encode_binary_state,
    LLMResponse,
    Message,
    StreamEvent,
    StreamSink,
    ThinkingConfig,
    ToolCall,
    ToolDef,
    Usage,
)

logger = get_logger(__name__)


class AnthropicProvider:
    provider_name = "anthropic"

    def __init__(
        self,
        api_key: str,
        *,
        proxy_url: Optional[str] = None,
        max_retries: int = 2,
    ):
        import anthropic

        kwargs: Dict[str, Any] = {
            "api_key": api_key,
            "max_retries": max(0, int(max_retries)),
        }
        if proxy_url:
            kwargs["base_url"] = proxy_url
        self._client = anthropic.AsyncAnthropic(**kwargs)

    # ------------------------------------------------------------------
    # chat
    # ------------------------------------------------------------------

    async def chat(
        self,
        messages: List[Message],
        *,
        model: str,
        temperature: float = 0.7,
        max_tokens: int = 4096,
        thinking: Optional[ThinkingConfig] = None,
        tools: Optional[List[ToolDef]] = None,
        context_management: Optional[Dict[str, Any]] = None,
        on_event: Optional[StreamSink] = None,
        effort: Optional[str] = None,
        extra_headers: Optional[Mapping[str, str]] = None,
        extra_body: Optional[Mapping[str, Any]] = None,
    ) -> LLMResponse:
        observe_stage("request_encoding")
        system, api_msgs = self._split_system(messages)
        policy = self._model_policy(model)

        params: Dict[str, Any] = {
            "model": model,
            "messages": api_msgs,
            "max_tokens": max_tokens,
        }
        if system:
            params["system"] = system

        thinking_on = bool(thinking and thinking.enabled)
        betas: List[str] = []

        if policy["adaptive_thinking"]:
            # ``budget_tokens`` was removed on these generations and is a 400,
            # not a warning — the model chooses its own depth.  ``disabled`` is
            # itself rejected on Fable/Mythos, so "thinking off" is expressed by
            # omitting the field and letting the model's own default stand.
            if thinking_on:
                params["thinking"] = {
                    "type": "adaptive",
                    # ``display`` defaults to "omitted" here, which would empty
                    # the reasoning text the node publishes downstream.
                    "display": "summarized",
                }
        elif thinking_on:
            budget = max(1024, int(thinking.budget or 2048))
            if max_tokens <= budget:
                params["max_tokens"] = budget + 1024
            params["thinking"] = {"type": "enabled", "budget_tokens": budget}

        if policy["thinking_prefix_binding"]:
            # Context can deliberately change between delegated missions or
            # at client-side compaction. New Claude models bind thinking to
            # that prefix. Let the API discard only incompatible reasoning,
            # preserving the signed history locally and valid blocks in tool
            # loops. Dropped reasoning can increase output-token usage.
            # The pinned SDK passes this beta field through unchanged.
            params.setdefault("thinking", {"type": "adaptive"})[
                "block_binding"
            ] = {"prefix_mismatch_behavior": "drop_block"}
            betas.append("thinking-binding-controls-2026-08-01")

        if policy["sampling_params"]:
            # Anthropic requires temperature=1 alongside budget thinking.
            params["temperature"] = 1 if thinking_on else temperature

        if effort:
            # The owner's chat choice (Quick / Thorough): how much the model
            # spends on the answer, thinking or not. Only the effort_models
            # receive one (ChatUnifier).
            params["output_config"] = {"effort": effort}

        # Tools
        if tools:
            params["tools"] = [self._to_api_tool(t) for t in tools]

        # Per-request extras: the LLM gateway's attribution headers and
        # replay-cache body (ChatUnifier sends them for gateway calls only).
        headers = dict(extra_headers or {})
        # The beta SDK lets extra_headers overwrite its generated beta header.
        # Combine caller betas first, including differently cased headers, so
        # gateway attribution and every requested capability survive.
        for name in list(headers):
            if name.lower() == "anthropic-beta":
                betas.extend(value.strip() for value in headers.pop(name).split(",") if value.strip())
        if headers:
            params["extra_headers"] = headers
        if extra_body:
            params["extra_body"] = dict(extra_body)

        # Always stream.  The SDK refuses a non-streaming request whose
        # ``max_tokens`` implies more than ten minutes of generation
        # (``_calculate_nonstreaming_timeout``), and ``resolve_max_tokens``
        # hands us the model's full output cap — 128K on every current
        # Claude model — so the plain ``create()`` path raises
        # ``ValueError: Streaming is required ...`` before the request is
        # ever sent.  ``get_final_message()`` returns the same accumulated
        # ``Message`` the non-streaming call would have, so ``_normalize``
        # is unaffected.
        if (
            isinstance(context_management, dict)
            and context_management.get("type") == "compaction"
        ):
            threshold = int(
                context_management.get("compact_threshold") or 0
            )
            edit: Dict[str, Any] = {
                "type": "compact_20260112",
                "pause_after_compaction": bool(
                    context_management.get("pause_after_compaction")
                ),
            }
            if threshold >= 50_000:
                edit["trigger"] = {
                    "type": "input_tokens",
                    "value": threshold,
                }
            betas.append("compact-2026-01-12")
            params["context_management"] = {"edits": [edit]}

        if betas:
            stream_ctx = self._client.beta.messages.stream(
                betas=list(dict.fromkeys(betas)), **params
            )
        else:
            stream_ctx = self._client.messages.stream(**params)

        observe_sdk_request(self)
        async with stream_ctx as stream:
            if on_event is not None:
                # The SDK's helper events carry each delta once (the raw
                # ``content_block_delta`` they come from is skipped), and
                # ``get_final_message`` still returns the accumulated message.
                async for event in stream:
                    kind = getattr(event, "type", None)
                    if kind == "text":
                        delta = getattr(event, "text", "") or ""
                        if delta:
                            await on_event(StreamEvent("text", delta))
                    elif kind == "thinking":
                        delta = getattr(event, "thinking", "") or ""
                        if delta:
                            await on_event(StreamEvent("reasoning", delta))
            resp = await stream.get_final_message()
        observe_response(resp)
        return self._normalize(resp, model)

    # ------------------------------------------------------------------
    # fetch_models
    # ------------------------------------------------------------------

    async def fetch_models(self, api_key: str) -> List[str]:
        import httpx

        async with httpx.AsyncClient() as client:
            r = await client.get(
                "https://api.anthropic.com/v1/models",
                headers={"x-api-key": api_key, "anthropic-version": "2023-06-01"},
                timeout=15.0,
            )
            r.raise_for_status()
            data = r.json()
        return sorted([m["id"] for m in data.get("data", [])])

    # ------------------------------------------------------------------
    # internals
    # ------------------------------------------------------------------

    def _model_policy(self, model: str) -> Dict[str, bool]:
        """Resolve JSON-driven per-model request-shape quirks.

        Mirrors ``OpenAIProvider._model_policy``: the model families that
        dropped sampling parameters and the ``budget_tokens`` thinking form
        are listed in ``llm_defaults.json`` rather than hardcoded here, so a
        new Claude generation is a config edit.
        """

        from services.llm.config import LLM_DEFAULTS

        config = LLM_DEFAULTS.get("providers", {}).get(self.provider_name, {})

        def matches(key: str) -> bool:
            return any(
                model.startswith(prefix) or prefix in model
                for prefix in config.get(key, ())
            )

        return {
            "adaptive_thinking": matches("adaptive_thinking_models"),
            "sampling_params": not matches("sampling_params_removed"),
            "thinking_prefix_binding": matches("thinking_prefix_binding_models"),
        }

    def _split_system(self, messages: List[Message]):
        """Extract system message (Anthropic takes it as a top-level param)."""
        system_parts = []
        api_msgs = []
        index = 0
        while index < len(messages):
            m = messages[index]
            if m.role == "system":
                if m.content:
                    system_parts.append(m.content)
                index += 1
                continue

            if m.role == "tool":
                # A parallel Anthropic tool-use turn must be answered by one
                # user message containing every corresponding tool_result
                # block.  Keep normalized messages provider-neutral and
                # coalesce their consecutive run only while compiling the
                # request.
                result_blocks: List[Dict[str, Any]] = []
                while index < len(messages) and messages[index].role == "tool":
                    tool_message = messages[index]
                    result_blocks.append(
                        {
                            "type": "tool_result",
                            "tool_use_id": tool_message.tool_call_id or "",
                            "content": self._tool_result_content(tool_message),
                        }
                    )
                    index += 1
                api_msgs.append({"role": "user", "content": result_blocks})
                continue

            api_msgs.append(self._to_api_message(m))
            index += 1
        return "\n\n".join(system_parts) if system_parts else None, api_msgs

    @staticmethod
    def _tool_result_content(m: Message) -> Any:
        """Anthropic tool_result content: plain string, or a block list when
        hydrated images ride along (the documented image-in-tool-result
        shape). Ref-only blocks render nothing here — hydration either
        produced bytes or a text placeholder before compile time."""
        images = AnthropicProvider._image_parts(m)
        if not images:
            return m.content
        return [{"type": "text", "text": m.content}, *images]

    @staticmethod
    def _image_parts(m: Message) -> List[Dict[str, Any]]:
        """The message's hydrated images as Anthropic image blocks."""
        return [
            {
                "type": "image",
                "source": {
                    "type": "base64",
                    "media_type": block.source["media_type"],
                    "data": block.source["data_b64"],
                },
            }
            for block in m.blocks or []
            if block.type == "image"
            and isinstance(block.source, dict)
            and block.source.get("kind") == "bytes"
        ]

    def _to_api_message(self, m: Message) -> Dict[str, Any]:
        role = "assistant" if m.role == "assistant" else "user"

        if m.role == "tool":
            return {
                "role": "user",
                "content": [
                    {
                        "type": "tool_result",
                        "tool_use_id": m.tool_call_id or "",
                        "content": self._tool_result_content(m),
                    }
                ],
            }

        if m.role == "assistant":
            state = m.provider_state
            if state.get("provider") == self.provider_name:
                payload = state.get("payload")
                if isinstance(payload, dict) and isinstance(
                    payload.get("content"), list
                ):
                    return {
                        "role": "assistant",
                        "content": [
                            self._state_block_to_api(block)
                            for block in payload["content"]
                            if isinstance(block, dict)
                        ],
                    }

        if m.role == "assistant" and m.tool_calls:
            content: List[Dict[str, Any]] = []
            if m.content:
                content.append({"type": "text", "text": m.content})
            for tc in m.tool_calls:
                content.append(
                    {
                        "type": "tool_use",
                        "id": tc.id,
                        "name": tc.name,
                        "input": tc.args,
                    }
                )
            return {"role": "assistant", "content": content}

        images = self._image_parts(m) if m.role == "user" else []
        if images:
            # Images the owner attached, ahead of their words (Anthropic's
            # recommended order).
            text = [{"type": "text", "text": m.content}] if m.content else []
            return {"role": "user", "content": [*images, *text]}
        return {"role": role, "content": m.content}

    @staticmethod
    def _to_api_tool(tool: ToolDef) -> Dict[str, Any]:
        from services.llm.schema import compile_tool_schema

        return {
            "name": tool.name,
            "description": tool.description,
            "input_schema": compile_tool_schema(
                tool.parameters, provider="anthropic"
            ),
        }

    def _normalize(self, resp: Any, model: str) -> LLMResponse:
        text_parts = []
        thinking_parts = []
        tool_calls = []
        blocks: List[ContentBlock] = []
        provider_blocks: List[Dict[str, Any]] = []

        for block in resp.content:
            if block.type == "text":
                text_parts.append(block.text)
                blocks.append(ContentBlock(type="text", text=block.text))
                provider_blocks.append({"type": "text", "text": block.text})
            elif block.type == "thinking":
                thinking_parts.append(block.thinking)
                metadata: Dict[str, Any] = {}
                provider_block: Dict[str, Any] = {
                    "type": "thinking",
                    "thinking": block.thinking,
                }
                signature = getattr(block, "signature", None)
                if isinstance(
                    signature, (str, bytes, bytearray, memoryview)
                ):
                    durable_signature = encode_binary_state(signature)
                    metadata["signature"] = durable_signature
                    provider_block["signature"] = durable_signature
                blocks.append(
                    ContentBlock(
                        type="reasoning",
                        text=block.thinking,
                        metadata=metadata,
                    )
                )
                provider_blocks.append(provider_block)
            elif block.type == "redacted_thinking":
                data = getattr(block, "data", "")
                if isinstance(data, (bytes, bytearray, memoryview)):
                    data = encode_binary_state(data)
                elif not isinstance(data, str):
                    data = str(data)
                blocks.append(
                    ContentBlock(
                        type="reasoning",
                        metadata={"redacted": True},
                    )
                )
                provider_blocks.append(
                    {"type": "redacted_thinking", "data": data}
                )
            elif block.type == "tool_use":
                call = ToolCall.from_raw(
                    id=block.id,
                    name=block.name,
                    arguments=block.input,
                )
                tool_calls.append(call)
                blocks.append(ContentBlock(type="tool_call", tool_call=call))
                provider_blocks.append(
                    {
                        "type": "tool_use",
                        "id": block.id,
                        "name": block.name,
                        "input": (
                            block.input
                            if isinstance(
                                block.input,
                                (dict, list, str, int, float, bool, type(None)),
                            )
                            else str(block.input)
                        ),
                    }
                )
            elif block.type == "compaction":
                summary = getattr(block, "content", "")
                if not isinstance(summary, str):
                    summary = str(summary or "")
                blocks.append(
                    ContentBlock(type="compaction", text=summary)
                )
                provider_blocks.append(
                    {"type": "compaction", "content": summary}
                )

        input_tokens = getattr(resp.usage, "input_tokens", 0) or 0
        output_tokens = getattr(resp.usage, "output_tokens", 0) or 0
        cache_creation_tokens = (
            getattr(resp.usage, "cache_creation_input_tokens", 0) or 0
        )
        cache_read_tokens = (
            getattr(resp.usage, "cache_read_input_tokens", 0) or 0
        )
        usage = Usage(
            input_tokens=input_tokens,
            output_tokens=output_tokens,
            total_tokens=(
                input_tokens
                + cache_creation_tokens
                + cache_read_tokens
                + output_tokens
            ),
            cache_creation_tokens=cache_creation_tokens,
            cache_read_tokens=cache_read_tokens,
        )
        iterations = getattr(resp.usage, "iterations", None) or ()
        billed_input = 0
        billed_output = 0
        for iteration in iterations:
            billed_input += int(
                getattr(iteration, "input_tokens", 0) or 0
            )
            billed_output += int(
                getattr(iteration, "output_tokens", 0) or 0
            )
        billing_usage = (
            Usage(
                input_tokens=billed_input,
                output_tokens=billed_output,
                total_tokens=billed_input + billed_output,
            )
            if billed_input or billed_output
            else usage
        )

        content = "\n".join(text_parts)
        thinking = "\n\n".join(thinking_parts) if thinking_parts else None
        assistant_message = Message(
            role="assistant",
            content=content,
            tool_calls=tool_calls,
            blocks=blocks,
            provider_state={
                "provider": self.provider_name,
                "payload": {"content": provider_blocks},
            },
        )
        return LLMResponse(
            content=content,
            thinking=thinking,
            tool_calls=tool_calls,
            usage=usage,
            billing_usage=billing_usage,
            model=model,
            finish_reason=resp.stop_reason or "stop",
            raw=resp,
            assistant_message=assistant_message,
        )

    @staticmethod
    def _state_block_to_api(block: Dict[str, Any]) -> Dict[str, Any]:
        """Rehydrate only the binary fields Anthropic returned originally."""

        result = dict(block)
        if result.get("type") == "thinking" and "signature" in result:
            result["signature"] = decode_binary_state(result["signature"])
        elif (
            result.get("type") == "redacted_thinking"
            and "data" in result
        ):
            result["data"] = decode_binary_state(result["data"])
        return result

    async def aclose(self) -> None:
        close = getattr(self._client, "close", None)
        if close is not None:
            result = close()
            if hasattr(result, "__await__"):
                await result


# ---------------------------------------------------------------------------
# Plugin self-registration
# ---------------------------------------------------------------------------
# Module load triggers registration into the global ProviderRegistry.
# The typed ``APIError`` class is declared as a lazy "module:Class" ref
# (resolved via ``pkgutil.resolve_name`` at except/read time) so that
# registration never imports the SDK — the eager import here used to
# cost seconds of boot time (docs-internal/performance.md).

from services.llm.registry import ProviderSpec, register_provider

register_provider(
    ProviderSpec(
        name="anthropic",
        factory=AnthropicProvider,
        sdk_exception_refs=("anthropic:APIError",),
    )
)