mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-29 08:00:45 +00:00
fix(antigravity): route standalone web searches to the OAuth search model (#791)
Co-authored-by: Zyy <zyycn@users.noreply.github.com>
This commit is contained in:
@@ -162,6 +162,7 @@ pub struct ModelCapabilities {
|
||||
translated_generation_protocols: BTreeSet<&'static str>,
|
||||
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
account_metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||
native_web_search_helper: Option<&'static str>,
|
||||
dedicated_web_search: Option<Arc<BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>>>,
|
||||
}
|
||||
|
||||
@@ -440,6 +441,7 @@ impl ModelCapabilities {
|
||||
reasoning_variants: BTreeMap::new(),
|
||||
account_metadata: BTreeMap::new(),
|
||||
dedicated_web_search: None,
|
||||
native_web_search_helper: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -483,6 +485,17 @@ impl ModelCapabilities {
|
||||
self
|
||||
}
|
||||
|
||||
/// 原生客户端用固定辅助型号发起独立搜索,目标来自 Provider 的账号搜索目录
|
||||
#[must_use]
|
||||
pub fn with_native_web_search_helper(
|
||||
mut self,
|
||||
model: &'static str,
|
||||
targets: BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>,
|
||||
) -> Self {
|
||||
self.native_web_search_helper = Some(model);
|
||||
self.with_dedicated_web_search(targets)
|
||||
}
|
||||
|
||||
/// 将请求形态 feature 的最终合法性判断交给上游 wire API
|
||||
#[must_use]
|
||||
pub const fn with_upstream_feature_validation(mut self) -> Self {
|
||||
|
||||
@@ -1614,23 +1614,37 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
|
||||
let requested_model = public_model.as_str();
|
||||
let explicitly_mapped = self
|
||||
.settings
|
||||
.values
|
||||
.model_mappings
|
||||
.contains_key(requested_model)
|
||||
|| self.model_alias(requested_model).is_some();
|
||||
let upstream_model = if let Some(direct) = direct_model {
|
||||
direct.clone()
|
||||
} else {
|
||||
let mapped_model = self.mapped_model(requested_model);
|
||||
if self
|
||||
.settings
|
||||
.values
|
||||
.model_mappings
|
||||
.contains_key(requested_model)
|
||||
|| self.model_alias(requested_model).is_some()
|
||||
{
|
||||
if explicitly_mapped {
|
||||
UpstreamModelId::new(mapped_model)
|
||||
} else {
|
||||
UpstreamModelId::from_client_wire(mapped_model)
|
||||
}
|
||||
.map_err(|_| RoutingError::InvalidIdentifier)?
|
||||
};
|
||||
if !explicitly_mapped
|
||||
&& enforce_routing_policy
|
||||
&& direct_model.is_none()
|
||||
&& operation.is_native_web_search()
|
||||
&& let Some(search) = self.native_web_search_candidates(
|
||||
&upstream_model,
|
||||
operation.protocol(),
|
||||
&account_scope,
|
||||
context,
|
||||
requirements.requested_output_tokens(),
|
||||
)
|
||||
{
|
||||
return Ok(self.model_plan(operation, account_scope, search?));
|
||||
}
|
||||
let grouped = self.providers.iter().any(|provider| {
|
||||
self.model_group(provider, upstream_model.as_str())
|
||||
.is_some()
|
||||
@@ -1871,17 +1885,12 @@ impl RuntimeSnapshot {
|
||||
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)
|
||||
{
|
||||
if !self.search_target_fits(
|
||||
provider,
|
||||
account,
|
||||
target,
|
||||
requirements.requested_output_tokens(),
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
targets
|
||||
@@ -1949,7 +1958,103 @@ impl RuntimeSnapshot {
|
||||
});
|
||||
}
|
||||
|
||||
Ok(RoutingPlan {
|
||||
Ok(self.model_plan(operation, account_scope, candidates))
|
||||
}
|
||||
|
||||
fn search_target_fits(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
account: &ProviderAccountId,
|
||||
target: &UpstreamModelId,
|
||||
requested_tokens: Option<u64>,
|
||||
) -> bool {
|
||||
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);
|
||||
requested_tokens
|
||||
.zip(limit)
|
||||
.is_none_or(|(requested, limit)| requested <= limit)
|
||||
}
|
||||
|
||||
/// 辅助型号只标识搜索操作,账号与分组的模型权限按实际搜索目标判断
|
||||
fn native_web_search_candidates(
|
||||
&self,
|
||||
requested_model: &UpstreamModelId,
|
||||
protocol: &str,
|
||||
scope: &FrozenAccountScope,
|
||||
context: &RoutingContext,
|
||||
requested_tokens: Option<u64>,
|
||||
) -> Option<Result<Vec<ProviderCandidate>, RoutingError>> {
|
||||
let mut candidates = None;
|
||||
let mut group_denied = false;
|
||||
for provider in self.available_provider_kinds(scope, context) {
|
||||
let Some(models) = self.provider_models.get(provider) else {
|
||||
continue;
|
||||
};
|
||||
// 当前范围已有原生型号时仍走普通路由,其他协议的同名模型不能接管 GenAI
|
||||
if models
|
||||
.get(requested_model)
|
||||
.is_some_and(|model| model.native_generation_protocols.contains(protocol))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let Some(targets) = models.values().find_map(|model| {
|
||||
model
|
||||
.dedicated_web_search
|
||||
.as_deref()
|
||||
.filter(|_| model.native_web_search_helper == Some(requested_model.as_str()))
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
let candidates = candidates.get_or_insert_with(Vec::new);
|
||||
let mut accounts_by_target = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for (account, target) in targets {
|
||||
if scope.account_provider(account) != Some(provider) || !scope.allows(account) {
|
||||
continue;
|
||||
}
|
||||
if !scope.allows_model(account, target.as_str()) {
|
||||
group_denied |= scope.groups_deny_model(Some(target.as_str()));
|
||||
continue;
|
||||
}
|
||||
if self.search_target_fits(provider, account, target, requested_tokens) {
|
||||
accounts_by_target
|
||||
.entry(target)
|
||||
.or_default()
|
||||
.insert(account.clone());
|
||||
}
|
||||
}
|
||||
for (target, accounts) in accounts_by_target {
|
||||
candidates.push(ProviderCandidate {
|
||||
dedicated_web_search: true,
|
||||
requires_direct_authentication: false,
|
||||
provider: provider.clone(),
|
||||
upstream_model: Some(target.clone()),
|
||||
emulated_features: BTreeSet::new(),
|
||||
account_scope: Arc::new(scope.restricted_to(&Default::default(), &accounts)),
|
||||
});
|
||||
}
|
||||
}
|
||||
candidates.map(|candidates| {
|
||||
if !candidates.is_empty() {
|
||||
Ok(candidates)
|
||||
} else if group_denied {
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
} else {
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn model_plan(
|
||||
&self,
|
||||
operation: &Operation,
|
||||
account_scope: Arc<FrozenAccountScope>,
|
||||
candidates: Vec<ProviderCandidate>,
|
||||
) -> RoutingPlan {
|
||||
RoutingPlan {
|
||||
request_body_limit: self.responses_max_decompressed_body_bytes(),
|
||||
max_retry_after: std::time::Duration::from_secs(u64::from(
|
||||
self.settings.values.max_retry_after_seconds,
|
||||
@@ -1971,7 +2076,7 @@ impl RuntimeSnapshot {
|
||||
.expect("constant request attempt limit is non-zero"),
|
||||
account_scope,
|
||||
candidates: Arc::from(candidates),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// 为 Provider 自有端点冻结请求计划
|
||||
|
||||
@@ -26,6 +26,144 @@ use gateway_core::routing::{
|
||||
};
|
||||
use gateway_core::settings::SettingsValues;
|
||||
|
||||
#[test]
|
||||
fn native_search_helper_routes_only_to_each_authorized_accounts_own_target() {
|
||||
use gateway_core::{
|
||||
account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId},
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{
|
||||
AccountGroupId, ClientRoutingScope, FrozenAccountScope, ProviderModel, RoutingContext,
|
||||
RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory, RuntimeSnapshot,
|
||||
},
|
||||
validation::RoutingError,
|
||||
};
|
||||
let provider = ProviderKind::new("alpha").unwrap();
|
||||
let helper = PublicModelId::new("search-helper").unwrap();
|
||||
let group = AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let allow = |ids: &[&str]| {
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Allowlist,
|
||||
ids.iter().map(|id| (*id).to_owned()).collect(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let mut accounts = BTreeMap::new();
|
||||
let mut targets = BTreeMap::new();
|
||||
for (id, declared, allowed) in [
|
||||
("acct_first", "search-a", "search-a"),
|
||||
("acct_second", "search-b", "search-b"),
|
||||
("acct_filtered", "search-a", "search-b"),
|
||||
("acct_unlisted", "search-c", "search-c"),
|
||||
] {
|
||||
let id = ProviderAccountId::new(id).unwrap();
|
||||
accounts.insert(
|
||||
id.clone(),
|
||||
RuntimeAccount::new(provider.clone(), [group.clone()].into())
|
||||
.with_model_access(allow(&[allowed])),
|
||||
);
|
||||
targets.insert(id, UpstreamModelId::new(declared).unwrap());
|
||||
}
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(
|
||||
RuntimeAccountDirectory::new(accounts).with_group_model_access(
|
||||
[(group.clone(), allow(&["search-a", "search-b"]))].into(),
|
||||
),
|
||||
),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![RoutingGroupSnapshot::new(group.clone(), "Group".into())],
|
||||
[group].into(),
|
||||
[provider.clone()].into(),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let operation = 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(),
|
||||
);
|
||||
let route = |same_name_protocol, targets, scope| {
|
||||
let caps = || {
|
||||
ModelCapabilities::new([OperationKind::Generate].into(), None)
|
||||
.with_upstream_feature_validation()
|
||||
};
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
revision(1),
|
||||
SettingsValues::new(1, "smart", BTreeMap::new(), None, None),
|
||||
vec![provider.clone()],
|
||||
vec![
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("main").unwrap(),
|
||||
caps()
|
||||
.with_generation_protocol("genai")
|
||||
.with_native_web_search_helper("search-helper", targets),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("search-helper").unwrap(),
|
||||
caps().with_generation_protocol(same_name_protocol),
|
||||
),
|
||||
],
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
snapshot.plan(&helper, &operation, scope, &RoutingContext::default())
|
||||
};
|
||||
let plan = route("openai", targets.clone(), scope.clone()).unwrap();
|
||||
let assignments: Vec<_> = plan
|
||||
.candidates()
|
||||
.iter()
|
||||
.map(|candidate| {
|
||||
assert!(candidate.uses_dedicated_web_search());
|
||||
(
|
||||
candidate.upstream_model().unwrap().as_str(),
|
||||
candidate
|
||||
.account_scope()
|
||||
.allowed_account_ids()
|
||||
.map(ProviderAccountId::as_str)
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
assignments,
|
||||
[
|
||||
("search-a", vec!["acct_first"]),
|
||||
("search-b", vec!["acct_second"])
|
||||
]
|
||||
);
|
||||
let denied = Arc::new(scope.restricted_to(
|
||||
&Default::default(),
|
||||
&[ProviderAccountId::new("acct_unlisted").unwrap()].into(),
|
||||
));
|
||||
assert!(matches!(
|
||||
route("openai", targets.clone(), denied),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
assert!(matches!(
|
||||
route("openai", BTreeMap::new(), scope.clone()),
|
||||
Err(RoutingError::WebSearchUnavailable)
|
||||
));
|
||||
assert!(matches!(
|
||||
route("genai", targets, scope),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
use gateway_core::{
|
||||
|
||||
@@ -197,7 +197,7 @@ impl CatalogService {
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_dedicated_web_search(search_models)
|
||||
.with_native_web_search_helper("gemini-3.1-flash-lite-preview", search_models)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL])
|
||||
.with_upstream_feature_validation();
|
||||
|
||||
@@ -960,7 +960,7 @@ async fn search_snapshot(fixture: &Fixture) -> gateway_core::routing::RuntimeSna
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_search_resolves_groups_and_preserves_explicit_models_and_grounding() {
|
||||
async fn native_search_routes_the_client_helper_and_groups_and_preserves_grounding() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
@@ -995,22 +995,35 @@ async fn native_search_resolves_groups_and_preserves_explicit_models_and_groundi
|
||||
};
|
||||
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 cli_body = json!({
|
||||
"contents": body["contents"],
|
||||
"systemInstruction":{"parts":[{"text":"Search the web"}]},
|
||||
"generationConfig":{}, "tools":[{"googleSearch":{}}]
|
||||
});
|
||||
for (requested, target, kind, body) in [
|
||||
(
|
||||
"gemini-3.1-flash-lite-preview",
|
||||
"search-only",
|
||||
"web_search",
|
||||
&cli_body,
|
||||
),
|
||||
("family", "search-only", "web_search", &body),
|
||||
("family-low", "family-low", "agent", &body),
|
||||
] {
|
||||
let op = operation(&body, false);
|
||||
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"))
|
||||
let _upstream = Mock::given(path("/v1internal:generateContent"))
|
||||
.and(body_partial_json(
|
||||
json!({"model":target,"requestType":kind,"request":body}),
|
||||
json!({"model":target,"requestType":kind,"request":{
|
||||
"contents":body["contents"],"tools":body["tools"],"generationConfig":body["generationConfig"]
|
||||
}}),
|
||||
))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({"response":grounded})))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.mount_as_scoped(&server)
|
||||
.await;
|
||||
let events = fixture
|
||||
.provider
|
||||
@@ -1043,14 +1056,43 @@ async fn native_search_resolves_groups_and_preserves_explicit_models_and_groundi
|
||||
explicit["generationConfig"]["thinkingConfig"] = json!({"thinkingLevel":"UNSUPPORTED"});
|
||||
for op in [
|
||||
operation(&body, true),
|
||||
operation(&json!({"contents":body["contents"]}), false),
|
||||
operation(&mixed, false),
|
||||
operation(&explicit, false),
|
||||
] {
|
||||
assert!(matches!(
|
||||
plan("gemini-3.1-flash-lite-preview", &op),
|
||||
Err(RoutingError::ModelNotFound { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
plan("family", &op),
|
||||
Err(RoutingError::InvalidReasoningVariant)
|
||||
));
|
||||
}
|
||||
let helper = PublicModelId::new("gemini-3.1-flash-lite-preview").unwrap();
|
||||
let op = operation(&body, false);
|
||||
for target in ["family-low", "missing-mapped-model"] {
|
||||
let settings = snapshot
|
||||
.settings()
|
||||
.clone()
|
||||
.with_model_mappings([(helper.as_str().to_owned(), target.to_owned())].into());
|
||||
let result = snapshot.with_settings(&settings).unwrap().plan(
|
||||
&helper,
|
||||
&op,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
);
|
||||
if target == "family-low" {
|
||||
let route = result.unwrap();
|
||||
assert_eq!(
|
||||
route.candidates()[0].upstream_model().unwrap().as_str(),
|
||||
target
|
||||
);
|
||||
assert!(!route.candidates()[0].uses_dedicated_web_search());
|
||||
} else {
|
||||
assert!(matches!(result, Err(RoutingError::ModelNotFound { .. })));
|
||||
}
|
||||
}
|
||||
server.verify().await;
|
||||
}
|
||||
|
||||
|
||||
@@ -256,6 +256,8 @@ OpenAI Provider 的 OAuth 账号使用 Responses 上游,API Key 账号通过 `
|
||||
|
||||
使用分组名调用 `generateContent` 时,若唯一工具为 `googleSearch` 且未指定 `thinkingConfig`,网关使用所选账号目录中 `webSearchModelIds` 的首个搜索型号,保留搜索选项。同一账号及授权分组须同时允许至少一个具体分组成员和该搜索型号
|
||||
|
||||
AGY 在 API Key 模式下使用 `gemini-3.1-flash-lite-preview` 发起同样的独立搜索。网关优先使用显式映射、别名和已有的 GenAI 原生型号。缺少对应型号时,网关使用各 OAuth 账号目录中 `webSearchModelIds` 的第一项,账号和授权分组都必须允许该型号
|
||||
|
||||
| 方法 | 路径 | 交付 |
|
||||
| --- | --- | --- |
|
||||
| POST | `/v1beta/models/{model}:generateContent` | 原生 JSON |
|
||||
|
||||
Reference in New Issue
Block a user