pricing.py 3.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. }
  22. def seed_default_pricing() -> int:
  23. """把种子单价写入单价表;已存在的模型不动。返回新写入条数。"""
  24. created = 0
  25. for model, (input_price, output_price) in SEED_PRICING.items():
  26. if billing_store.get_pricing(model) is None:
  27. billing_store.set_pricing(model, input_price, output_price)
  28. created += 1
  29. # 当前配置的主模型必须在表内,否则首轮就会 fail-closed
  30. for model in {config.MODEL}:
  31. if model and billing_store.get_pricing(model) is None:
  32. billing_store.set_pricing(model, 0.0, 0.0)
  33. created += 1
  34. logger.warning(
  35. "模型 %s 未在种子单价表中,已按 0 价登记——上线前请补真实单价", model
  36. )
  37. if created:
  38. logger.info("单价表初始化:新写入 %d 条", created)
  39. return created
  40. def compute_cost(model: str, input_tokens: int, output_tokens: int) -> tuple[float, str]:
  41. """按单价表算本轮费用。
  42. 返回 ``(cost, currency)``。模型未定价时:
  43. - 默认 fail-closed —— 抛 :class:`UnpricedModelError`,避免「静默免费」
  44. - ``BILLING_ALLOW_UNPRICED=1`` 时降级为 0 价并告警(便于本地开发)
  45. """
  46. pricing = billing_store.get_pricing(model)
  47. if pricing is None:
  48. if config.get_bool("BILLING_ALLOW_UNPRICED", False):
  49. logger.warning("模型 %s 未定价,按 0 计费(BILLING_ALLOW_UNPRICED=1)", model)
  50. return 0.0, "CNY"
  51. raise UnpricedModelError(
  52. f"模型 {model!r} 未在 billing_pricing 表中定价;"
  53. f"请补单价,或设 BILLING_ALLOW_UNPRICED=1 临时按 0 计费"
  54. )
  55. input_price = float(pricing.get("input_price") or 0)
  56. output_price = float(pricing.get("output_price") or 0)
  57. cost = (int(input_tokens) / 1000.0) * input_price + (
  58. int(output_tokens) / 1000.0
  59. ) * output_price
  60. return round(cost, 8), str(pricing.get("currency") or "CNY")
  61. def pricing_table() -> list[dict]:
  62. """当前单价表(供 /api/usage 展示)。"""
  63. rows = billing_store.list_pricing()
  64. return [
  65. {
  66. "model": row.get("model"),
  67. "input_price": float(row.get("input_price") or 0),
  68. "output_price": float(row.get("output_price") or 0),
  69. "currency": row.get("currency"),
  70. "updated_at": row.get("updated_at"),
  71. }
  72. for row in rows
  73. ]
  74. __all__ = [
  75. "SEED_PRICING",
  76. "UnpricedModelError",
  77. "compute_cost",
  78. "pricing_table",
  79. "seed_default_pricing",
  80. "db_conn",
  81. ]