mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 08:00:38 +00:00
fix(antigravity): route standalone web searches on model groups
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -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())
|
||||
|
||||
+3
-1
@@ -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` 的首个搜索型号,保留搜索选项。同一账号及授权分组须同时允许至少一个具体分组成员和该搜索型号
|
||||
|
||||
| 方法 | 路径 | 交付 |
|
||||
| --- | --- | --- |
|
||||
|
||||
Reference in New Issue
Block a user