> ## Documentation Index
> Fetch the complete documentation index at: https://docs.shannon.run/llms.txt
> Use this file to discover all available pages before exploring further.

# 成本控制

> 在 Shannon 中管理令牌预算和降低 LLM 成本

## 概述

Shannon 提供全面的成本控制功能，以防止意外的 LLM 费用并优化支出。通过内置的预算执行和智能路由，与简单实现相比，通常可实现 **显著的成本降低（60–90%）**（取决于工作负载）。

## 设置预算

预算在平台级别配置（不是通过 REST 每个请求）。在 `.env` 中使用环境变量：

```bash theme={null}
# LLM 服务预算保护
MAX_TOKENS_PER_REQUEST=10000    # 每次请求的最大令牌数
MAX_COST_PER_REQUEST=0.50       # 每次请求的最大成本（美元）

# 应用更改
docker compose restart
```

<Note>
  Shannon 在执行过程中强制预算限制。当达到限制时，系统会停止进一步支出，并根据上下文返回最佳可用结果或错误。
</Note>

## 模型层级

Shannon 根据能力和成本将模型分为不同层级：

| 层级         | 模型                            | 每百万令牌成本         | 用例        |
| ---------- | ----------------------------- | --------------- | --------- |
| **SMALL**  | gpt-5-nano<br />claude-haiku  | $0.15 - $0.25   | 简单查询、高容量  |
| **MEDIUM** | gpt-5-mini<br />claude-sonnet | $3.00 - $15.00  | 通用任务      |
| **LARGE**  | gpt-5.1<br />claude-opus      | $15.00 - $75.00 | 复杂推理、关键任务 |

### 显式层级偏好

通过环境变量设置首选的默认层级：

```bash theme={null}
DEFAULT_MODEL_TIER=small   # small | medium | large
```

## 智能路由器

Shannon 的学习路由器自动选择能够处理每个任务的最便宜模型。

### 工作原理

1. **任务分析**：分析复杂度和所需能力
2. **模型选择**：从最小可行模型开始
3. **质量检查**：验证输出质量
4. **学习**：记住成功的模型-任务配对

### 成本节省

```python theme={null}
# 没有智能路由
传统：始终使用 GPT-5 → 每个任务 $0.50

# 使用 Shannon 的路由
Shannon:
  - 70% 路由到 gpt-5-nano → $0.01
  - 25% 路由到 gpt-5-mini → $0.15
  - 5% 路由到 gpt-5.1 → $0.50
示例平均：每个任务 $0.05（约 90% 节省）
```

### 监控路由器决策

使用仪表板或 SDK 状态查看成本：

```python theme={null}
status = client.wait(handle.task_id)
if status.token_usage:
    print(f"成本（USD）：{status.token_usage.cost_usd:.4f}")
```

## 响应缓存

Shannon 缓存 LLM 响应以消除冗余 API 调用：

### 缓存策略

* **键**：`(messages + model + parameters)` 的 SHA256 哈希
* **TTL**：可配置（通常约 1 小时，通过 Redis TTL）
* **存储**：内存 LRU + 可选 Redis 用于分布式缓存
* **命中率**：生产工作负载通常为 30-50%

### 缓存优势

```bash theme={null}
# 第一次调用：缓存未命中
任务 1："什么是 Python？" → $0.002（LLM 调用）

# 第二次调用：缓存命中
任务 2："什么是 Python？" → $0.000（已缓存）
```

### 监控缓存性能

```python theme={null}
status = client.wait(handle.task_id)
if status.token_usage:
    if status.token_usage.cost_usd == 0:
        print("很可能来自缓存（无 LLM 成本）")
    else:
        print(f"成本：${status.token_usage.cost_usd:.4f}")
```

## 提供商速率限制

Shannon 自动遵守提供商速率限制：

### 配置的限制

来自 `config/models.yaml`：

```yaml theme={null}
providers:
  openai:
    rpm: 10000  # 每分钟请求数
    tpm: 2000000  # 每分钟令牌数
  anthropic:
    rpm: 4000
    tpm: 400000
```

### 自动节流

当接近限制时：

1. 对请求进行排队
2. 随时间分散负载
3. 如果可用，回退到替代提供商

## 成本监控

### 跟踪每个任务的支出

```python theme={null}
status = client.wait(handle.task_id)
if status.token_usage:
    print(f"使用的令牌：{status.token_usage.total_tokens}")
    print(f"成本：${status.token_usage.cost_usd:.4f}")
```

### 聚合指标

Shannon 通过指标管道跟踪累计成本：

* 按天/周/月的总支出
* 按用户/团队的成本
* 按认知模式的成本
* 令牌使用趋势

部署 Prometheus/Grafana 后，可通过监控面板可视化这些指标。桌面应用的运行视图也可以帮助检查单个任务的成本。

## 最佳实践

### 1. 始终设置预算

永远不要在没有预算限制的情况下运行生产任务：

```python theme={null}
# ❌ 不好：无预算限制
client.submit_task(query="...")

# ✅ 好：预算保护
client.submit_task(
    query="...",
    # 通过 .env 配置预算}
)
```

### 2. 尽可能使用简单模式

复杂模式成本更高：

```python theme={null}
# 简单查询：使用简单模式
client.submit_task(
    query="法国的首都是什么？",
    # 自动选择模式  # 单智能体，最少令牌
)

# 复杂查询：使用标准/复杂模式
client.submit_task(
    query="研究并比较 5 种数据库技术",
    # 自动选择模式  # 任务分解是合理的
)
```

### 3. 利用缓存

对于重复查询，使用一致的措辞以最大化缓存命中：

```python theme={null}
# ❌ 不好：不同措辞阻止缓存命中
client.submit_task(query="什么是 Python？")
client.submit_task(query="告诉我关于 Python 的事")
client.submit_task(query="解释 Python")

# ✅ 好：一致的查询命中缓存
standard_query = "什么是 Python？"
client.submit_task(query=standard_query)  # 缓存未命中
client.submit_task(query=standard_query)  # 缓存命中
client.submit_task(query=standard_query)  # 缓存命中
```

### 4. 监控和优化

定期查看成本指标：

```python theme={null}
# 启用详细日志
import logging
logging.basicConfig(level=logging.INFO)

total_cost = 0.0
for t in tasks:
    st = client.wait(t.task_id)
    if st.token_usage:
        total_cost += st.token_usage.cost_usd
        print(f"任务：${st.token_usage.cost_usd:.4f}，累计：${total_cost:.4f}")
```

### 5. 首先使用较小的模型

让智能路由器证明何时需要更大的模型：

```python theme={null}
# 让 Shannon 选择
client.submit_task(query="...")  # 自动选择层级

# 模型层级由平台路由器选择。SDK 不接受每个请求的模型层级或预算参数。
```

## 成本优化清单

<Accordion title="优化清单">
  * [ ] 在所有任务上设置 `max_cost_usd`
  * [ ] 对直接查询使用 `# 自动选择模式`
  * [ ] 启用响应缓存（默认：已启用）
  * [ ] 在适当时使用 `model_tier="small"`
  * [ ] 标准化查询措辞以实现缓存命中
  * [ ] 在仪表板中监控成本指标
  * [ ] 设置预算警报（通过 Prometheus）
  * [ ] 审查和优化提示模板
  * [ ] 使用会话上下文减少令牌使用
  * [ ] 启用学习路由器（默认：已启用）
</Accordion>

## 示例：成本优化工作流

```python theme={null}
from shannon import ShannonClient

client = ShannonClient()

# 高容量、简单查询
simple_tasks = [
    "分类情感：很棒的产品！",
    "分类情感：糟糕的体验",
    "分类情感：还可以"
]

total_cost = 0
for query in simple_tasks:
    handle = client.submit_task(query=query)
    status = client.wait(handle.task_id)
    if status.token_usage:
        total_cost += status.token_usage.cost_usd

print(f"3 个任务的总成本：${total_cost:.4f}")
# 示例：约 $0.006（与始终使用 GPT-5 相比约 90% 节省）
```

## 下一步

<CardGroup cols={2}>
  <Card title="流式传输事件" icon="stream" href="/cn/quickstart/concepts/streaming">
    实时任务监控
  </Card>

  <Card title="配置" icon="gear" href="/cn/quickstart/configuration">
    高级成本设置
  </Card>

  <Card title="API 概述" icon="code" href="/cn/api/overview">
    端点和用法
  </Card>

  <Card title="监控" icon="chart-line" href="/cn/quickstart/concepts/monitoring">
    成本监控 UI
  </Card>
</CardGroup>

***
