Logo
Section 1 / 2

基于 OpenRouter 的成本感知开发

通过 OpenRouter 的 Activity 页面和 credits 端点,以编程方式监控 API 使用情况,并通过提示缓存将令牌成本降低高达 90%。本课程涵盖按令牌计价、Anthropic 模型所需的显式 cache_control 语法,以及财务防护措施,包括每密钥支出限额和团队级预算。

导入

基于 OpenRouter 的成本感知开发

通过 OpenRouter 的 Activity 页面和 credits 端点,以编程方式监控 API 使用情况,并通过提示缓存将令牌成本降低高达 90%。本课程涵盖按令牌计价、Anthropic 模型所需的显式 cache_control 语法,以及财务防护措施,包括每密钥支出限额和团队级预算。

...
OpenRouter 活动页面的截图,显示一个包含模型、提示令牌、完成令牌和成本列的表格
提供商启用方式读取成本(缓存)写入成本/条件
OpenAI自动输入的 0.25x – 0.50x免费。需要最小提示大小为 1,024 个令牌。
Google Gemini自动输入的 0.25x免费。需要满足最低令牌阈值。
Anthropic通过 cache_control 显式设置输入的 0.1x5 分钟 TTL:输入的 1.25x。1 小时 TTL:输入的 2.0x。需要满足最低令牌阈值(例如 1,024 或 4,096)。

在 OpenRouter 上为 Anthropic 的 Claude 设置缓存控制

1import os 2import requests 3 4api_key = os.getenv("OPENROUTER_API_KEY") 5 6response = requests.post( 7 url="https://openrouter.ai/api/v1/chat/completions", 8 headers={ 9 "Authorization": f"Bearer {api_key}", 10 "Content-Type": "application/json", 11 }, 12 json={ 13 "model": "anthropic/claude-sonnet-4.6", 14 "messages": [ 15 { 16 "role": "user", 17 "content": [ 18 { 19 "type": "text", 20 "text": "Your long system context or document here...", 21 "cache_control": {"type": "ephemeral"} 22 } 23 ] 24 } 25 ] 26 } 27) 28# ... handle response

模型抽象与路由

比较与基准测试模型