Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 21 additions & 6 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,12 +80,27 @@ clean the diff is:

## The price list

`crates/tw-pricing` embeds a pinned snapshot. It is **not** auto-updated:
following upstream automatically means two builds can compute different
prices, and "yesterday's number doesn't match today's" cannot be
explained to a user. Update steps are in
`crates/tw-pricing/data/PROVENANCE.md`, and a CI test compares the
snapshot against the hand-checked `data/verified.yaml` row by row.
Prices come in two layers.

- **The default price table** is LiteLLM's public dataset. A pinned
snapshot is embedded in `crates/tw-pricing`, so a fresh install and an
offline machine have one. Update steps are in
`crates/tw-pricing/data/PROVENANCE.md`, and a CI test compares the
snapshot against the hand-checked `data/verified.yaml` row by row. At
runtime the control plane refreshes the table once a day (unless
`pricing.auto_update: false`) and saves it as `model_prices.json` beside
`config.yaml`. Whichever of the two is newer prices requests.
- **Price sheets** live in `config.yaml` under `pricing.sheets`: a
multiplier over the default table, plus per-model overrides with every
field written out (dollars per million tokens; nothing is inferred at
pricing time). An upstream picks a sheet with `pricing:`. Without one,
the default table applies.

A refresh or an edited sheet changes the price of requests from then on,
never of the ones already recorded. Each request stores its cost and where
the price came from: the default table and its date, a sheet's multiplier,
or a sheet's override. "Yesterday's number doesn't match today's" is then
answered on the request itself.

## Cutting a release

Expand Down
5 changes: 2 additions & 3 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ Point a client (Claude Code, Codex, and friends) at a local port, and:
upstream, rewriting parameters, or refusing outright.
- **Fail over mid-flight** — before the first byte an upstream can be swapped
transparently; after it, the only honest thing left is to report what happened.
- **Make cost visible** — token usage, cache hits, priced against a snapshot
table. What cannot be priced is labelled *unknown* rather than given an
invented number.
- **Make cost visible** — token usage, cache hits, priced against a public
price table that refreshes daily, with price sheets for upstreams that
charge differently. What cannot be priced is labelled *unknown* rather
than given an invented number.
- **Redact outbound** — secrets in a request are replaced with placeholders
before they reach a relay, and restored when the model echoes them back.
- **Inspect inbound** — tool calls returned by an upstream are checked against
Expand Down
32 changes: 10 additions & 22 deletions bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -657,23 +657,17 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
rt.block_on(async move {
let state = tw_gateway::AppState::new(cfg.clone())
.map_err(|e| anyhow::anyhow!("{}", e.message))?;
// **和观测那一层用同一份价目表。**两处各拿一份的话,「成本栏
// 显示的」和「按最便宜选的」会对不上(用户覆盖层就是
// `cheapest` 唯一的判据来源)。读不了就用内置那份,转发照常。
match tw_pricing::Prices::builtin()
.and_then(|p| p.with_overrides(&dir.join("pricing.yaml")))
{
Ok(p) => state.set_prices(p),
Err(e) => tracing::warn!("价目表的用户覆盖读不了,按内置那份算:{e}"),
}
// 默认价目表:上次联网刷新存下的那份,或者内置的。自定义价目表已经
// 随配置进了价格簿
state.set_price_table(tw_control::pricing::load_table(&config_path));

// 观测这一层。**起不来不是致命的** —— 历史记录看不见,而网关
// 照常转发。所以这里所有的失败都只记一行日志。
//
// body 的通道在这里建:**它是唯一同时看得见网关和存储的地方**,
// 而两边各有各的同形结构,是为了不让「观测」挂到「转发」下面。
let (body_tx, body_rx) = tokio::sync::mpsc::channel(tw_gateway::bodies::CHANNEL_CAP);
let store = build_store(&dir, state.bus.clone(), body_rx);
let store = build_store(&dir, state.bus.clone(), state.pricing.clone(), body_rx);
if store.is_some() {
state.set_body_sink(body_tx);
}
Expand Down Expand Up @@ -704,6 +698,7 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
cfg: manager,
gateway_addr: if safe { None } else { Some(addr.to_string()) },
store,
price_updater: Default::default(),
};
// 盯着客户端配置面。**只报告** —— 这条路径上没有任何
// 一处会改用户的文件。盯不住就只是少了「变更时告警」,页面上
Expand All @@ -712,6 +707,8 @@ fn cmd_serve(path: &Path, port: Option<u16>, safe: bool, parent: Option<u32>) ->
// 不是人发起的配置写入** —— 理由是服务器换发新 refresh token 的
// 那一刻旧的就作废了,不写回等于让配置文件从那一秒起就是坏的。
tw_control::rotation::spawn(control.clone());
// 定期刷新默认价目表(`pricing.auto_update`,默认开)
tw_control::pricing::spawn(control.clone());

let _scan_watch = match tw_control::scan::spawn_watcher(control.clone()) {
Ok(w) => Some(w),
Expand Down Expand Up @@ -803,6 +800,8 @@ fn build_store(
// **收整条总线,不只是一个订阅端。**存储层算完价钱要往回报一条
// (见 `Event::RequestPriced`)—— 它是这条链上唯一知道单价的地方。
bus: tw_observe::EventBus,
// **和网关同一份价格簿**,不是一份副本:改了价目表,下一个结束的请求就按新价算
pricing: tw_pricing::Shared,
bodies: tokio::sync::mpsc::Receiver<tw_gateway::BodyRecord>,
) -> Option<std::sync::Arc<tokio::sync::Mutex<tw_store::Recorder>>> {
let events = bus.subscribe();
Expand All @@ -813,17 +812,6 @@ fn build_store(
return None;
}
};
// 价目表解不开是个打包错误,但同样不该挡住转发 —— 那时成本一栏
// 是空的,而请求照常。
let prices = match tw_pricing::Prices::builtin()
.and_then(|p| p.with_overrides(&dir.join("pricing.yaml")))
{
Ok(p) => p,
Err(e) => {
tracing::warn!("价目表读不了,成本一栏会是空的:{e}");
return None;
}
};
let blobs = tw_store::Blobs::new(dir.join("blobs"));
// 两边的 body 结构在这里对接。**一次移动,不复制** —— `Bytes` 的
// 克隆是引用计数。
Expand All @@ -849,7 +837,7 @@ fn build_store(
Some(tw_store::task::spawn(
// 算完价钱往回报一条 —— 见 `Event::RequestPriced`。这里是唯一
// 同时看得见总线和存储层的地方,所以接线在这儿完成。
tw_store::Recorder::new(db, blobs, prices).reporting_to(bus),
tw_store::Recorder::new(db, blobs, pricing).reporting_to(bus),
events,
rx,
))
Expand Down
Loading
Loading