Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

3.1 KB
Raw Blame
"""Claude via the direct Anthropic API (standard API key).

Keyring/ENV: `anthropic_api_key` / `ANTHROPIC_API_KEY`.
"""
from __future__ import annotations

import asyncio
from collections.abc import AsyncIterator
from typing import Any

from dodaios.core import config as cfg
from dodaios.core.protocols import BrainDelta, BrainRequest

from ._anthropic_base import stream_complete

DEFAULT_MODEL = "claude-haiku-4-5-20251001"

#: Required for a Claude login bearer; without it the API treats the bearer as
#: an API key and refuses it.
_OAUTH_BETA = "oauth-2025-04-20"


class ClaudeAPIBrain:
    """Anthropic messages API via API-Key (classical developer path)."""

    name: str = "claude-api"
    context_window: int = 200_000
    supports_tools: bool = True
    supports_vision: bool = True

    def __init__(self, model: str | None = None, *, auth_token: str | None = None) -> None:
        self._model = model or DEFAULT_MODEL
        self._client: Any = None
        #: A Claude login bearer instead of an API key (Hermes / OpenClaw
        #: agents without a key; Anthropic bills it as extra usage).
        self._auth_token = auth_token

    def _ensure_client(self) -> Any:
        if self._client is None and self._auth_token:
            from anthropic import AsyncAnthropic

            self._client = AsyncAnthropic(
                auth_token=self._auth_token,
                default_headers={"anthropic-beta": _OAUTH_BETA},
                max_retries=0,
                timeout=15.0,
            )
        if self._client is None:
            ep = cfg.resolve_provider_endpoint("claude-api")
            if not ep.credential:
                raise RuntimeError(
                    "No Anthropic API key found. Please set one via the wizard or "
                    "ANTHROPIC_API_KEY in the environment."
                )
            from anthropic import AsyncAnthropic
            # max_retries=0 → BrainManager-Fallback greift schneller bei 429
            kwargs: dict[str, Any] = {"api_key": ep.credential, "max_retries": 0, "timeout": 15.0}
            if ep.base_url:
                kwargs["base_url"] = ep.base_url
            self._client = AsyncAnthropic(**kwargs)
        return self._client

    async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
        client = self._client
        if client is None:
            # The first call imports the SDK (pydantic model generation for a
            # few hundred types) and reads the credential store. Done ON the
            # event loop, that import ran for 15 s on a cold disk and stopped
            # every WebSocket, route and turn with it (2026-08-27, BUG-189) —
            # so the one-time construction happens on a worker thread.
            client = await asyncio.to_thread(self._ensure_client)
        async for delta in stream_complete(client, self._model, req):
            yield delta

    def estimate_cost(self, req: BrainRequest) -> float:
        # Rough Claude-Opus estimate: $15/M-in + $75/M-out
        in_tokens = sum(len(str(m.content)) for m in req.messages) // 4
        return (in_tokens * 15 + req.max_tokens * 75) / 1_000_000