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
1 change: 1 addition & 0 deletions Cargo.lock

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

28 changes: 28 additions & 0 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1548,6 +1548,21 @@ pub struct HistoryRow {
/// 按什么价格算的。没算出金额的、老记录没有它
#[serde(default, skip_serializing_if = "Option::is_none")]
pub price_source: Option<PriceSourceView>,
/// 服务它的那一跳做过的格式转换。直通的、老记录没有它
#[serde(default, skip_serializing_if = "Option::is_none")]
pub translated: Option<TranslatedView>,
}

/// 一次请求做过的格式转换。
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TranslatedView {
/// 客户端的格式:`anthropic` / `openai-chat` / `openai-responses` / `gemini`
pub from: String,
/// 服务它的上游的格式
pub to: String,
/// 客户端请求里转不过去、被丢掉的字段路径
#[serde(default)]
pub dropped: Vec<String>,
}

/// 一条请求的全部细节。**详情抽屉吃这个。**
Expand Down Expand Up @@ -2054,6 +2069,19 @@ pub struct DryRunResult {
/// 规则选中、但服务不了这个请求而被跳过的上游
#[serde(default)]
pub skipped: Vec<SkippedView>,
/// 候选链里要转换格式的上游:客户端的格式和上游的协议不同
#[serde(default)]
pub converted: Vec<ConvertedView>,
}

/// 一个要转换格式的候选上游。
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ConvertedView {
pub provider: String,
/// 客户端的格式:`anthropic` / `openai-chat` / `openai-responses` / `gemini`
pub from: String,
/// 这个上游的格式
pub to: String,
}

/// 一个被跳过的候选上游。
Expand Down
17 changes: 17 additions & 0 deletions crates/tw-control/src/dryrun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ pub async fn dry_run(
hurts_cache: false,
circuit_open: Vec::new(),
skipped: Vec::new(),
converted: Vec::new(),
};

match engine.route(&f) {
Expand Down Expand Up @@ -194,6 +195,22 @@ pub async fn dry_run(
// 于是它显示的是轮转序列里的当前位置 —— 而那正是一个没有
// 会话指纹的请求真的会走的路。
out.candidates = order_like_the_data_plane(&s, engine, &d, &f);
// 哪些候选要转换格式。**试算里要说出来**:转换可能丢掉请求里的字段,
// 而「规则把我分到了一个别的格式的上游」本身就是用户来试算想知道的事。
// 协议认不出来的上游直通,不算
out.converted = out
.candidates
.iter()
.filter_map(|name| {
let p = rt.config.providers.iter().find(|p| &p.name == name)?;
let to = p.effective_protocol()?.slug();
(to != req.dialect).then(|| tw_api::ConvertedView {
provider: name.clone(),
from: req.dialect.clone(),
to: to.to_string(),
})
})
.collect();
}
Ok(Outcome::Deny { rule, reason }) => {
out.outcome = "deny".into();
Expand Down
4 changes: 4 additions & 0 deletions crates/tw-control/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,10 @@ fn history_row(r: tw_store::RequestRow) -> tw_api::HistoryRow {
.price_source
.as_deref()
.and_then(|j| serde_json::from_str(j).ok()),
translated: r
.translated
.as_deref()
.and_then(|j| serde_json::from_str(j).ok()),
}
}

Expand Down
1 change: 1 addition & 0 deletions crates/tw-control/tests/adopt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -460,6 +460,7 @@ async fn replaying_a_truncated_body_is_refused_rather_than_misleading() {
billing: String::new(),
cache_saved_micros: None,
price_source: None,
translated: None,
};
row.id = 1;
db.insert(&row).unwrap();
Expand Down
23 changes: 23 additions & 0 deletions crates/tw-control/tests/dryrun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,26 @@ async fn the_defaults_describe_an_ordinary_request() {
let trace: Vec<_> = r.trace.iter().map(|t| t.name.as_str()).collect();
assert_eq!(trace.len(), 4, "每条规则都要有个交代:{trace:?}");
}

#[tokio::test]
async fn a_candidate_in_another_format_is_listed_as_converted() {
// 试算要说出来:规则把一个 Chat 客户端分到了 Anthropic 上游,请求会被转换,
// 转不过去的字段会被丢掉
let (_d, app) = app();
let r = run(
&app,
r#"{"model":"claude-sonnet-4-5","dialect":"openai-chat"}"#,
)
.await;
assert_eq!(
r.converted,
vec![tw_api::ConvertedView {
provider: "官方".into(),
from: "openai-chat".into(),
to: "anthropic".into(),
}],
"协议认不出来的中转站直通,不算转换"
);
let r = run(&app, r#"{"model":"claude-sonnet-4-5"}"#).await;
assert!(r.converted.is_empty(), "{:?}", r.converted);
}
2 changes: 1 addition & 1 deletion crates/tw-dialect/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
description = "Dialect translation of requests and responses between Anthropic and OpenAI chat"
description = "Request, response and stream conversion between Anthropic Messages, OpenAI Chat Completions, OpenAI Responses and Gemini"

[dependencies]
serde = { workspace = true }
Expand Down
8 changes: 8 additions & 0 deletions crates/tw-dialect/src/anthropic/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
//! Anthropic Messages(`/v1/messages`)。

pub mod request;
pub mod response;
pub mod stream;

pub use request::{decode_request, encode_request};
pub use response::{decode_response, encode_response};
Loading
Loading