pricing.py 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. """模型单价与费用计算。
  2. 单价含义:每 1K token 的价格(与 config 表 billing_pricing 的列注释一致)。
  3. 骨架自带一组种子单价,启动时写入 billing_pricing(不覆盖已存在的人工调价)。
  4. """
  5. from __future__ import annotations
  6. import config
  7. from db import billing_store, db_conn
  8. from obs import get_logger
  9. logger = get_logger(__name__)
  10. class UnpricedModelError(RuntimeError):
  11. """模型在 billing_pricing 里没有单价,且不允许按 0 计费。"""
  12. # 种子单价:仅为了让骨架开箱可算费,**不是**真实报价,上线前必须按实际
  13. # 供应商账单校准。单位:元 / 1K token。
  14. SEED_PRICING: dict[str, tuple[float, float]] = {
  15. "deepseek-flash": (0.0005, 0.0015),
  16. "deepseek-v4-flash": (0.0005, 0.0015),
  17. "deepseek-v4-pro": (0.002, 0.008),
  18. "deepseek-chat": (0.001, 0.002),
  19. "deepseek-reasoner": (0.001, 0.002),
  20. "gpt-4o-mini": (0.001, 0.004),
  21. # 用户提供的平台报价:输入 0.4 元 / M,输出 3.2 元 / M,换算为每 1K token。
  22. "qwen3.5-35b-a3b": (0.0004, 0.0032),
  23. }
  24. def seed_default_pricing() -> int:
  25. """把种子单价写入单价表;已存在的模型不动。返回新写入条数。"""
  26. created = 0
  27. for model, (input_price, output_price) in SEED_PRICING.items():
  28. if billing_store.get_pricing(model) is None:
  29. billing_store.set_pricing(model, input_price, output_price)
  30. created += 1
  31. if created:
  32. logger.info("单价表初始化:新写入 %d 条", created)
  33. return created
  34. def compute_cost(model: str, input_tokens: int, output_tokens: int) -> tuple[float, str]:
  35. """按单价表算本轮费用。
  36. 返回 ``(cost, currency)``。模型未定价时:
  37. - 默认 fail-closed —— 抛 :class:`UnpricedModelError`,避免「静默免费」
  38. - ``BILLING_ALLOW_UNPRICED=1`` 时降级为 0 价并告警(便于本地开发)
  39. """
  40. pricing = billing_store.get_pricing(model)
  41. if pricing is None:
  42. if config.get_bool("BILLING_ALLOW_UNPRICED", False):
  43. logger.warning("模型 %s 未定价,按 0 计费(BILLING_ALLOW_UNPRICED=1)", model)
  44. return 0.0, "CNY"
  45. raise UnpricedModelError(
  46. f"模型 {model!r} 未在 billing_pricing 表中定价;"
  47. f"请补单价,或设 BILLING_ALLOW_UNPRICED=1 临时按 0 计费"
  48. )
  49. input_price = float(pricing.get("input_price") or 0)
  50. output_price = float(pricing.get("output_price") or 0)
  51. cost = (int(input_tokens) / 1000.0) * input_price + (
  52. int(output_tokens) / 1000.0
  53. ) * output_price
  54. return round(cost, 8), str(pricing.get("currency") or "CNY")
  55. def pricing_table() -> list[dict]:
  56. """当前单价表(供 /api/usage 展示)。"""
  57. rows = billing_store.list_pricing()
  58. return [
  59. {
  60. "model": row.get("model"),
  61. "input_price": float(row.get("input_price") or 0),
  62. "output_price": float(row.get("output_price") or 0),
  63. "currency": row.get("currency"),
  64. "updated_at": row.get("updated_at"),
  65. }
  66. for row in rows
  67. ]
  68. __all__ = [
  69. "SEED_PRICING",
  70. "UnpricedModelError",
  71. "compute_cost",
  72. "pricing_table",
  73. "seed_default_pricing",
  74. "db_conn",
  75. ]