mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 16:01:05 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eece08a4a2 | ||
|
|
4bdb15ccd9 | ||
|
|
aad6304a33 | ||
|
|
db22550e61 |
@@ -923,7 +923,7 @@ impl Operation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Responses 要求本轮执行托管搜索时,按账号快照选择搜索目标
|
||||
/// 请求强制执行托管搜索时,按账号目录选择搜索目标
|
||||
#[must_use]
|
||||
pub fn requires_web_search(&self) -> bool {
|
||||
matches!(self, Self::Generate(request) if {
|
||||
@@ -936,6 +936,16 @@ impl Operation {
|
||||
})
|
||||
}
|
||||
|
||||
/// 原生单次搜索可通过账号的搜索目标解析未选档的模型组
|
||||
#[must_use]
|
||||
pub fn is_native_web_search(&self) -> bool {
|
||||
matches!(self, Self::Generate(request) if {
|
||||
let payload = request.protocol_payload();
|
||||
payload.protocol() == gateway_protocol::genai::GENAI_PROTOCOL
|
||||
&& gateway_protocol::genai::is_standalone_web_search(payload.body(), payload.context())
|
||||
})
|
||||
}
|
||||
|
||||
/// 仅提取本次正文明确声明的推理档位,路由不继承 Provider 会话默认值
|
||||
pub(crate) fn requested_reasoning_effort(&self) -> Option<String> {
|
||||
let observation = match self {
|
||||
|
||||
@@ -656,6 +656,7 @@ pub struct DirectAccountModel<'a> {
|
||||
/// 已绑定 Provider 的请求候选;模型端点携带真实上游模型,原生端点不虚构模型
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProviderCandidate {
|
||||
dedicated_web_search: bool,
|
||||
provider: ProviderKind,
|
||||
requires_direct_authentication: bool,
|
||||
upstream_model: Option<UpstreamModelId>,
|
||||
@@ -664,6 +665,12 @@ pub struct ProviderCandidate {
|
||||
}
|
||||
|
||||
impl ProviderCandidate {
|
||||
/// 搜索目标和账号范围已经由目录解析,Provider 依此选择上游请求类型
|
||||
#[must_use]
|
||||
pub const fn uses_dedicated_web_search(&self) -> bool {
|
||||
self.dedicated_web_search
|
||||
}
|
||||
|
||||
/// 模型按直连账号身份选择,Provider 必须在发送前核对实际凭据。
|
||||
#[must_use]
|
||||
pub const fn requires_direct_authentication(&self) -> bool {
|
||||
|
||||
@@ -1643,6 +1643,7 @@ impl RuntimeSnapshot {
|
||||
|| account_scope.provider_kinds().clone(),
|
||||
|provider| BTreeSet::from([provider.clone()]),
|
||||
);
|
||||
let search = operation.requires_web_search();
|
||||
let mut invalid_variant = false;
|
||||
let mut group_model_denied = false;
|
||||
let mut search_unavailable = false;
|
||||
@@ -1665,216 +1666,243 @@ impl RuntimeSnapshot {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut candidate_scope = Arc::clone(&account_scope);
|
||||
let upstream_model =
|
||||
if let Some(group) = self.model_group(provider, upstream_model.as_str()) {
|
||||
if group.match_operation(operation, &requirements).is_none() {
|
||||
continue;
|
||||
}
|
||||
let group = self.model_group(provider, upstream_model.as_str());
|
||||
let group_search_targets = group
|
||||
.and_then(|group| group.dedicated_web_search.as_deref())
|
||||
.filter(|_| operation.is_native_web_search());
|
||||
let mut search_variants = None;
|
||||
let source = if let Some(group) = group {
|
||||
if group.match_operation(operation, &requirements).is_none() {
|
||||
continue;
|
||||
}
|
||||
if group_search_targets.is_some() {
|
||||
// 独立搜索只执行搜索型号,任一获准的具体成员都能证明同账号的分组资格
|
||||
search_variants = Some(group.reasoning_variants.values());
|
||||
None
|
||||
} else {
|
||||
let effort = operation.requested_reasoning_effort();
|
||||
let Some(variant) = effort
|
||||
.as_ref()
|
||||
.and_then(|effort| group.reasoning_variants.get(effort))
|
||||
.and_then(|level| group.reasoning_variants.get(level))
|
||||
else {
|
||||
invalid_variant = true;
|
||||
continue;
|
||||
};
|
||||
// 空集合在 restricted_to 中表示不收窄,必须先拒绝没有来源的档位
|
||||
if variant.accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
account_scope
|
||||
.restricted_to(&BTreeSet::from([provider.clone()]), &variant.accounts),
|
||||
);
|
||||
&variant.model
|
||||
} else {
|
||||
&upstream_model
|
||||
};
|
||||
if enforce_routing_policy
|
||||
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
{
|
||||
group_model_denied = true;
|
||||
continue;
|
||||
}
|
||||
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
||||
if enforce_routing_policy
|
||||
&& !candidate_scope.allows_provider_model(provider, upstream_model.as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let capabilities = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
if operation.requires_native_protocol()
|
||||
&& !capabilities.is_some_and(|model| {
|
||||
model
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
})
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 直连模型需要原生能力,不能借用插件为同名模型声明的账号与能力。
|
||||
if direct_model.is_some() && capabilities.is_none() {
|
||||
continue;
|
||||
}
|
||||
let contributions: Vec<_> = self
|
||||
.contributed_models()
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
direct_model.is_none()
|
||||
&& &model.provider == provider
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
let Some(emulated) = capabilities.match_operation(operation, &requirements)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
emulated
|
||||
}
|
||||
// 固定账号诊断由指定 Provider 向上游核实,停用账号可能从未出现在公开目录
|
||||
None if enforce_routing_policy
|
||||
&& (known_model
|
||||
|| self.exhaustive_provider_catalogs.contains(provider)) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
None => BTreeSet::new(),
|
||||
Some((&variant.model, Some(&variant.accounts)))
|
||||
}
|
||||
} else {
|
||||
let native =
|
||||
capabilities.and_then(|value| value.match_operation(operation, &requirements));
|
||||
let capable_accounts: BTreeSet<_> = contributions
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
model.protocol == operation.protocol()
|
||||
&& model
|
||||
.capabilities
|
||||
.match_operation(operation, &requirements)
|
||||
.is_some()
|
||||
})
|
||||
.flat_map(|model| model.accounts.iter())
|
||||
.filter(|account| {
|
||||
candidate_scope.account_provider(account) == Some(provider)
|
||||
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if native.is_some() {
|
||||
// 这些账号实际由适配器执行,不能借用同名原生模型的能力
|
||||
let mut restricted = candidate_scope.as_ref().clone();
|
||||
for account in contributions.iter().flat_map(|model| &model.accounts) {
|
||||
if !capable_accounts.contains(account) {
|
||||
restricted = restricted.excluding_account(account.clone());
|
||||
}
|
||||
}
|
||||
candidate_scope = Arc::new(restricted);
|
||||
} else {
|
||||
// restricted_to 的空集合表示不收窄,因此必须先拒绝空候选
|
||||
if capable_accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
);
|
||||
}
|
||||
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
Some((&upstream_model, None))
|
||||
};
|
||||
let sources = source.into_iter().chain(
|
||||
search_variants
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|variant| (&variant.model, Some(&variant.accounts))),
|
||||
);
|
||||
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for (upstream_model, accounts) in sources {
|
||||
if accounts.is_some_and(BTreeSet::is_empty) {
|
||||
continue;
|
||||
}
|
||||
native.unwrap_or_default()
|
||||
};
|
||||
// 原生输出上限属于具体型号与账号,适配器账号沿用自己的能力合同
|
||||
if let (Some(requested), Some(model)) =
|
||||
(requirements.requested_output_tokens(), capabilities)
|
||||
{
|
||||
let mut excluded = model
|
||||
.account_metadata
|
||||
.iter()
|
||||
.filter_map(|(id, metadata)| {
|
||||
(metadata
|
||||
.max_output_tokens
|
||||
.is_some_and(|limit| requested > limit)
|
||||
&& !contributions
|
||||
.iter()
|
||||
.any(|adapter| adapter.accounts.contains(id))
|
||||
&& candidate_scope.allows(id))
|
||||
.then_some(id)
|
||||
let mut candidate_scope = accounts.map_or_else(
|
||||
|| Arc::clone(&account_scope),
|
||||
|accounts| {
|
||||
Arc::new(
|
||||
account_scope
|
||||
.restricted_to(&BTreeSet::from([provider.clone()]), accounts),
|
||||
)
|
||||
},
|
||||
);
|
||||
if enforce_routing_policy
|
||||
&& candidate_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
{
|
||||
group_model_denied = true;
|
||||
continue;
|
||||
}
|
||||
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
||||
if enforce_routing_policy
|
||||
&& !candidate_scope.allows_provider_model(provider, upstream_model.as_str())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let capabilities = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
if operation.requires_native_protocol()
|
||||
&& !capabilities.is_some_and(|model| {
|
||||
model
|
||||
.native_generation_protocols
|
||||
.contains(operation.protocol())
|
||||
})
|
||||
.peekable();
|
||||
if excluded.peek().is_some() {
|
||||
let mut narrowed = candidate_scope.as_ref().clone();
|
||||
narrowed.exclude_accounts(excluded.cloned());
|
||||
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// 直连模型需要原生能力,不能借用插件为同名模型声明的账号与能力。
|
||||
if direct_model.is_some() && capabilities.is_none() {
|
||||
continue;
|
||||
}
|
||||
let contributions: Vec<_> = self
|
||||
.contributed_models()
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
direct_model.is_none()
|
||||
&& &model.provider == provider
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
let Some(emulated) =
|
||||
capabilities.match_operation(operation, &requirements)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
emulated
|
||||
}
|
||||
// 固定账号诊断由指定 Provider 向上游核实,停用账号可能从未出现在公开目录
|
||||
None if enforce_routing_policy
|
||||
&& (known_model
|
||||
|| self.exhaustive_provider_catalogs.contains(provider)) =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
None => BTreeSet::new(),
|
||||
}
|
||||
} else {
|
||||
let native = capabilities
|
||||
.and_then(|value| value.match_operation(operation, &requirements));
|
||||
let capable_accounts: BTreeSet<_> = contributions
|
||||
.iter()
|
||||
.filter(|model| {
|
||||
model.protocol == operation.protocol()
|
||||
&& model
|
||||
.capabilities
|
||||
.match_operation(operation, &requirements)
|
||||
.is_some()
|
||||
})
|
||||
.flat_map(|model| model.accounts.iter())
|
||||
.filter(|account| {
|
||||
candidate_scope.account_provider(account) == Some(provider)
|
||||
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
if native.is_some() {
|
||||
// 这些账号实际由适配器执行,不能借用同名原生模型的能力
|
||||
let mut restricted = candidate_scope.as_ref().clone();
|
||||
for account in contributions.iter().flat_map(|model| &model.accounts) {
|
||||
if !capable_accounts.contains(account) {
|
||||
restricted = restricted.excluding_account(account.clone());
|
||||
}
|
||||
}
|
||||
candidate_scope = Arc::new(restricted);
|
||||
} else {
|
||||
// restricted_to 的空集合表示不收窄,因此必须先拒绝空候选
|
||||
if capable_accounts.is_empty() {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
);
|
||||
}
|
||||
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(narrowed);
|
||||
native.unwrap_or_default()
|
||||
};
|
||||
// 原生输出上限属于具体型号与账号,适配器账号沿用自己的能力合同
|
||||
if let (Some(requested), Some(model)) =
|
||||
(requirements.requested_output_tokens(), capabilities)
|
||||
{
|
||||
let mut excluded = model
|
||||
.account_metadata
|
||||
.iter()
|
||||
.filter_map(|(id, metadata)| {
|
||||
(metadata
|
||||
.max_output_tokens
|
||||
.is_some_and(|limit| requested > limit)
|
||||
&& !contributions
|
||||
.iter()
|
||||
.any(|adapter| adapter.accounts.contains(id))
|
||||
&& candidate_scope.allows(id))
|
||||
.then_some(id)
|
||||
})
|
||||
.peekable();
|
||||
if excluded.peek().is_some() {
|
||||
let mut narrowed = candidate_scope.as_ref().clone();
|
||||
narrowed.exclude_accounts(excluded.cloned());
|
||||
if !narrowed.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(narrowed);
|
||||
}
|
||||
}
|
||||
if let Some(model) = capabilities
|
||||
&& let Some(search_models) = group_search_targets
|
||||
.or(model.dedicated_web_search.as_deref().filter(|_| search))
|
||||
{
|
||||
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
|
||||
for account in model.account_metadata.keys() {
|
||||
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(target) = search_models.get(account) else {
|
||||
search_unavailable = true;
|
||||
continue;
|
||||
};
|
||||
if !candidate_scope.allows_model_pair(
|
||||
account,
|
||||
upstream_model.as_str(),
|
||||
target.as_str(),
|
||||
) {
|
||||
group_model_denied |=
|
||||
candidate_scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
let limit = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(target))
|
||||
.and_then(|model| model.account_metadata.get(account))
|
||||
.and_then(|meta| meta.max_output_tokens);
|
||||
if requirements
|
||||
.requested_output_tokens()
|
||||
.zip(limit)
|
||||
.is_some_and(|(requested, limit)| requested > limit)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
targets
|
||||
.entry((target, emulated_features.clone()))
|
||||
.or_default()
|
||||
.insert(account.clone());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
candidates.push(ProviderCandidate {
|
||||
dedicated_web_search: false,
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(upstream_model.clone()),
|
||||
emulated_features,
|
||||
account_scope: candidate_scope,
|
||||
});
|
||||
}
|
||||
if operation.requires_web_search()
|
||||
&& let Some(model) = capabilities
|
||||
&& let Some(search_models) = &model.dedicated_web_search
|
||||
{
|
||||
// 仅目录中同时拥有请求型号和搜索目标的账号可执行本次搜索
|
||||
let mut targets = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for account in model.account_metadata.keys() {
|
||||
if !candidate_scope.allows_model(account, upstream_model.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Some(target) = search_models.get(account) else {
|
||||
search_unavailable = true;
|
||||
continue;
|
||||
};
|
||||
if !candidate_scope.allows_model_pair(
|
||||
account,
|
||||
upstream_model.as_str(),
|
||||
target.as_str(),
|
||||
) {
|
||||
group_model_denied |=
|
||||
candidate_scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
let limit = self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(target))
|
||||
.and_then(|model| model.account_metadata.get(account))
|
||||
.and_then(|meta| meta.max_output_tokens);
|
||||
if requirements
|
||||
.requested_output_tokens()
|
||||
.zip(limit)
|
||||
.is_some_and(|(requested, limit)| requested > limit)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
targets.entry(target).or_default().insert(account.clone());
|
||||
}
|
||||
for (target, accounts) in targets {
|
||||
candidates.push(ProviderCandidate {
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features: emulated_features.clone(),
|
||||
account_scope: Arc::new(
|
||||
candidate_scope.restricted_to(&Default::default(), &accounts),
|
||||
),
|
||||
});
|
||||
}
|
||||
continue;
|
||||
for ((target, emulated_features), accounts) in targets {
|
||||
candidates.push(ProviderCandidate {
|
||||
dedicated_web_search: true,
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features,
|
||||
account_scope: Arc::new(
|
||||
account_scope.restricted_to(&Default::default(), &accounts),
|
||||
),
|
||||
});
|
||||
}
|
||||
candidates.push(ProviderCandidate {
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(upstream_model.clone()),
|
||||
emulated_features,
|
||||
account_scope: candidate_scope,
|
||||
});
|
||||
}
|
||||
|
||||
// 冷启动或目录不可读时不能按 Provider 名称猜测模型归属
|
||||
@@ -1998,6 +2026,7 @@ impl RuntimeSnapshot {
|
||||
});
|
||||
}
|
||||
let candidate = ProviderCandidate {
|
||||
dedicated_web_search: false,
|
||||
requires_direct_authentication: false,
|
||||
provider: provider.clone(),
|
||||
upstream_model: upstream_model.cloned(),
|
||||
|
||||
@@ -113,7 +113,12 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family").unwrap(),
|
||||
caps().with_reasoning_variants(variants),
|
||||
caps()
|
||||
.with_reasoning_variants(variants)
|
||||
.with_dedicated_web_search(BTreeMap::from([(
|
||||
declared.clone(),
|
||||
UpstreamModelId::new("search").unwrap(),
|
||||
)])),
|
||||
)
|
||||
.with_presentation(
|
||||
ModelPresentation::default()
|
||||
@@ -184,6 +189,34 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
let native_search = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object(
|
||||
"genai",
|
||||
serde_json::json!({"tools":[{"googleSearch":{}}]})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
)
|
||||
.unwrap()
|
||||
.with_context(
|
||||
serde_json::json!({"stream":false})
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.clone(),
|
||||
),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
);
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&PublicModelId::new("alias").unwrap(),
|
||||
&native_search,
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
let old_account =
|
||||
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
|
||||
assert!(matches!(
|
||||
@@ -242,7 +275,31 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
Arc::clone(scope.directory()),
|
||||
ClientRoutingScope::all_accounts(),
|
||||
);
|
||||
let routed = snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&native_search,
|
||||
Arc::new(all.clone()),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let [target] = routed.candidates() else {
|
||||
panic!("one search target across multiple allowed members")
|
||||
};
|
||||
assert_eq!(target.upstream_model().unwrap().as_str(), "search");
|
||||
assert!(target.account_scope().allows(&declared));
|
||||
assert!(!target.account_scope().allows(&other));
|
||||
assert!(!target.account_scope().allows(&high_only));
|
||||
let only_high_scope = all.restricted_to(&BTreeSet::new(), &BTreeSet::from([high_only]));
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&base,
|
||||
&native_search,
|
||||
Arc::new(only_high_scope.clone()),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
));
|
||||
let only_high = snapshot.public_model_profiles_for_scope(&only_high_scope);
|
||||
assert_eq!(only_high.len(), 2);
|
||||
for profile in only_high {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
mod request;
|
||||
mod response;
|
||||
|
||||
pub use request::is_standalone_web_search;
|
||||
pub(crate) use request::{request_facts, thinking_level};
|
||||
pub use response::{
|
||||
GenerateContentObservation, GenerationFinish, UsageMetadata, has_finish_signal,
|
||||
|
||||
@@ -49,6 +49,30 @@ pub(crate) fn request_facts(body: &Map<String, Value>, facts: &mut RequestFacts)
|
||||
});
|
||||
}
|
||||
|
||||
/// 原生独立搜索使用单次 JSON 调用,工具声明中的搜索选项保留给上游
|
||||
#[must_use]
|
||||
pub fn is_standalone_web_search(body: &Map<String, Value>, context: &Map<String, Value>) -> bool {
|
||||
if context.get("stream").and_then(Value::as_bool) != Some(false)
|
||||
|| thinking_config(body).is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let Some([tool]) = body
|
||||
.get("tools")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
tool.as_object().is_some_and(|tool| {
|
||||
tool.len() == 1
|
||||
&& tool
|
||||
.get("googleSearch")
|
||||
.or_else(|| tool.get("google_search"))
|
||||
.is_some_and(Value::is_object)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn thinking_level(body: &Map<String, Value>) -> Option<&str> {
|
||||
field(thinking_config(body), "thinkingLevel", "thinking_level")?
|
||||
.as_str()
|
||||
|
||||
@@ -41,7 +41,7 @@ impl AntigravityProvider {
|
||||
let started = Instant::now();
|
||||
let affinity =
|
||||
super::affinity::session_key(request.operation(), ctx.client_api_key_ref(), &model);
|
||||
let search = request.operation().requires_web_search();
|
||||
let search = request.candidate().uses_dedicated_web_search();
|
||||
let selected = self
|
||||
.select_account(&model, &ctx, affinity.as_ref(), search)
|
||||
.await?;
|
||||
@@ -89,7 +89,8 @@ impl AntigravityProvider {
|
||||
Some(model.as_str().to_owned()),
|
||||
selected.account.id().clone(),
|
||||
Box::new(move |operation, headers| Box::pin(async move {
|
||||
if operation.requires_web_search() != search {
|
||||
let requests_search = operation.requires_web_search() || (search && operation.is_native_web_search());
|
||||
if requests_search != search {
|
||||
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
||||
}
|
||||
let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) {
|
||||
|
||||
@@ -861,16 +861,11 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{PublicModelId, RoutingContext},
|
||||
};
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
{
|
||||
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
|
||||
let (_, bytes) = catalog.as_mut().unwrap();
|
||||
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
|
||||
value["webSearchModelIds"] = json!(["fixture-model"]);
|
||||
*bytes = value.to_string().into();
|
||||
}
|
||||
let snapshot = search_snapshot(&fixture).await;
|
||||
for options in [
|
||||
json!({"user_location":{"type":"approximate","approximate":{"country":"US"}}}),
|
||||
json!({"search_context_size":"high"}),
|
||||
@@ -880,11 +875,19 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new("fixture-model").unwrap(),
|
||||
&operation,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let error = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
ProviderRequest::new(operation, request(false).candidate().clone()),
|
||||
ProviderRequest::new(operation, plan.candidates()[0].clone()),
|
||||
context(frozen_profile(), CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
@@ -905,21 +908,19 @@ async fn unsupported_chat_search_options_fail_before_sending_and_release_the_lea
|
||||
assert!(upstream.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
async fn search_snapshot(fixture: &Fixture) -> gateway_core::routing::RuntimeSnapshot {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
event::GatewayEvent,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{ConfigRevision, ProviderModel, PublicModelId, RoutingContext, RuntimeSnapshot},
|
||||
routing::{ConfigRevision, ProviderModel, RuntimeSnapshot},
|
||||
settings::SettingsValues,
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
{
|
||||
let mut catalog = fixture.store.primary().catalog.lock().unwrap();
|
||||
let (_, bytes) = catalog.as_mut().unwrap();
|
||||
let mut value: serde_json::Value = serde_json::from_slice(bytes).unwrap();
|
||||
for level in ["low", "high"] {
|
||||
value["models"][format!("family-{level}")] = json!({"displayName": level});
|
||||
}
|
||||
value["groupedModels"] = json!({"family":{"supportedThinkingLevels":[{"thinkingSuffix":"low"},{"thinkingSuffix":"high"}]}});
|
||||
value["webSearchModelIds"] = json!(["search-only", "not-selected"]);
|
||||
*bytes = value.to_string().into();
|
||||
}
|
||||
@@ -930,7 +931,7 @@ async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
.iter()
|
||||
.any(|m| m.upstream_model().as_str() == "search-only")
|
||||
);
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
SettingsValues::new(1, "smart", Default::default(), None, None),
|
||||
vec![kind.clone()],
|
||||
@@ -946,7 +947,115 @@ async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
.collect(),
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_search_resolves_groups_and_preserves_explicit_models_and_grounding() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{PublicModelId, RoutingContext},
|
||||
validation::RoutingError,
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let snapshot = search_snapshot(&fixture).await;
|
||||
let body = json!({
|
||||
"contents":[{"role":"user","parts":[{"text":"Find the source"}]}],
|
||||
"tools":[{"googleSearch":{"enhancedContent":{"imageSearch":{"maxResultCount":5}}}}],
|
||||
"generationConfig":{"candidateCount":1}
|
||||
});
|
||||
let operation = |body: &serde_json::Value, stream| {
|
||||
Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone())
|
||||
.unwrap()
|
||||
.with_context(json!({"stream":stream}).as_object().unwrap().clone()),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
)
|
||||
};
|
||||
let plan = |model: &str, op: &Operation| {
|
||||
snapshot.plan(
|
||||
&PublicModelId::new(model).unwrap(),
|
||||
op,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
};
|
||||
let grounded = json!({"candidates":[{"content":{"parts":[{"text":"Found"}]},"finishReason":"STOP",
|
||||
"groundingMetadata":{"groundingChunks":[{"web":{"uri":"https://example.org/source"}}]}}]});
|
||||
for (requested, target, kind) in [
|
||||
("family", "search-only", "web_search"),
|
||||
("family-low", "family-low", "agent"),
|
||||
] {
|
||||
let op = operation(&body, false);
|
||||
let route = plan(requested, &op).unwrap();
|
||||
let [candidate] = route.candidates() else {
|
||||
panic!("one eligible target")
|
||||
};
|
||||
Mock::given(path("/v1internal:generateContent"))
|
||||
.and(body_partial_json(
|
||||
json!({"model":target,"requestType":kind,"request":body}),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":grounded})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
ProviderRequest::new(op, candidate.clone()),
|
||||
context(frozen_profile(), CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
let wire = events
|
||||
.iter()
|
||||
.find_map(|event| event.wire_event()?.raw_json_body())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<serde_json::Value>(wire).unwrap(),
|
||||
grounded
|
||||
);
|
||||
released(&fixture).await;
|
||||
}
|
||||
let mut mixed = body.clone();
|
||||
mixed["tools"]
|
||||
.as_array_mut()
|
||||
.unwrap()
|
||||
.push(json!({"functionDeclarations":[{"name":"lookup"}]}));
|
||||
let mut explicit = body.clone();
|
||||
explicit["generationConfig"]["thinkingConfig"] = json!({"thinkingLevel":"UNSUPPORTED"});
|
||||
for op in [
|
||||
operation(&body, true),
|
||||
operation(&mixed, false),
|
||||
operation(&explicit, false),
|
||||
] {
|
||||
assert!(matches!(
|
||||
plan("family", &op),
|
||||
Err(RoutingError::InvalidReasoningVariant)
|
||||
));
|
||||
}
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn chat_search_uses_catalog_target_and_delivers_grounded_terminal() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
event::GatewayEvent,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{PublicModelId, RoutingContext},
|
||||
};
|
||||
let server = MockServer::start().await;
|
||||
let fixture = Fixture::new(&server.uri());
|
||||
let snapshot = search_snapshot(&fixture).await;
|
||||
let body = json!({"model":"fixture-model","stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"你好"}],"web_search_options":{}});
|
||||
let op = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
|
||||
@@ -636,6 +636,7 @@ impl CodexBackendClient {
|
||||
} = *route;
|
||||
let exchange = execute_prepared_response_create_request_stream(
|
||||
&websocket_request,
|
||||
request.generate(),
|
||||
prepared,
|
||||
context.response_control.cloned(),
|
||||
context
|
||||
|
||||
@@ -609,6 +609,7 @@ fn continuation_unavailable(
|
||||
|
||||
pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
request: &CodexWebSocketRequest,
|
||||
generate: bool,
|
||||
prepared: PreparedWebSocket,
|
||||
response_control: Option<gateway_core::engine::response_control::ResponseControl>,
|
||||
trace: gateway_core::diagnostics::TraceContext,
|
||||
@@ -683,6 +684,7 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
let connection_local_available = lease.is_some() && !websocket.is_closed();
|
||||
let pool_return = lease.map(|lease| WebSocketStreamPoolReturn {
|
||||
lease,
|
||||
reused,
|
||||
created_at,
|
||||
lifetime,
|
||||
continuation,
|
||||
@@ -693,7 +695,7 @@ pub(crate) async fn execute_prepared_response_create_request_stream(
|
||||
websocket,
|
||||
metadata,
|
||||
pool_return,
|
||||
reused,
|
||||
generate,
|
||||
stream_idle_timeout,
|
||||
trace,
|
||||
response_control,
|
||||
|
||||
@@ -28,6 +28,7 @@ use super::{
|
||||
|
||||
pub(in crate::transport::websocket) struct WebSocketStreamPoolReturn {
|
||||
pub(in crate::transport::websocket) lease: WebSocketPoolLease,
|
||||
pub(in crate::transport::websocket) reused: bool,
|
||||
pub(in crate::transport::websocket) lifetime: super::super::pool::WebSocketConnectionLifetime,
|
||||
pub(in crate::transport::websocket) created_at: tokio::time::Instant,
|
||||
pub(in crate::transport::websocket) continuation: WebSocketContinuationState,
|
||||
@@ -63,9 +64,9 @@ impl StreamWebSocketDiscardReason {
|
||||
|
||||
pub(in crate::transport::websocket) async fn stream_websocket_response(
|
||||
mut websocket: PumpedWebSocket,
|
||||
metadata: CodexWebSocketConnectionMetadata,
|
||||
mut metadata: CodexWebSocketConnectionMetadata,
|
||||
pool_return: Option<WebSocketStreamPoolReturn>,
|
||||
reused_connection: bool,
|
||||
generate: bool,
|
||||
stream_idle_timeout: Option<Duration>,
|
||||
trace: TraceContext,
|
||||
response_control: Option<ResponseControl>,
|
||||
@@ -76,7 +77,17 @@ pub(in crate::transport::websocket) async fn stream_websocket_response(
|
||||
.and_then(ResponseControl::connection_cancellation)
|
||||
.cloned();
|
||||
let websocket_connection_id = websocket.connection_id();
|
||||
let response_metadata = metadata.clone();
|
||||
let mut response_metadata = metadata.clone();
|
||||
// 握手 ETag 留给首次生成;预热时保留池中快照,生成时只保留本次交付的副本
|
||||
let omit_etag = if generate {
|
||||
&mut metadata.response_metadata
|
||||
} else {
|
||||
&mut response_metadata.response_metadata
|
||||
};
|
||||
omit_etag.models_etag = None;
|
||||
omit_etag
|
||||
.client_headers
|
||||
.retain(|(name, _)| !name.eq_ignore_ascii_case("x-models-etag"));
|
||||
let rate_limit_updates = Arc::new(Mutex::new(Vec::new()));
|
||||
let rate_limit_updates_for_task = Arc::clone(&rate_limit_updates);
|
||||
let response_metadata_updates = Arc::new(Mutex::new(CodexWebSocketResponseMetadataUpdate {
|
||||
@@ -97,7 +108,6 @@ pub(in crate::transport::websocket) async fn stream_websocket_response(
|
||||
websocket,
|
||||
metadata,
|
||||
pool_return,
|
||||
reused_connection,
|
||||
stream_idle_timeout,
|
||||
first_reply: Some(first_reply),
|
||||
delivery: WebSocketStreamDelivery {
|
||||
@@ -145,7 +155,6 @@ struct WebSocketStreamForwardState {
|
||||
websocket: PumpedWebSocket,
|
||||
metadata: CodexWebSocketConnectionMetadata,
|
||||
pool_return: Option<WebSocketStreamPoolReturn>,
|
||||
reused_connection: bool,
|
||||
stream_idle_timeout: Option<Duration>,
|
||||
rate_limit_updates: CodexWebSocketRateLimitUpdates,
|
||||
response_metadata_updates: CodexWebSocketResponseMetadataUpdates,
|
||||
@@ -199,7 +208,6 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
||||
mut websocket,
|
||||
mut metadata,
|
||||
pool_return,
|
||||
reused_connection,
|
||||
stream_idle_timeout,
|
||||
rate_limit_updates,
|
||||
response_metadata_updates,
|
||||
@@ -207,6 +215,7 @@ async fn forward_websocket_response_stream(state: WebSocketStreamForwardState) {
|
||||
delivery,
|
||||
} = state;
|
||||
let trace = &delivery.trace;
|
||||
let reused_connection = pool_return.as_ref().is_some_and(|pool| pool.reused);
|
||||
let mut pool_return = pool_return;
|
||||
let mut continuation = pool_return
|
||||
.as_mut()
|
||||
|
||||
@@ -24,7 +24,7 @@ pub struct CodexWebSocketPoolKey {
|
||||
account_id: String,
|
||||
conversation_id: String,
|
||||
connection_profile: String,
|
||||
response_exclusions: Vec<String>,
|
||||
response_exclusions: Vec<(&'static str, String)>,
|
||||
installation_id: Option<String>,
|
||||
routing_affinity_id: Option<Uuid>,
|
||||
fedramp_routing: bool,
|
||||
@@ -69,11 +69,15 @@ impl CodexWebSocketPoolKey {
|
||||
|
||||
/// 上游只在握手时读取响应排除项,精确续接也必须匹配最终发出的头值
|
||||
pub(crate) fn with_response_exclusions(mut self, opening_headers: &[(String, String)]) -> Self {
|
||||
self.response_exclusions = opening_headers
|
||||
.iter()
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case("x-codex-exclude"))
|
||||
.map(|(_, value)| value.clone())
|
||||
.collect();
|
||||
self.response_exclusions.clear();
|
||||
for header in ["x-codex-exclude", "x-codex-exclude-stream-fields"] {
|
||||
self.response_exclusions.extend(
|
||||
opening_headers
|
||||
.iter()
|
||||
.filter(|(name, _)| name.eq_ignore_ascii_case(header))
|
||||
.map(|(_, value)| (header, value.clone())),
|
||||
);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -135,9 +139,11 @@ impl CodexWebSocketPoolKey {
|
||||
routing_affinity.as_str(),
|
||||
];
|
||||
short_sha256(
|
||||
parts
|
||||
.into_iter()
|
||||
.chain(self.response_exclusions.iter().map(String::as_str)),
|
||||
parts.into_iter().chain(
|
||||
self.response_exclusions
|
||||
.iter()
|
||||
.flat_map(|(name, value)| [*name, value.as_str()]),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,21 @@ use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn reused_websocket_should_keep_response_metadata_scoped_to_each_exchange() {
|
||||
for warmup_rounds in [0, 2] {
|
||||
assert_metadata_on_pooled_connection(warmup_rounds).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn assert_metadata_on_pooled_connection(warmup_rounds: usize) {
|
||||
const ROUNDS: usize = 40;
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut websocket = accept_codex_test_websocket_with(stream, |_, response| {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert("x-models-etag", "opening".parse().unwrap());
|
||||
for value in ["first", "second"] {
|
||||
response
|
||||
.headers_mut()
|
||||
@@ -54,6 +63,14 @@ async fn reused_websocket_should_keep_response_metadata_scoped_to_each_exchange(
|
||||
)
|
||||
.with_websocket_pool(pool);
|
||||
let request = pooled_websocket_request("conversation-response-metadata");
|
||||
let mut body = codex_request_body("gpt-test", "be brief", vec![]);
|
||||
body.insert("generate".to_owned(), json!(false));
|
||||
body.insert("store".to_owned(), json!(false));
|
||||
let mut warmup = CodexResponsesRequest::from_body(body);
|
||||
warmup.use_websocket = true;
|
||||
warmup
|
||||
.local_conversation_id
|
||||
.clone_from(&request.local_conversation_id);
|
||||
let expected = CodexResponseMetadata {
|
||||
client_headers: vec![
|
||||
(
|
||||
@@ -68,18 +85,40 @@ async fn reused_websocket_should_keep_response_metadata_scoped_to_each_exchange(
|
||||
..CodexResponseMetadata::default()
|
||||
};
|
||||
|
||||
let mut first_generation = expected.clone();
|
||||
first_generation.models_etag = Some("opening".into());
|
||||
first_generation.client_headers.insert(
|
||||
0,
|
||||
(
|
||||
"x-models-etag".into(),
|
||||
bytes::Bytes::from_static(b"opening"),
|
||||
),
|
||||
);
|
||||
|
||||
for round in 0..ROUNDS {
|
||||
let response = timeout(
|
||||
Duration::from_secs(10),
|
||||
backend.create_response(
|
||||
&request,
|
||||
if round < warmup_rounds {
|
||||
&warmup
|
||||
} else {
|
||||
&request
|
||||
},
|
||||
request_context("req_response_metadata", Some("chatgpt-account")),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect("response within timeout")
|
||||
.expect("response should complete on the same socket");
|
||||
assert_eq!(response.response_metadata, expected, "exchange {round}");
|
||||
let expected_metadata = if round == warmup_rounds {
|
||||
&first_generation
|
||||
} else {
|
||||
&expected
|
||||
};
|
||||
assert_eq!(
|
||||
&response.response_metadata, expected_metadata,
|
||||
"exchange {round}"
|
||||
);
|
||||
assert!(response.body.contains(&format!("etag-{round}")));
|
||||
assert_eq!(response.turn_state, Some(format!("turn-{round}")));
|
||||
if round > 0 {
|
||||
|
||||
@@ -2049,12 +2049,22 @@ async fn codex_backend_client_should_discard_pooled_websocket_after_unknown_resp
|
||||
|
||||
#[tokio::test]
|
||||
async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
|
||||
const EXCLUSIONS: &[&[&str]] = &[
|
||||
const RESPONSE: &str = "x-codex-exclude";
|
||||
const STREAM: &str = "x-codex-exclude-stream-fields";
|
||||
const EXCLUSIONS: &[&[(&str, &str)]] = &[
|
||||
&[],
|
||||
&["tools,usage.attribution"],
|
||||
&["tools"],
|
||||
&["tools", "usage.attribution"],
|
||||
&[""],
|
||||
&[(STREAM, "delta.sequence_number")],
|
||||
&[(RESPONSE, "tools"), (STREAM, "delta.sequence_number")],
|
||||
&[
|
||||
(RESPONSE, "tools"),
|
||||
(STREAM, "delta.sequence_number"),
|
||||
(STREAM, "reasoning.added.encrypted_content"),
|
||||
],
|
||||
&[(RESPONSE, "tools")],
|
||||
&[(RESPONSE, "tools"), (RESPONSE, "usage.attribution")],
|
||||
&[(RESPONSE, "tools,usage.attribution")],
|
||||
&[(RESPONSE, "")],
|
||||
&[(STREAM, "")],
|
||||
];
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
@@ -2063,13 +2073,18 @@ async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
|
||||
for (index, &expected) in EXCLUSIONS.iter().enumerate() {
|
||||
let (stream, _) = listener.accept().await.unwrap();
|
||||
let mut socket = accept_codex_test_websocket_with(stream, |request, _| {
|
||||
let actual: Vec<_> = request
|
||||
.headers()
|
||||
.get_all("x-codex-exclude")
|
||||
.iter()
|
||||
.map(|value| value.to_str().unwrap())
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
for header in [RESPONSE, STREAM] {
|
||||
let actual = request
|
||||
.headers()
|
||||
.get_all(header)
|
||||
.iter()
|
||||
.map(|value| value.to_str().unwrap());
|
||||
let values = expected
|
||||
.iter()
|
||||
.filter(|(name, _)| *name == header)
|
||||
.map(|(_, value)| *value);
|
||||
assert!(actual.eq(values), "{header} in opening {index}");
|
||||
}
|
||||
})
|
||||
.await;
|
||||
handlers.spawn(async move {
|
||||
@@ -2098,14 +2113,10 @@ async fn response_exclusions_bind_websocket_reuse_and_exact_continuation() {
|
||||
test_wire_profile(),
|
||||
)
|
||||
.with_websocket_pool(pool.clone());
|
||||
let make_request = |values: &[&str]| {
|
||||
let headers: Vec<_> = values
|
||||
.iter()
|
||||
.map(|&value| ("x-codex-exclude", value))
|
||||
.collect();
|
||||
let make_request = |headers: &[(&str, &str)]| {
|
||||
let mut request = encode_request_with_headers(
|
||||
codex_request_body("gpt-test", "be brief", vec![]),
|
||||
&headers,
|
||||
headers,
|
||||
);
|
||||
request.local_conversation_id = Some("shared-session".into());
|
||||
request.use_websocket = true;
|
||||
|
||||
+5
-3
@@ -252,7 +252,9 @@ OpenAI Provider 的 OAuth 账号使用 Responses 上游,API Key 账号通过 `
|
||||
|
||||
客户端用 `Authorization: Bearer <Client Key>` 或 `x-goog-api-key: <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。
|
||||
|
||||
上游目录声明的模型分组支持使用基础模型名,并通过 `generationConfig.thinkingConfig.thinkingLevel` 指定档位,例如 `gemini-4-hydrogen` 配合 `MEDIUM`。网关只选择该账号目录明确列出的分组成员,账号和分组模型限制按最终型号校验;目录中至少有一个可访问档位时才显示基础模型名。缺少或不支持的档位返回 400,显式完整型号及指向完整型号的模型映射保持原目标。分组能力随上游目录刷新,旧缓存未包含分组时仍只提供完整型号
|
||||
上游目录声明的模型分组支持使用基础模型名,并通过 `generationConfig.thinkingConfig.thinkingLevel` 指定档位,例如 `gemini-4-hydrogen` 配合 `MEDIUM`。网关只选择该账号目录明确列出的分组成员,账号和分组模型限制按最终型号校验;目录中至少有一个可访问档位时才显示基础模型名。普通生成和计数缺少或不支持的档位时返回 400。显式完整型号及指向完整型号的模型映射保持原目标。分组能力随上游目录刷新,旧缓存未包含分组时仍只提供完整型号
|
||||
|
||||
使用分组名调用 `generateContent` 时,若唯一工具为 `googleSearch` 且未指定 `thinkingConfig`,网关使用所选账号目录中 `webSearchModelIds` 的首个搜索型号,保留搜索选项。同一账号及授权分组须同时允许至少一个具体分组成员和该搜索型号
|
||||
|
||||
| 方法 | 路径 | 交付 |
|
||||
| --- | --- | --- |
|
||||
@@ -535,8 +537,8 @@ Responses 的安装身份通过正文 `client_metadata` 及 turn metadata 发送
|
||||
上述过滤描述原生转发;已信任插件的显式 header 改写可以覆盖账号与画像生成的默认头,
|
||||
不按认证或会话字段名称拦截,边界见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
|
||||
|
||||
Responses 透传客户端的 `x-codex-exclude`,由上游按请求省略响应字段。上游 WebSocket 只在握手时读取该头,
|
||||
因此连接池按最终握手中的全部同名头值复用连接。头值变化时,依赖原连接的精确续接需要客户端重放完整历史
|
||||
Responses 透传 `x-codex-exclude` 和 `x-codex-exclude-stream-fields`,分别协商省略的响应字段和流事件字段。
|
||||
上游 WebSocket 在握手时读取两组头值。复用连接要求两组值分别匹配。任一组变化时,依赖原连接的精确续接需要客户端重放完整历史
|
||||
|
||||
Responses 也不透传 `x-stainless-*`、`Origin`、`Referer`、`sec-ch-ua*` 和 `sec-fetch-*`
|
||||
携带的下游 SDK/浏览器环境或页面来源。过滤规则适用于所有下游客户端,与 User-Agent 无关;
|
||||
|
||||
@@ -1082,7 +1082,7 @@ PostgreSQL schema 由迁移目录按编号管理;冻结、升级与校验规
|
||||
### 账号模型目录
|
||||
|
||||
OpenAI 在 PostgreSQL 保存账号最近一次成功的模型目录、凭据版本、观测时间及 ETag。启动时批量恢复,按不同正文解析一次,保留每个账号的独立归属。没有历史目录也能发布路由快照;能力读取与推理不等待上游查询。
|
||||
账号缺少目录或收到新 ETag 时,后台重新查询该账号。正常响应的 ETag 与该账号当前凭据和套餐的目录一致时,在内存中续期。距上次成功拉取或确认满 1 小时后,由后台复查。重启后从持久化的目录观测时间起算。
|
||||
账号缺少目录或收到新 ETag 时,后台重新查询该账号。正常响应的 ETag 与该账号当前凭据和套餐的目录一致时,在内存中续期。WebSocket 握手的 ETag 由该连接首次生成请求确认一次,预热时保留。距上次成功拉取或确认满 1 小时后,由后台复查。重启后从持久化的目录观测时间起算。
|
||||
刷新期间及失败后继续使用上次成功的目录。凭据或套餐变化后重新发现模型。
|
||||
刷新并发与节奏由 [Provider 目录实现](../backend/crates/providers/openai/src/credential/catalog/mod.rs)统一维护
|
||||
|
||||
|
||||
+4
-19
@@ -1,22 +1,7 @@
|
||||
# v3.57.0
|
||||
|
||||
## 新增功能
|
||||
|
||||
- OpenAI 数据驻留与账号路由可在平台设置中调整,保存后对新请求生效,无需重启
|
||||
- OpenAI 连接池支持在线调整并发建连上限、建连等待时间、连接寿命、空闲回收时间和流式空闲超时
|
||||
|
||||
## 优化改进
|
||||
|
||||
- 设置表单补充参数说明,并统一显示时间与数量单位
|
||||
# v3.57.1
|
||||
|
||||
## 问题修复
|
||||
|
||||
- Antigravity 生成与 Token 计数保留客户端的全局规则、项目规则和工具说明,平台提示词放在客户端系统指令之前
|
||||
|
||||
## 升级须知
|
||||
|
||||
- YAML 中的 `openai.residency`、`openai.account_routing_override` 和 `openai.ws_pool` 不再生效,升级前记录自定义值,升级后在 OpenAI 平台设置中重新保存并删除旧字段
|
||||
- 数据驻留初始化为 `us`,账号路由默认为空;需要移除数据驻留请求头时,在管理端清空该项并保存
|
||||
- OpenAI 连接池始终启用,不再支持 `ws_pool.enabled: false`;调整连接寿命与空闲回收时间只影响新建连接,已有连接沿用创建时的期限
|
||||
- 管理 API 更新设置时须提交完整的 `openaiRequestSettings` 和 `openaiWebsocketPool` 对象;调用运行设置服务的插件须更新 SDK 并重新构建
|
||||
- 未发布的 `0048`~`0050` 迁移已合并为 `0048`,从 v3.56.1 及同大版本更早正式版可正常升级;已执行原迁移的源码部署不能直接复用该数据库升级
|
||||
- Antigravity CLI 使用分组模型调用 `search_web` 时,无需指定推理档位即可搜索,原有搜索选项随请求透传
|
||||
- OpenAI Responses 通过 WebSocket 复用连接时,按当前请求的设置省略响应字段和流事件字段,避免沿用其他请求的设置
|
||||
- OpenAI 模型目录保留预热连接握手返回的 ETag,复用同一连接时只确认一次目录版本
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.57.0
|
||||
version: 3.57.1
|
||||
published:
|
||||
'3':
|
||||
stable: 3.56.1
|
||||
rc: 3.56.1
|
||||
beta: 3.56.1
|
||||
alpha: 3.56.1
|
||||
stable: 3.57.0
|
||||
rc: 3.57.0
|
||||
beta: 3.57.0
|
||||
alpha: 3.57.0
|
||||
|
||||
Reference in New Issue
Block a user