# https://github.com/itsthelore/wayfinder-router 项目说明书

生成时间：2026-06-28 04:49:56 UTC

## 目录

- [Overview and Quickstart](#page-overview)
- [Routing Engine Architecture](#page-routing-engine)
- [Gateway Control Plane: Virtual Keys, Rate Limiting, Caching, and Budgets](#page-gateway-control-plane)
- [Calibration, Onboarding, and Feedback Loop](#page-calibration-feedback)

<a id='page-overview'></a>

## Overview and Quickstart

### 相关页面

相关主题：[Routing Engine Architecture](#page-routing-engine), [Gateway Control Plane: Virtual Keys, Rate Limiting, Caching, and Budgets](#page-gateway-control-plane)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/itsthelore/wayfinder-router/blob/main/README.md)
- [pyproject.toml](https://github.com/itsthelore/wayfinder-router/blob/main/pyproject.toml)
- [wayfinder_router/__init__.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/__init__.py)
- [wayfinder_router/cli.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/cli.py)
- [wayfinder_router/bootstrap.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/bootstrap.py)
- [wayfinder_router/onboard.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/onboard.py)
- [wayfinder_router/gateway/__init__.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/gateway/__init__.py)
</details>

# Overview and Quickstart

## 项目定位与设计理念

Wayfinder Router 是一个**确定性提示词复杂度路由器**（deterministic prompt-complexity router），其核心目标是在不调用任何模型的前提下，根据提示词的结构与词汇特征，快速判定应当将其路由到本地小模型还是云端大模型，从而节省成本同时保持响应质量。资料来源：[README.md:1-30]()。

该项目采用"分层纯净度"（purity layering）的架构思想：**评分核心**（scorer）、**配置加载器**（config）、**校准器**（calibrator）保持纯函数式且完全离线运行；只有**网关层**（gateway）与可选的本地 UI 才负责接触 API 密钥与网络请求。资料来源：[README.md:24-28]()。

Wayfinder 的设计哲学强调：

- **零模型调用决策**：路由决策由结构分析得出，而非依赖另一个 LLM 的判断；
- **完全可复现**：相同的提示词与阈值永远得到相同的路由结果；
- **自带数据可校准**：用户可基于自身流量数据微调阈值，而非依赖通用预训练模型；
- **自带密钥自托管**：密钥仅在请求时从环境变量读取，绝不写入配置文件。资料来源：[README.md:13-23]()。

## 核心架构

```mermaid
flowchart LR
    A[客户端应用] -->|OpenAI API| B[Wayfinder Gateway]
    B --> C{评分核心<br/>scorer}
    C -->|score < threshold| D[本地模型<br/>local]
    C -->|score ≥ threshold| E[云端模型<br/>cloud]
    D --> F[响应回传]
    E --> F
    B -.日志.-> G[反馈日志<br/>feedback log]
    G -.校准.-> H[calibrate]
    H -.重写.-> I[wayfinder-router.toml]
    I -.热加载.-> B
```

如上图所示，请求先经由网关进入，评分核心离线计算一个 0.0–1.0 之间的复杂度分数，再与配置中的阈值或层级表对比，决定目标模型。资料来源：[README.md:32-48]()。

## 快速上手（Quickstart）

### 安装与初始化

```bash
pip install "wayfinder-router[gateway]"
wayfinder-router init                 # 起步配置（hybrid 预设）
wayfinder-router init --preset openai # 两级 OpenAI（gpt-4o-mini → gpt-4o）
wayfinder-router init --preset gemini # 两级 Gemini（flash → pro）
wayfinder-router init --interactive   # 逐步选择 provider/model
```

`init` 子命令会生成一份 `wayfinder-router.toml` 起步配置以及 `.env.example` 文件，并自动校验密钥可用性。资料来源：[README.md:78-95]()。

### 最简配置示例

```toml
[routing]
threshold = 0.5            # 低于阈值路由到 local，否则路由到 cloud

[gateway.models.local]
base_url = "http://localhost:11434/v1"
model = "llama3.2"

[gateway.models.cloud]
base_url = "https://api.openai.com/v1"
model = "gpt-4o"
api_key_env = "OPENAI_API_KEY"   # 仅记录环境变量名
# api_key_cmd = "op read op://Private/OpenAI/credential"  # 可选：从 vault 注入
```

客户端只需将 `base_url` 切换为 Wayfinder 网关地址（如 `http://localhost:8088/v1`），原有的 OpenAI SDK 调用无需修改。资料来源：[README.md:97-115]()。

### CLI 评分与路由

```bash
echo "Summarise this paragraph in one sentence." | wayfinder-router route -
```

输出包括推荐模型、复杂度分数、参与的特征值，添加 `--json` 可得到机器可读的 JSON，供上层 agent 自主路由。资料来源：[README.md:142-175]()。

### 路由模式优先级

Wayfinder 支持三种路由模式，按优先级排列：**classifier > tiers > threshold**。资料来源：[README.md:117-140]()。

- **Binary（默认）**：单一阈值切分；
- **Tiered**：按分数段映射到任意数量的模型；
- **Classifier**：多分类器对每个候选模型输出线性分数后取 argmax。

## 2026.6.7 版本：网关升级为控制平面

最新发布的 **Wayfinder Router 2026.6.7** 将网关从"个人代理"演进为"团队级控制平面"，新增多项面向生产环境的能力（均为 opt-in，路由决策方式不变）：

| 新增能力 | 作用 |
| --- | --- |
| **API 密钥分发** | 网关为不同团队签发 Bearer 密钥，归属与消耗独立核算 |
| **按密钥可视化** | `GET /v1/savings` 的 `by_key` 字段与 `wayfinder_router_key_requests_total` 指标展示各团队花费 |
| **预算/速率限制/模型白名单** | 每个密钥可绑定预算上限、rpm/tpm 速率限制与 `models` 允许列表（自动收紧到最近允许的层级） |
| **响应缓存** | `[gateway.cache]` 启用精确匹配缓存，对幂等请求实现瞬时免费复用 |

上述新增能力遵循"路由决策保持纯净"的设计原则，所有这些团队级控制都在网关层完成，不影响评分核心的离线与确定性。资料来源：[README.md:240-265]()。

### Docker 部署

```bash
docker build -t wayfinder-router . && docker run -p 8088:8088 -v "$PWD/data:/data" wayfinder-router
# 或：docker compose up gateway
```

`Dockerfile` 与 `docker-compose.example.yml` 已经随仓库提供。资料来源：[README.md:42-46]()。

## 测试与开发

```bash
pip install -e .[dev]   # 或：pip install pytest
make test
```

测试套件覆盖：scorer、config、calibration、explain、feedback、onboard、recalibrate、CLI、gateway 以及 UI 各模块。资料来源：[README.md:49-52]()。

## Python API（库内使用）

```python
from wayfinder_router import score_complexity, RoutingConfig, explain_score

result = score_complexity(prompt_text, config=RoutingConfig.binary(threshold=0.7))
print(result.recommendation, result.score, result.features)
for fc in explain_score(result.features, RoutingConfig().weights):
    print(fc.name, fc.contribution)
```

库导入仅依赖标准库，可作为进程内（in-process）路由使用，避开网关的网络开销。资料来源：[README.md:296-305]()。

## See Also

- [How it compares](https://github.com/itsthelore/wayfinder-router/blob/main/README.md) — 与 RouteLLM、NotDiamond、OpenRouter 等的对比
- [Calibration & Lexical Routing](docs/lexical-routing.md) — 词汇特征权重与校准方法
- [FAQ](docs/faq.md) — 常见问题与已知弱点
- [Benchmark](benchmarks/README.md) — RouterBench / RouterArena 评测
- [Explainer](EXPLAINER.md) — 设计理念与决策记录索引

---

<a id='page-routing-engine'></a>

## Routing Engine Architecture

### 相关页面

相关主题：[Overview and Quickstart](#page-overview), [Gateway Control Plane: Virtual Keys, Rate Limiting, Caching, and Budgets](#page-gateway-control-plane), [Calibration, Onboarding, and Feedback Loop](#page-calibration-feedback)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/itsthelore/wayfinder-router/blob/main/README.md)
- [examples/README.md](https://github.com/itsthelore/wayfinder-router/blob/main/examples/README.md)
- [wayfinder_router/](https://github.com/itsthelore/wayfinder-router/tree/main/wayfinder_router)
- [docs/lexical-routing.md](https://github.com/itsthelore/wayfinder-router/blob/main/docs/lexical-routing.md)
- [examples/wayfinder-router.lexical.toml](https://github.com/itsthelore/wayfinder-router/blob/main/examples/wayfinder-router.lexical.toml)
- [benchmarks/README.md](https://github.com/itsthelore/wayfinder-router/blob/main/benchmarks/README.md)
</details>

# 路由引擎架构

## 概述与定位

Wayfinder 路由引擎是一个**确定性、离线、无模型调用**的提示词复杂度评分器。它的核心职责是读取提示词的结构特征（长度、标题、列表、代码块）以及可选的词法线索（推理词、数学符号、硬约束），在毫秒级时间内为每个提示词打分并推荐本地或云端模型。资料来源：[README.md:36-50]()

整个路由引擎由两类层组成：**纯函数核心**（scorer、tiers、classifier、config、calibrator、explain）保持无依赖且可独立 `import`；**非纯层**（gateway、本地 UI）通过可选的 extras 引入，负责网络与密钥管理。资料来源：[README.md:200-220]()

```mermaid
flowchart TD
    A[客户端请求<br/>OpenAI 兼容] --> B[Wayfinder Gateway]
    B --> C{路由决策}
    C -->|mode=scored| D[评分器<br/>score_complexity]
    C -->|mode=pinned| E[直接锁定端点]
    C -->|mode=threshold-override| F[请求级 X-Wayfinder-Threshold]
    D --> G{路由模式}
    G -->|binary| H[threshold 阈值切割]
    G -->|tiered| I[[routing.tiers] 阶梯匹配]
    G -->|classifier| J[多项逻辑回归 argmax]
    H --> K[本地模型 / Ollama / vLLM]
    I --> K
    J --> K
    H --> L[云端模型 / OpenAI / Anthropic]
    I --> L
    J --> L
    K --> M[响应回传 + 路由头]
    L --> M
```

## 评分与三种路由模式

### 结构化特征评分

评分器从提示词中提取结构特征（`word_count`、`heading_count`、`list_item_count`、`code_block_count` 等），并按权重线性求和得到 0.0–1.0 的分数。词法线索（`reasoning_term_count` 等）默认关闭，需要在配置中显式提高权重才会启用。资料来源：[README.md:160-175]()

### 三种路由模式（优先级：classifier > tiers > threshold）

**Binary（二元切割）**：单一阈值是最简单也最常用的模式。低于阈值走本地，等于或高于阈值走云端。`--threshold N` 可在运行时覆盖，`WAYFINDER_ROUTER_THRESHOLD` 环境变量同样生效。资料来源：[README.md:155-165]()

**Tiered（多档分级）**：按分数段映射到任意数量的模型。例如：

```toml
[[routing.tiers]]
min_score = 0.0
model = "llama-3b"
[[routing.tiers]]
min_score = 0.3
model = "llama-70b"
[[routing.tiers]]
min_score = 0.6
model = "claude-cloud"
```

资料来源：[README.md:170-185]()

**Classifier（分类器）**：通过 `calibrate --mode classifier` 离线拟合的多项逻辑回归模型，对每个模型输出一条线性分数，取 `argmax`。通常由 `calibrate` 自动生成而非手写。资料来源：[README.md:185-195]()

## 请求级干预与单次控制

引擎将 OpenAI 的 `model` 字段视为**路由指令**，而非模型标识：

| 取值 | 行为 |
| --- | --- |
| `auto` 或普通模型 id | 由评分器自动决策 |
| `local` / `cloud`（配置端点名） | 锁定到该端点（mode=pinned） |
| `prefer-local` / `prefer-hosted` | 锁定到路由器的最低/最高档 |
| `X-Wayfinder-Threshold` 请求头 | 仅对二元路由器生效，覆盖该次决策的阈值 |

响应头 `x-wayfinder-router-mode` 会标注决策来自哪种通道（`scored` / `pinned` / `threshold-override`）。资料来源：[README.md:140-160]()

## 校准、词法线索与配置管理

引擎虽然默认开箱即用，但鼓励用户基于自身流量重新校准。`wayfinder-router calibrate` 子命令读取 `{"text": ..., "label": ...}` 格式的 JSONL 数据集，离线运行 L2 正则化的 Newton/IRLS 拟合，输出可直接粘贴进 `wayfinder-router.toml` 的配置片段。`--objective knee` 选项会自动选择成本-质量拐点，避免在偏斜标签上退化为"全部走昂贵模型"。资料来源：[README.md:60-90]()

词法线索（证明、数学、约束）在真实前沿流量上能让 held-out 技能从 −0.038 提升到 +0.057、节省 61% RouterBench 成本，但双盲测试显示其泛化能力并不强，因此**默认关闭**，需要显式启用。资料来源：[README.md:165-180]()、[docs/lexical-routing.md]()

## 与 Gateway 的集成

路由引擎通过 `[gateway.models.<name>]` 块映射路由名到上游 `base_url`、`model` 及 `api_key_env`（环境变量名而非密钥本身）。Gateway 是唯一接触密钥与网络的层；评分器、配置和校准器始终保持纯函数与离线。`GET /v1/models` 会向客户端暴露路由选项（`auto` / `prefer-local` / `prefer-hosted` 及配置的端点），使 LibreChat、Open WebUI 等兼容 UI 自动获得路由模式选择器而无需 fork。资料来源：[README.md:195-210]()、[examples/README.md:1-25]()

`wayfinder-router.toml` 由 CLI 在当前目录向上回溯发现，三种模式按优先级（classifier > tiers > threshold）生效，标量分数 `weights` 适用于前两种。资料来源：[README.md:150-165]()

## 参见

- [快速开始与 Quickstart](../README.md#quickstart)
- [词法路由指南](../docs/lexical-routing.md)
- [集成示例（LibreChat / Open WebUI）](../examples/README.md)
- [基准测试与公平比较](../benchmarks/README.md)
- [常见问题 FAQ](../docs/faq.md)
- [2026.6.7 版本说明 — gateway as a control plane](#)

---

<a id='page-gateway-control-plane'></a>

## Gateway Control Plane: Virtual Keys, Rate Limiting, Caching, and Budgets

### 相关页面

相关主题：[Overview and Quickstart](#page-overview), [Routing Engine Architecture](#page-routing-engine), [Calibration, Onboarding, and Feedback Loop](#page-calibration-feedback)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [wayfinder_router/gateway.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/gateway.py)
- [wayfinder_router/cache.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/cache.py)
- [wayfinder_router/ratelimit.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/ratelimit.py)
- [wayfinder_router/vkeys.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/vkeys.py)
- [wayfinder_router/reliability.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/reliability.py)
- [wayfinder_router/pricing.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/pricing.py)
- [wayfinder_router/metrics.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/metrics.py)
- [README.md](https://github.com/itsthelore/wayfinder-router/blob/main/README.md)
- [decisions/WF-ADR-0031.md](https://github.com/itsthelore/wayfinder-router/blob/main/decisions/WF-ADR-0031.md)
- [decisions/WF-ADR-0032.md](https://github.com/itsthelore/wayfinder-router/blob/main/decisions/WF-ADR-0032.md)
- [decisions/WF-ADR-0033.md](https://github.com/itsthelore/wayfinder-router/blob/main/decisions/WF-ADR-0033.md)
- [decisions/WF-ADR-0034.md](https://github.com/itsthelore/wayfinder-router/blob/main/decisions/WF-ADR-0034.md)
- [decisions/WF-ADR-0035.md](https://github.com/itsthelore/wayfinder-router/blob/main/decisions/WF-ADR-0035.md)
</details>

# Gateway Control Plane: Virtual Keys, Rate Limiting, Caching, and Budgets

Wayfinder Router 2026.6.7 将网关从个人代理升级为团队级控制平面。本次发布以"opt-in、可观测、可审计"为设计前提，在不破坏现有路由决策路径的前提下，新增虚拟 API 密钥、按配额计费、限流、响应缓存与预算守护。所有守护栏均在评分与转发链路外围按需开启，由配置驱动，不引入任何额外的模型调用 资料来源：[README.md:1-50]()。

## 1. 总体架构与请求生命周期

控制平面在网关请求处理管道中以**前置守护栏**的形式出现，顺序为：限流 → 密钥鉴权 → 预算 → 缓存读取 → 评分与路由 → 转发 → 缓存写入 → 计费 → 度量导出。这样设计确保所有守护栏都在请求真正落到上游模型前生效，避免无谓的网络与计费开销 资料来源：[wayfinder_router/gateway.py:1-200]()。

```mermaid
flowchart LR
    A[Client Request] --> B[Rate Limiter]
    B -->|429| Z[Reject]
    B --> C[Virtual Key Auth]
    C -->|401| Z
    C --> D[Budget Check]
    D -->|402| Z
    D --> E[Cache Lookup]
    E -->|hit| Y[Replay Response]
    E -->|miss| F[Score + Route]
    F --> G[Upstream Call]
    G --> H[Cache Write]
    H --> I[Cost Attribution]
    I --> J[Metrics + Headers]
    Y --> J
    J --> K[Response to Client]
```

每个阶段都向响应注入 `x-wayfinder-router-*` 头，便于运维侧观察决策与拦截位置 资料来源：[README.md:150-200]()。

## 2. 虚拟 API 密钥（Virtual Keys）

虚拟密钥让单个 Wayfinder 网关实例可以被多团队共享使用，同时为每个团队提供独立的配额、限流与模型白名单。`wayfinder-router keys new` 生成新密钥，**仅存储 SHA-256 哈希**；原始令牌仅在创建时显示一次 资料来源：[README.md:165-175]()。

### 2.1 配置结构

每个密钥在 `wayfinder-router.toml` 中由 `[gateway.keys.<id>]` 块描述。嵌套的 `budget`、`rate_limit`、`models` 字段分别用于设定该密钥的预算上限、限流策略与可访问模型白名单；网关侧采用"最严格优先"策略合并用户级与密钥级配置 资料来源：[wayfinder_router/vkeys.py:1-150]()。

### 2.2 节省归因

`/v1/savings` 端点支持 `by_key` 维度，揭示每条密钥的累计支出、路由节省金额与命中率。`wayfinder_router_key_requests_total` Prometheus 指标按密钥打标，使财务与可观测系统可独立核算 资料来源：[README.md:170-180]()、资料来源：[wayfinder_router/metrics.py:1-120]()。

### 2.3 模型白名单与降级

当密钥携带 `models = ["local"]` 之类的允许列表时，网关会把评分结果"夹"到最近的可允许层级——例如评分请求 `cloud` 但白名单仅含 `local` 时，请求会被强制路由到本地端点 资料来源：[decisions/WF-ADR-0035.md:1-60]()。

## 3. 限流、可靠性与重试

### 3.1 速率限制

`[gateway.rate_limit]` 段支持 `rpm`（每分钟请求数）与 `tpm`（每分钟上游 token 数）两种维度，二者可独立启用并叠加生效。窗口长度由 `window` 控制，默认 60 秒。超额时返回 HTTP `429` 并附带 `Retry-After`；未超限的响应会回传 `X-RateLimit-Limit`、`X-RateLimit-Remaining`、`X-RateLimit-Reset`，便于客户端自我节流 资料来源：[wayfinder_router/ratelimit.py:1-160]()、资料来源：[decisions/WF-ADR-0034.md:1-50]()。

### 3.2 重试与熔断

`[gateway.reliability]` 段提供 `max_retries` 与 `breaker_cooldown` 两个开关：前者限定对瞬时传输错误、`429` 与 `5xx` 的有界重试次数，后者控制每个上游目标的熔断恢复时间。熔断器按目标独立维护，避免单点失败污染整体可用性 资料来源：[wayfinder_router/reliability.py:1-180]()、资料来源：[decisions/WF-ADR-0031.md:1-60]()。

## 4. 响应缓存

`[gateway.cache]` 提供基于精确匹配的响应缓存，对**确定性请求**返回已存储的回答，使重复请求瞬时且免费。该功能默认关闭，开启后仅在内存中保存，并可通过 `max_bytes`（默认 64 MiB）与 `max_entries` 控制体量 资料来源：[wayfinder_router/cache.py:1-150]()、资料来源：[decisions/WF-ADR-0033.md:1-40]()。

### 4.1 命中观测

每次响应都会携带 `x-wayfinder-router-cache: hit|miss` 头，运维侧据此判断缓存效果。关闭缓存时会自动清空既有条目，防止陈旧数据回流 资料来源：[README.md:155-165]()。

### 4.2 适用边界

缓存仅对"相同输入产生相同输出"的请求有效：例如 `temperature=0` 的聊天补全、确定的嵌入调用等。带 `stream: true` 的流式请求在网关层会被缓存决策拦截后再决定是否走流通道，避免不一致体验 资料来源：[wayfinder_router/cache.py:50-120]()。

## 5. 预算守护

`[gateway.budget]` 段控制总支出上限，由 `limit`、`window`（`day` / `month` / `all`）与 `on_breach`（`degrade` / `block`）三个字段构成。`degrade`（默认）将超额请求降级到最便宜的层级，**永不抬升成本**；`block` 则直接返回 HTTP `402` 阻止调用 资料来源：[decisions/WF-ADR-0032.md:1-50]()。

预算计算依赖真实价格：在 `[gateway.models.<name>]` 中需提供 `cost_per_1k` 字段，否则系统会以"成本未知"的形式跳过预算检查并在响应头 `x-wayfinder-router-budget` 中明示。价格元数据同时上报到 `/metrics`，供财务与可观测系统使用 资料来源：[wayfinder_router/pricing.py:1-120]()。

## 6. 配置速查表

| 配置段 | 关键字段 | 默认值 | 行为 |
| --- | --- | --- | --- |
| `[gateway.rate_limit]` | `rpm` / `tpm` / `window` | 未启用 | 触发 `429`；响应携带 `X-RateLimit-*` 头 |
| `[gateway.budget]` | `limit` / `window` / `on_breach` | 未启用 | 触发 `degrade` 或 `402` |
| `[gateway.cache]` | `enabled` / `ttl` / `max_bytes` | 关闭 | 命中返回缓存；携带 `x-wayfinder-router-cache` |
| `[gateway.keys.<id>]` | `hash` / `tags` / `budget` / `rate_limit` / `models` | 无 | `401` 拦截未授权；严格合并生效 |
| `[gateway.reliability]` | `max_retries` / `breaker_cooldown` | 关闭 | 对瞬时错误有界重试；按目标熔断 |

## 7. 常见故障与处理

- **预算未生效**：检查模型配置是否提供 `cost_per_1k`；若缺失，预算是"软跳过"而非拒绝 资料来源：[wayfinder_router/pricing.py:80-120]()。
- **密钥失效**：`keys new` 仅展示原始令牌一次；丢失后必须重新签发，原哈希不可逆 资料来源：[wayfinder_router/vkeys.py:60-100]()。
- **缓存命中率低**：检查请求是否带有影响输出的字段（`temperature`、`seed`、`tools`），非确定性请求会被旁路 资料来源：[wayfinder_router/cache.py:30-80]()。
- **熔断时间过长**：`breaker_cooldown` 单位为秒，过高会导致流量长时间被剔除；建议配合监控逐步调优 资料来源：[decisions/WF-ADR-0031.md:30-60]()。

## See Also

- [Wayfinder Router 主维基页](README.md)
- [可靠性设计（WF-ADR-0031）](decisions/WF-ADR-0031.md)
- [预算守护（WF-ADR-0032）](decisions/WF-ADR-0032.md)
- [响应缓存（WF-ADR-0033）](decisions/WF-ADR-0033.md)
- [速率限制（WF-ADR-0034）](decisions/WF-ADR-0034.md)
- [虚拟密钥（WF-ADR-0035）](decisions/WF-ADR-0035.md)

---

<a id='page-calibration-feedback'></a>

## Calibration, Onboarding, and Feedback Loop

### 相关页面

相关主题：[Routing Engine Architecture](#page-routing-engine), [Gateway Control Plane: Virtual Keys, Rate Limiting, Caching, and Budgets](#page-gateway-control-plane)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [wayfinder_router/calibrate.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/calibrate.py)
- [wayfinder_router/feedback.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/feedback.py)
- [wayfinder_router/onboard.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/onboard.py)
- [wayfinder_router/recalibrate.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/recalibrate.py)
- [wayfinder_router/pricing.py](https://github.com/itsthelore/wayfinder-router/blob/main/wayfinder_router/pricing.py)
- [decisions/WF-ADR-0003-calibration-and-classifier.md](https://github.com/itsthelore/wayfinder-router/blob/main/decisions/WF-ADR-0003-calibration-and-classifier.md)
- [docs/lexical-routing.md](https://github.com/itsthelore/wayfinder-router/blob/main/docs/lexical-routing.md)
- [benchmarks/calibration-eval.md](https://github.com/itsthelore/wayfinder-router/blob/main/benchmarks/calibration-eval.md)
</details>

# Calibration, Onboarding, and Feedback Loop

## 概述

Wayfinder 的路由决策基于一个 0.0–1.0 的"复杂度分数",该分数通过纯离线、确定性的方式计算（不调用任何模型）。然而,这个分数本身只是难度的代理指标,因此最终的"切割点"(threshold / tiers / classifier)必须由使用者根据自身流量调优。**校准(Calibration)、引导(Onboarding)与反馈循环(Feedback Loop)** 正是用来解决这一问题的子系统:它把人工判断转成可执行的路由配置,并在网关运行期间持续迭代,使切割点始终贴近真实业务负载。整套机制运行在纯 Python 中,从不发起模型调用,因此即便在最严格的离线环境也能保持可重现。 资料来源：[README.md]()

## 校准(calibrate)

`wayfinder-router calibrate` 是整个反馈循环的"拟合"环节。它读取一个 JSONL 格式的标注数据集 `{"text": ..., "label": ...}`,在本地拟合三种模式之一,并把可直接部署的 TOML 配置片段输出到 stdout,把准确率与所选切割点打印到 stderr。 资料来源：[wayfinder_router/calibrate.py]()

| 模式 | 行为 | 典型用途 |
| --- | --- | --- |
| `--mode threshold` | 在 0.0–1.0 之间扫描,选出最优单切割点 | 默认二元(local vs cloud)路由 |
| `--mode tiers` | 拟合有序多档位切割(ordinal) | 三个或更多模型的分层路由 |
| `--mode classifier` | 训练一个多项 Logit,每模型得出一组线性权重 | 非有序、含跳跃式档位的场景 |

拟合算法使用确定性 L2 正则化的 Newton/IRLS,纯 Python 实现,通常在数轮迭代内收敛。 资料来源：[README.md]() 资料来源：[decisions/WF-ADR-0003-calibration-and-classifier.md]()

### 成本感知目标

单纯追求准确率会令模型在偏斜标签下"全选贵的"。为此 calibrate 提供两类目标函数:

- `--objective knee` — 自动挑选成本曲线的拐点,最大化 `quality_recovered × cost_saved`,无需指定目标,也不会退化为全选高端模型。
- `--objective cost-quality --target-savings X` — 在保证不低于 `X` 节省率的前提下最大化质量。

成本通过 `--costs local=0.2,cloud=1.0` 提供,**仅参与拟合与 `/metrics` 报告,绝不参与单请求决策**,从而保证路由本身保持确定性、零成本。 资料来源：[README.md]() 资料来源：[wayfinder_router/pricing.py]()

### 词法特征校准

词法线索(推理词、数学符号、约束词等)在默认状态下是关闭的,因其通用性较差(`benchmarks/blind-eval.md` 显示盲测下提升仅约 20% 且会输给纯词数基线)。可通过 `--weights` 在 calibrate 中一并拟合并写出,使产出的配置可直接部署。 资料来源：[docs/lexical-routing.md]() 资料来源：[benchmarks/calibration-eval.md]()

## 引导与反馈(onboard / feedback)

仅靠历史日志启动时往往缺乏标签。`wayfinder-router onboard` 通过 A/B 方式在终端或 UI 中**对同一条样本同时跑两臂模型**,让用户挑选"哪一臂足够好",其判定 `{"text", "label"}` 直接落到反馈日志中,等同于 calibrate 的数据集。配合 `--calibrate` 选项,onboard 可一次性把日志转成 TOML 并写入文件。 资料来源：[wayfinder_router/onboard.py]() 资料来源：[README.md]()

当网关已在运行时,可直接通过 HTTP 端点写入判定,无需重启:

```bash
curl localhost:8088/v1/feedback -d '{"text": "...", "label": "cloud"}'
```

判定被持久化为 JSONL,无任何提示词原文以外的敏感信息;密钥读取和模型调用仅限于网关层,评分核心不被触发。 资料来源：[wayfinder_router/feedback.py]()

## 重校准与热重载(recalibrate)

```mermaid
flowchart LR
  A[prompt traffic] --> B{router}
  B --> C[judge / onboard]
  C --> D[feedback log<br/>JSONL]
  D --> E[recalibrate]
  E --> F[wayfinder-router.toml]
  F --> B
  B -.header.-> G[per-request<br/>X-Wayfinder-Threshold]
```

`wayfinder-router recalibrate` 编排"日志 → calibrate → 写配置"的全流程,可由 cron、Kubernetes CronJob 或 UI 按钮触发。它**只重写 `[routing]` 段**,完整保留 `[gateway]` 中的端点、密钥与重试配置;运行中的网关会**无重启地热加载**新配置。 资料来源：[wayfinder_router/recalibrate.py]() 资料来源：[README.md]()

为避免在标签不足时给出噪声拟合,recalibrate 接受 `--min-labels 50` 阈值,在样本数不达标时静默 no-op,从而保护生产稳定性。 资料来源：[wayfinder_router/recalibrate.py]()

## 常见失败模式

- **样本过少即启动**:约 20 条仅是冒烟测试;真实部署至少应达到 `--min-labels 50` 推荐值,否则配置容易被个别极值样本拉偏。 资料来源：[benchmarks/calibration-eval.md]()
- **盲目启用词法权重**:在自有语料外泛化能力差,务必通过 calibrate `--weights` 在本业务流量上重训。 资料来源：[docs/lexical-routing.md]()
- **把成本误用于请求决策**:cost 仅参与拟合与统计上报,不得在单请求路径上读取,否则破坏离线确定性。 资料来源：[wayfinder_router/pricing.py]()

## See Also

- 配置与切割点形状(Threshold / Tiers / Classifier):参见 *Routing Modes* 页面
- 网关故障转移、重试与限速:参见 *Gateway Reliability & Cost Controls* 页面
- 双盲评估与基线对比:参见 [benchmarks/blind-eval.md](https://github.com/itsthelore/wayfinder-router/blob/main/benchmarks/blind-eval.md) 与 [benchmarks/README.md](https://github.com/itsthelore/wayfinder-router/blob/main/benchmarks/README.md)
- 设计动机与历史取舍:[decisions/WF-ADR-0003-calibration-and-classifier.md](https://github.com/itsthelore/wayfinder-router/blob/main/decisions/WF-ADR-0003-calibration-and-classifier.md)

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：itsthelore/wayfinder-router

摘要：发现 6 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：能力坑 - 能力判断依赖假设。

## 1. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://news.ycombinator.com/item?id=48704373 | README/documentation is current enough for a first validation pass.

## 2. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://news.ycombinator.com/item?id=48704373 | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://news.ycombinator.com/item?id=48704373 | no_demo; severity=medium

## 4. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://news.ycombinator.com/item?id=48704373 | no_demo; severity=medium

## 5. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://news.ycombinator.com/item?id=48704373 | issue_or_pr_quality=unknown

## 6. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://news.ycombinator.com/item?id=48704373 | release_recency=unknown

<!-- canonical_name: itsthelore/wayfinder-router; human_manual_source: deepwiki_human_wiki -->
