指南
成本优化
本指南介绍如何通过 BYOKS 的功能降低 API 调用成本。
成本优化策略
1. 使用成本路由
自动选择最便宜的 Provider:
{
"strategy": "cost",
"maxLatency": 5000
}BYOKS 会在满足延迟要求的前提下,选择价格最低的 Provider。
2. 启用响应缓存
对于重复的请求,返回缓存响应:
{
"cache": {
"enabled": true,
"ttl": 3600
}
}适用场景:
- 常见问题回答
- 固定的提示词
- 重复的分析任务
节省效果:缓存命中时,Token 成本为 0。
3. 选择合适的模型
不同任务使用不同模型:
| 任务类型 | 推荐模型 | 相对成本 |
|---|---|---|
| 简单问答 | gpt-3.5-turbo | $ |
| 一般任务 | gpt-4o-mini | $$ |
| 复杂推理 | gpt-4o | $$$ |
| 最强能力 | claude-3-opus | $$$$ |
使用模型映射简化管理
{
"modelMapping": {
"cheap": "gpt-3.5-turbo",
"balanced": "gpt-4o-mini",
"smart": "gpt-4o"
}
}// 简单任务用便宜模型
const simple = await client.chat.completions.create({
model: 'cheap',
messages: [...],
});
// 复杂任务用强模型
const complex = await client.chat.completions.create({
model: 'smart',
messages: [...],
});4. 优化 Prompt
减少输入 Token
// 不推荐:冗长的 prompt
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'system',
content: '你是一个非常有帮助的AI助手,你会尽可能详细、准确、全面地回答用户的问题...',
},
// ... 很长的上下文
],
});
// 推荐:精简的 prompt
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{
role: 'system',
content: '简洁回答。',
},
// ... 精简的上下文
],
});限制输出长度
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [...],
max_tokens: 500, // 限制输出长度
});5. 使用第三方 Provider
部分第三方 Provider 可能提供更低的价格:
const response = await client.chat.completions.create({
model: 'gpt-4o@cheap-provider', // 指定便宜的 Provider
messages: [...],
});使用第三方 Provider 时,数据会经过第三方。请权衡成本和安全。
成本监控
Dashboard 查看
在 Dashboard 中可以查看:
- 每日/每月成本
- 按模型分类的成本
- 按 Provider 分类的成本
API 获取用量
每次响应都包含用量信息:
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [...],
});
console.log('Token 用量:', response.usage);
// { prompt_tokens: 10, completion_tokens: 50, total_tokens: 60 }估算成本
function estimateCost(usage, pricePerM) {
const inputCost = (usage.prompt_tokens / 1_000_000) * pricePerM.input;
const outputCost = (usage.completion_tokens / 1_000_000) * pricePerM.output;
return inputCost + outputCost;
}
const cost = estimateCost(response.usage, {
input: 2.50, // $2.50 / 1M input tokens
output: 10.00, // $10.00 / 1M output tokens
});
console.log('预估成本: $', cost.toFixed(6));成本优化检查清单
- 启用响应缓存
- 配置成本路由
- 为不同任务选择合适的模型
- 精简 prompt
- 设置合理的 max_tokens
- 监控每日成本
- 设置成本告警
成本告警
在 Dashboard 中设置成本告警:
{
"alerts": {
"dailyCost": {
"threshold": 10, // 每日超过 $10 告警
"notify": ["email"]
},
"monthlyCost": {
"threshold": 100, // 每月超过 $100 告警
"notify": ["email", "webhook"]
}
}
}实际案例
案例:客服机器人
优化前:
- 模型:gpt-4o
- 无缓存
- 月成本:$500
优化后:
- 简单问题:gpt-3.5-turbo
- 复杂问题:gpt-4o
- 启用缓存(30% 命中率)
- 月成本:$150
节省:70%
案例:内容生成
优化前:
- 所有任务使用 gpt-4o
- 无限制输出长度
- 月成本:$1000
优化后:
- 草稿:gpt-4o-mini
- 精修:gpt-4o
- 限制输出 500 tokens
- 月成本:$400
节省:60%