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
5 changes: 5 additions & 0 deletions Cargo.lock

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

20 changes: 15 additions & 5 deletions bin/twcore/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,11 +612,19 @@ fn cmd_check(path: &Path) -> Result<()> {
None => "not recognized (forwarded in the Anthropic format)".to_string(),
};
// 说来源而不是值。
let credential = match (&p.key, &p.oauth) {
(Some(k), _) => format!("API key {} ({})", k.describe(), p.auth_header().0),
(None, Some(_)) => "OAuth".to_string(),
(None, None) if !p.headers.is_empty() => "headers".to_string(),
(None, None) => "no credential".to_string(),
let credential = match (&p.key, &p.oauth, &p.aws) {
(Some(k), _, _) => {
format!("API key {} ({})", k.describe(), p.auth_header().0)
}
(None, Some(_), _) => "OAuth".to_string(),
// 签名用的密钥:说来源(环境变量还是写死的),不说值
(None, None, Some(a)) => format!(
"AWS access key {}, signed for {}",
a.access_key_id.describe(),
p.bedrock_region().unwrap_or("an unknown region")
),
(None, None, None) if !p.headers.is_empty() => "headers".to_string(),
(None, None, None) => "no credential".to_string(),
};
println!(
" · {} → {} [{}] {credential}",
Expand Down Expand Up @@ -673,6 +681,8 @@ fn cmd_check(path: &Path) -> Result<()> {
);
} else if let Err(e) = p.outbound_headers(None) {
println!(" ⚠ the credential could not be obtained: {e}");
} else if let Err(e) = p.aws_credentials() {
println!(" ⚠ the AWS access keys could not be obtained: {e}");
}
}
Ok(())
Expand Down
18 changes: 18 additions & 0 deletions crates/tw-api/msg-codes.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,16 @@ config.bad_remote_allow_from
config.blank_models_only
config.control_key_invalid
config.control_key_missing
config.credential.aws_bad_region
config.credential.aws_empty
config.credential.aws_no_region
config.credential.aws_not_bedrock
config.credential.aws_region_mismatch
config.credential.aws_signed_header
config.credential.bad_header_name
config.credential.bad_header_value
config.credential.bedrock_no_credential
config.credential.bedrock_oauth
config.credential.chatgpt_client_identity
config.credential.chatgpt_without_login
config.credential.claude_subscription
Expand All @@ -20,6 +28,7 @@ config.credential.empty_oauth
config.credential.google_subscription
config.credential.identity_header
config.credential.key_and_auth_header
config.credential.key_and_aws
config.credential.key_and_oauth
config.credential.no_token
config.credential.oauth_and_auth_header
Expand Down Expand Up @@ -135,6 +144,7 @@ control.redirect_must_be_app_scheme
control.remote.control_section_locked
control.remote.diagnostics_refused
control.remote.shutdown_refused
control.replay_bedrock
control.request_body_gone
control.request_body_truncated
control.request_not_found
Expand Down Expand Up @@ -238,6 +248,8 @@ gw.oauth.status
gw.oauth.unreachable
gw.output_limit.cut
gw.output_limit.withheld
gw.probe.aws_token_expired
gw.probe.bedrock_list_denied
gw.probe.connect
gw.probe.key_rejected
gw.probe.request_failed
Expand All @@ -253,9 +265,14 @@ gw.route.selected_upstream_missing
gw.route.upstream_missing
gw.toolcall.blocked
gw.toolcall.cut
gw.upstream.aws_token_expired
gw.upstream.bedrock_refused
gw.upstream.eventstream_broken
gw.upstream.forward_failed
gw.upstream.rate_limited
gw.upstream.sign_failed
gw.upstream.status
gw.upstream.stream_exception
gw.upstream.timeout
gw.upstream.unreachable
gw.ws.bad_header
Expand Down Expand Up @@ -323,6 +340,7 @@ l1.tls.failed
l1.unreachable
l3.not_streamed
l3.refused
l3.sign_failed
l3.stream_failed
pricing.sheet.bad_multiplier
pricing.sheet.bad_price
Expand Down
47 changes: 43 additions & 4 deletions crates/tw-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,8 @@ slug_enum! {
Gemini = "gemini",
/// ChatGPT 账号登录的 Codex 后端
Chatgpt = "chatgpt",
/// Amazon Bedrock 的 Converse 接口:Bedrock API Key,或者 AWS 访问密钥签名
Bedrock = "bedrock",
}
}

Expand All @@ -110,7 +112,7 @@ slug_enum! {
OpenaiChat = "openai-chat",
OpenaiResponses = "openai-responses",
Gemini = "gemini",
/// 只有企业版接 Bedrock;桌面版不会发出这个词
/// Bedrock 的 Converse。只会是上游的格式:客户端不说它
Bedrock = "bedrock",
}
}
Expand Down Expand Up @@ -627,7 +629,13 @@ pub const MSG_CODES: &str = include_str!("../msg-codes.txt");
/// `/latency` 两个端点和 [`LiveView::tokens_per_sec`] 同版改成从第一个 token 算:以前
/// 从响应头算,非流式请求的响应头要等整段生成完才到,一条就能把速度顶到几万。照 26
/// 写的界面不认那个新事件。
pub const CONTROL_API_VERSION: u32 = 27;
///
/// **28 起有 Bedrock 上游**:[`Protocol`] 多了 `bedrock`,[`ProviderInput::aws`] /
/// [`ProviderView::aws`]([`AwsKeys`]:AWS 访问密钥,每个请求签名)、
/// [`ProviderView::region`] 和 [`ProviderPreview::region`]。Bedrock API Key 走
/// 原来的 `key`,放进 `Authorization: Bearer`。照 27 写的界面解析不了带 `bedrock` 的
/// 上游列表。
pub const CONTROL_API_VERSION: u32 = 28;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
Expand Down Expand Up @@ -1629,8 +1637,14 @@ pub struct ProviderView {
pub headers: Vec<HeaderView>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub oauth: Option<OAuthView>,
/// Bedrock 的 AWS 访问密钥,配置里写的原样。用 API Key 的、别的协议的都是空
#[serde(default, skip_serializing_if = "Option::is_none")]
pub aws: Option<AwsKeys>,
/// Bedrock 的区域:标准地址里的那个,或者 `aws.region`。别的协议是空
#[serde(default, skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
/// 实际生效的协议:`anthropic` / `openai-chat` / `openai-responses` /
/// `gemini`。猜不出来时为空
/// `gemini` / `bedrock`。猜不出来时为空
pub protocol: Option<Protocol>,
/// 协议是配置里写明的,还是按地址推断的
pub protocol_explicit: bool,
Expand Down Expand Up @@ -1691,6 +1705,24 @@ pub struct HeaderView {
pub value: String,
}

/// Bedrock 上游的 AWS 访问密钥:每个请求用它们签名(SigV4)。每一项都可以写
/// `${NAME}` 从环境变量读。视图和保存用的是同一个:配置里写的原样。
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct AwsKeys {
/// 访问密钥 ID
pub access_key_id: String,
/// 私有访问密钥
pub secret_access_key: String,
/// 会话令牌:临时凭证才有
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_token: Option<String>,
/// 签名用的区域。地址是标准的 `https://bedrock-runtime.<区域>.amazonaws.com`
/// 时不用给,从地址读
#[serde(default, skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
}

/// OAuth 凭据,配置里写的原样。**access token 不在这里**:它由网关换发、写回,
/// 界面拿到的那一把很快就过期。
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
Expand Down Expand Up @@ -2423,7 +2455,10 @@ pub struct ProviderInput {
/// OAuth。修改时默认保持原样
#[serde(default)]
pub oauth: OAuthChange,
/// `anthropic` / `openai-chat` / `openai-responses` / `gemini`。
/// Bedrock 的 AWS 访问密钥。和 `key`(Bedrock API Key)二选一;不给就是不用
#[serde(default, skip_serializing_if = "Option::is_none")]
pub aws: Option<AwsKeys>,
/// `anthropic` / `openai-chat` / `openai-responses` / `gemini` / `bedrock`。
/// 不给就按地址推断
#[serde(default, skip_serializing_if = "Option::is_none")]
pub protocol: Option<Protocol>,
Expand Down Expand Up @@ -2473,6 +2508,10 @@ pub struct ProviderPreview {
/// API 密钥放在哪个请求头里:`x-api-key` / `authorization` / `x-goog-api-key`。
/// 选定了协议按选定的算,否则按推断出的
pub auth_header: String,
/// 标准 Bedrock 地址(`https://bedrock-runtime.<区域>.amazonaws.com`)里的区域。
/// 别的地址是空
#[serde(default, skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
}

slug_enum! {
Expand Down
103 changes: 103 additions & 0 deletions crates/tw-bedrock/src/beta.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
//! Anthropic 的 beta 功能在 Bedrock 上怎么开。
//!
//! 客户端直连 Anthropic 时把 beta 写在 `anthropic-beta` 请求头里。转成 Converse 之后
//! 没有这个头可发,Claude 的 beta 放进请求体的 `additionalModelRequestFields.anthropic_beta`
//! —— Claude Code 自己连 Bedrock 时也是把头里的值搬进请求体的 `anthropic_beta`。
//!
//! **只带 Bedrock 认的那几个。**直连 Anthropic 的客户端会带上一整串只有 Anthropic
//! 认的 beta(`oauth-…`、`prompt-caching-scope-…` 这些),原样交给 Bedrock,整个请求
//! 会因为不认识的 beta 被拒。名单取自 AWS 为 Bedrock 上的 Claude 列出的 beta,只留
//! 转成 Converse 之后还有意义的:服务端工具、上下文管理、压缩这些对应的请求字段在
//! 转换时已经丢掉了,只开 beta 没有用处。

use serde_json::{Map, Value};

/// Bedrock 上的 Claude 认、转成 Converse 之后仍然有用的 beta。
pub const SUPPORTED: &[&str] = &[
// 思考和工具调用交替进行(Claude 4 起)
"interleaved-thinking-2025-05-14",
// 100 万 token 的上下文
"context-1m-2025-08-07",
// Claude 3.7 Sonnet 的 128k 输出
"output-128k-2025-02-19",
// 工具调用少用一些输出 token
"token-efficient-tools-2025-02-19",
// 工具参数边生成边流出来
"fine-grained-tool-streaming-2025-05-14",
];

/// 客户端 `anthropic-beta` 头里 Bedrock 认的那些,去重、保持顺序。头可能分几行写,
/// 每行也可能是逗号隔开的一串。
pub fn supported<'a>(header_values: impl IntoIterator<Item = &'a str>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for v in header_values {
for b in v.split(',').map(str::trim) {
if SUPPORTED.contains(&b) && !out.iter().any(|x| x == b) {
out.push(b.to_string());
}
}
}
out
}

/// 把 beta 写进一份 Converse 请求体的 `additionalModelRequestFields.anthropic_beta`。
/// 请求体读不成 JSON 对象时原样返回 `None`,不猜。
pub fn with_betas(body: &[u8], betas: &[String]) -> Option<Vec<u8>> {
if betas.is_empty() {
return None;
}
let mut v: Value = serde_json::from_slice(body).ok()?;
let fields = v
.as_object_mut()?
.entry("additionalModelRequestFields")
.or_insert_with(|| Value::Object(Map::new()))
.as_object_mut()?;
fields.insert(
"anthropic_beta".into(),
Value::Array(betas.iter().cloned().map(Value::String).collect()),
);
serde_json::to_vec(&v).ok()
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn only_what_bedrock_takes_is_kept_once_in_order() {
let got = supported([
"claude-code-20250219,interleaved-thinking-2025-05-14, oauth-2025-04-20",
"context-1m-2025-08-07,interleaved-thinking-2025-05-14",
"prompt-caching-scope-2026-01-05",
]);
assert_eq!(
got,
["interleaved-thinking-2025-05-14", "context-1m-2025-08-07"]
);
assert!(supported(["claude-code-20250219"]).is_empty());
}

#[test]
fn betas_join_whatever_else_goes_to_the_model() {
let body =
br#"{"messages":[],"additionalModelRequestFields":{"thinking":{"type":"adaptive"}}}"#;
let out = with_betas(body, &["context-1m-2025-08-07".to_string()]).unwrap();
let v: Value = serde_json::from_slice(&out).unwrap();
assert_eq!(
v["additionalModelRequestFields"],
serde_json::json!({
"thinking": {"type": "adaptive"},
"anthropic_beta": ["context-1m-2025-08-07"],
})
);
}

#[test]
fn a_body_without_the_pocket_gets_one_and_nothing_is_touched_without_betas() {
let out = with_betas(br#"{"messages":[]}"#, &["x".to_string()]).unwrap();
let v: Value = serde_json::from_slice(&out).unwrap();
assert_eq!(v["additionalModelRequestFields"]["anthropic_beta"][0], "x");
assert!(with_betas(br#"{"messages":[]}"#, &[]).is_none());
assert!(with_betas(b"not json", &["x".to_string()]).is_none());
}
}
2 changes: 2 additions & 0 deletions crates/tw-bedrock/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Amazon Bedrock 在线路上要的东西,两个网关共用。
//!
//! - [`endpoint`]:区域、runtime 和控制面的地址、模型 id 怎么写进路径
//! - [`beta`]:客户端的 `anthropic-beta` 里哪些能带给 Bedrock 上的 Claude
//! - [`sign`]:SigV4 签名,以及「带 API Key 就不签」这条规则
//! - [`eventstream`]:ConverseStream 的二进制帧 → SSE
//! - [`catalog`]:一个区域能路由到哪些模型
Expand All @@ -13,6 +14,7 @@
//! 这是第一层:只依赖第三方 crate 和第一层的彼此(`tw-dialect` 的
//! `layer_one_depends_only_on_itself` 守着)。

pub mod beta;
pub mod catalog;
pub mod endpoint;
pub mod error;
Expand Down
2 changes: 2 additions & 0 deletions crates/tw-config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ tw-api = { workspace = true }
tw-secret = { workspace = true }
# 校验要认得出配置里写到的内置脱敏规则 id
tw-guard = { workspace = true }
# Bedrock 的区域:认标准地址、校验区域代码,和转发时用的是同一份
tw-bedrock = { workspace = true }
regex = { workspace = true }
tw-pricing = { workspace = true }
# 凭据轮换要把一个标量写回 config.yaml。**span 补丁,不是
Expand Down
Loading
Loading