__init__.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. """Native Anthropic provider profile."""
  2. import json
  3. import logging
  4. import urllib.request
  5. from hermes_cli.urllib_security import open_credentialed_url
  6. from providers import register_provider
  7. from providers.base import ProviderProfile
  8. logger = logging.getLogger(__name__)
  9. class AnthropicProfile(ProviderProfile):
  10. """Native Anthropic — uses x-api-key header, not Bearer."""
  11. def fetch_models(
  12. self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0
  13. ) -> list[str] | None:
  14. """Anthropic uses x-api-key header and anthropic-version. ``/v1/models`` is cursor-paginated
  15. (default page 20, smaller than the live catalog), so follow ``has_more``/``last_id``."""
  16. if not api_key:
  17. return None
  18. from hermes_cli.models import _ANTHROPIC_MODELS_MAX_PAGES, _anthropic_models_url, _anthropic_next_cursor
  19. def _page(after_id: str | None):
  20. req = urllib.request.Request(_anthropic_models_url(base_url, after_id=after_id))
  21. for k, v in (("x-api-key", api_key), ("anthropic-version", "2023-06-01"), ("Accept", "application/json")):
  22. req.add_header(k, v)
  23. with open_credentialed_url(req, timeout=timeout) as resp:
  24. return json.loads(resp.read().decode())
  25. try:
  26. models: list[str] = []
  27. seen_cursors: set[str] = set()
  28. cursor: str | None = None
  29. for _ in range(_ANTHROPIC_MODELS_MAX_PAGES):
  30. data = _page(cursor)
  31. models.extend(m["id"] for m in data.get("data", []) if isinstance(m, dict) and "id" in m)
  32. cursor = _anthropic_next_cursor(data, seen_cursors)
  33. if cursor is None:
  34. break
  35. return list(dict.fromkeys(models))
  36. except Exception as exc:
  37. logger.debug("fetch_models(anthropic): %s", exc)
  38. return None
  39. anthropic = AnthropicProfile(
  40. name="anthropic", aliases=("claude", "claude-oauth", "claude-code"), api_mode="anthropic_messages",
  41. env_vars=("ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"),
  42. base_url="https://api.anthropic.com", auth_type="api_key", default_aux_model="claude-haiku-4-5-20251001",
  43. )
  44. register_provider(anthropic)