billing_links.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """Provider-agnostic billing/credit recovery links for billing-classified failures.
  2. Detection lives in :mod:`agent.error_classifier` (``FailoverReason.billing``); the
  3. :class:`BillingBlock` rides the turn result and the gateway ``message.complete`` event
  4. so every surface renders one structured signal instead of re-parsing error text.
  5. """
  6. from __future__ import annotations
  7. from dataclasses import asdict, dataclass
  8. from typing import Optional
  9. from utils import base_url_host_matches
  10. @dataclass
  11. class BillingBlock:
  12. """Structured billing-wall descriptor shared across every surface. ``is_nous`` is the routing bit:
  13. Nous has an in-app billing surface (Settings → Billing, ``/topup``) preferred over ``billing_url``;
  14. third-party providers have none, so ``billing_url`` is the deep link needed."""
  15. provider: str
  16. provider_label: str
  17. model: str
  18. billing_url: Optional[str]
  19. is_nous: bool
  20. message: str
  21. def to_dict(self) -> dict:
  22. return asdict(self)
  23. @dataclass(frozen=True)
  24. class _Provider:
  25. label: str
  26. url: str
  27. slugs: tuple[str, ...]
  28. hosts: tuple[str, ...] = ()
  29. # Single source of truth: slug(s) + base_url host(s) → curated "add credits" page.
  30. # Hosts back the OpenAI-compatible fallback where the slug is a generic bucket but
  31. # base_url reveals the real upstream. Unknown providers get a readable label, no URL.
  32. _PROVIDERS: tuple[_Provider, ...] = (
  33. _Provider("OpenAI", "https://platform.openai.com/settings/organization/billing", ("openai",), ("api.openai.com",)),
  34. _Provider("Anthropic", "https://console.anthropic.com/settings/billing", ("anthropic",), ("api.anthropic.com",)),
  35. _Provider("OpenRouter", "https://openrouter.ai/settings/credits", ("openrouter",), ("openrouter.ai",)),
  36. _Provider("xAI", "https://console.x.ai/team/default/billing", ("xai", "xai-oauth"), ("api.x.ai",)),
  37. _Provider("DeepSeek", "https://platform.deepseek.com/top_up", ("deepseek",), ("api.deepseek.com",)),
  38. _Provider("Groq", "https://console.groq.com/settings/billing", ("groq",), ("api.groq.com",)),
  39. _Provider("Mistral", "https://console.mistral.ai/billing", ("mistral",), ("api.mistral.ai",)),
  40. _Provider("Together AI", "https://api.together.ai/settings/billing", ("together",), ("api.together.ai", "api.together.xyz")),
  41. _Provider("Fireworks AI", "https://fireworks.ai/account/billing", ("fireworks",), ("fireworks.ai",)),
  42. _Provider("Perplexity", "https://www.perplexity.ai/settings/api", ("perplexity",), ("perplexity.ai",)),
  43. _Provider("Google AI", "https://aistudio.google.com/app/billing", ("google", "gemini"), ("generativelanguage.googleapis.com",)),
  44. _Provider("Cohere", "https://dashboard.cohere.com/billing", ("cohere",)),
  45. _Provider("Moonshot AI", "https://platform.moonshot.ai/console/pay", ("moonshot",)),
  46. _Provider("NVIDIA", "https://build.nvidia.com/settings/billing", ("nvidia",)),
  47. )
  48. _BY_SLUG: dict[str, _Provider] = {slug: p for p in _PROVIDERS for slug in p.slugs}
  49. def is_nous_inference_route(provider: str, base_url: str) -> bool:
  50. """True when the failing route is the Nous-managed inference gateway."""
  51. return (provider or "").strip().lower() == "nous" or base_url_host_matches(str(base_url or ""), "inference-api.nousresearch.com")
  52. def _nous_billing_url() -> Optional[str]:
  53. """Best-effort Nous portal billing URL (text-surface fallback; Nous prefers the in-app flow)."""
  54. try:
  55. from hermes_cli.nous_account import nous_portal_billing_url
  56. return nous_portal_billing_url(None)
  57. except Exception:
  58. return "https://portal.nousresearch.com/billing"
  59. def _resolve_provider_link(slug: str, base_url: str) -> tuple[str, Optional[str]]:
  60. """Resolve ``(label, url)``: exact slug → base_url host → readable-label fallback."""
  61. base = str(base_url or "")
  62. hit = _BY_SLUG.get(slug) or next(
  63. (p for p in _PROVIDERS if any(base_url_host_matches(base, host) for host in p.hosts)), None
  64. )
  65. if hit:
  66. return hit.label, hit.url
  67. return slug.replace("_", " ").replace("-", " ").strip().title() or "your provider", None
  68. def build_billing_block(*, provider: str, base_url: str, model: str, message: str = "") -> BillingBlock:
  69. """Billing descriptor for a billing-classified failure; ``message`` (agent-loop guidance) passes through unchanged."""
  70. slug = (provider or "").strip().lower()
  71. model = (model or "").strip()
  72. if is_nous_inference_route(slug, base_url):
  73. return BillingBlock(slug or "nous", "Nous Portal", model, _nous_billing_url(), True, message or "")
  74. label, url = _resolve_provider_link(slug, base_url)
  75. return BillingBlock(slug, label, model, url, False, message or "")