mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-25 16:01:26 +00:00
fix(antigravity): resolve native model groups by thinking level
Resolve declared model groups to concrete variants before account and model-policy checks. Preserve explicit model IDs and native request bodies, and expose only accessible groups in the catalog. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -24,6 +24,10 @@ pub(super) fn authentication_gateway_error(error: ClientAuthenticationError) ->
|
||||
|
||||
pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> GatewayError {
|
||||
match error {
|
||||
crate::validation::RoutingError::InvalidReasoningVariant => GatewayError::new(
|
||||
GatewayErrorKind::InvalidRequest,
|
||||
"A supported reasoning effort is required for this model group.",
|
||||
),
|
||||
crate::validation::RoutingError::GroupModelDenied => GatewayError::new(
|
||||
GatewayErrorKind::PolicyDenied,
|
||||
crate::validation::GROUP_MODEL_DENIED_MESSAGE,
|
||||
|
||||
@@ -920,6 +920,40 @@ pub enum Operation {
|
||||
}
|
||||
|
||||
impl Operation {
|
||||
pub(crate) fn requires_native_protocol(&self) -> bool {
|
||||
match self {
|
||||
Self::Generate(request) => request.requires_native_protocol(),
|
||||
Self::CountTokens(request) => request.requires_native_protocol(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 仅提取本次正文明确声明的推理档位,路由不继承 Provider 会话默认值
|
||||
pub(crate) fn requested_reasoning_effort(&self) -> Option<String> {
|
||||
let observation = match self {
|
||||
Self::Generate(request) => {
|
||||
let payload = request.protocol_payload();
|
||||
gateway_protocol::request::request_observation(
|
||||
payload.protocol(),
|
||||
payload.body(),
|
||||
payload.context(),
|
||||
None,
|
||||
)
|
||||
}
|
||||
Self::CountTokens(request) => {
|
||||
let payload = request.payload();
|
||||
let body = serde_json::from_slice::<Map<String, Value>>(payload.body()).ok()?;
|
||||
gateway_protocol::request::token_count_observation(
|
||||
payload.protocol(),
|
||||
&body,
|
||||
payload.context(),
|
||||
)
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
observation.reasoning_effort
|
||||
}
|
||||
|
||||
pub(crate) fn with_inherited_capability_requirements(
|
||||
self,
|
||||
inherited: CapabilityRequirements,
|
||||
|
||||
@@ -12,6 +12,13 @@ use super::{
|
||||
ModelCapabilities, ModelPresentation, PublicModelId, PublicModelProfile, UpstreamModelId,
|
||||
};
|
||||
|
||||
/// Provider 声明的推理档位目标及确认该分组成员关系的账号
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ReasoningModelVariant {
|
||||
pub model: UpstreamModelId,
|
||||
pub accounts: BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
/// 扩展集合持有的直接模型别名;执行与元数据仍归属内置 Provider
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContributedModelAlias {
|
||||
|
||||
@@ -13,7 +13,7 @@ pub use crate::identity::ProviderKind;
|
||||
pub use catalog::{
|
||||
ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, ProviderCatalogPort,
|
||||
ProviderCatalogUnavailable, ProviderModelCapabilities, ProviderModelContent,
|
||||
ProviderModelDescriptor, PublicModelDescriptor,
|
||||
ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant,
|
||||
};
|
||||
pub use snapshot::RuntimeSnapshot;
|
||||
|
||||
@@ -118,6 +118,12 @@ impl fmt::Display for UpstreamModelId {
|
||||
}
|
||||
}
|
||||
|
||||
impl std::borrow::Borrow<str> for UpstreamModelId {
|
||||
fn borrow(&self) -> &str {
|
||||
self.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
/// `runtime_settings.config_revision`
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct ConfigRevision(NonZeroU64);
|
||||
@@ -153,6 +159,7 @@ pub struct ModelCapabilities {
|
||||
upstream_validates_features: bool,
|
||||
generation_protocol: Option<&'static str>,
|
||||
translated_generation_protocols: BTreeSet<&'static str>,
|
||||
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
}
|
||||
|
||||
/// Provider 为客户端模型目录提供的展示与交互能力
|
||||
@@ -427,6 +434,7 @@ impl ModelCapabilities {
|
||||
upstream_validates_features: false,
|
||||
generation_protocol: None,
|
||||
translated_generation_protocols: BTreeSet::new(),
|
||||
reasoning_variants: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -436,6 +444,21 @@ impl ModelCapabilities {
|
||||
self
|
||||
}
|
||||
|
||||
/// 分组名只按请求明确声明的档位解析,不推测默认型号
|
||||
#[must_use]
|
||||
pub fn with_reasoning_variants(
|
||||
mut self,
|
||||
variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
) -> Self {
|
||||
self.reasoning_variants = variants;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn reasoning_variants(&self) -> &BTreeMap<String, ReasoningModelVariant> {
|
||||
&self.reasoning_variants
|
||||
}
|
||||
|
||||
/// 将请求形态 feature 的最终合法性判断交给上游 wire API
|
||||
#[must_use]
|
||||
pub const fn with_upstream_feature_validation(mut self) -> Self {
|
||||
@@ -465,6 +488,11 @@ impl ModelCapabilities {
|
||||
operation: &crate::operation::Operation,
|
||||
requirements: &CapabilityRequirements,
|
||||
) -> Option<BTreeSet<Feature>> {
|
||||
if operation.requires_native_protocol()
|
||||
&& self.generation_protocol != Some(operation.protocol())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if matches!(operation, crate::operation::Operation::Generate(_))
|
||||
&& self.generation_protocol.is_some_and(|protocol| {
|
||||
protocol != operation.protocol()
|
||||
|
||||
@@ -1078,6 +1078,35 @@ impl RuntimeSnapshot {
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.is_ok()
|
||||
|| scope.provider_kinds().iter().any(|provider| {
|
||||
self.contains_public_model_for_provider(model, provider)
|
||||
&& self
|
||||
.model_group(provider, &self.mapped_model(model.as_str()))
|
||||
.is_some_and(|group| {
|
||||
group
|
||||
.match_operation(
|
||||
operation,
|
||||
&operation.capability_requirements(),
|
||||
)
|
||||
.is_some()
|
||||
&& group.reasoning_variants.values().any(|variant| {
|
||||
self.variant_allowed(provider, variant, scope)
|
||||
&& self
|
||||
.provider_models
|
||||
.get(provider)
|
||||
.and_then(|models| models.get(&variant.model))
|
||||
.is_some_and(|target| {
|
||||
target
|
||||
.match_operation(
|
||||
operation,
|
||||
&operation
|
||||
.capability_requirements(),
|
||||
)
|
||||
.is_some()
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1172,6 +1201,13 @@ impl RuntimeSnapshot {
|
||||
return false;
|
||||
};
|
||||
let upstream = self.mapped_model(public_model.as_str());
|
||||
if let Some(group) = self.model_group(provider, &upstream) {
|
||||
return self.contains_public_model_for_provider(public_model, provider)
|
||||
&& group.reasoning_variants.values().any(|variant| {
|
||||
variant.accounts.contains(account)
|
||||
&& scope.allows_model(account, variant.model.as_str())
|
||||
});
|
||||
}
|
||||
if !scope.allows_model(account, &upstream)
|
||||
|| !self.contains_public_model_for_provider(public_model, provider)
|
||||
{
|
||||
@@ -1237,6 +1273,25 @@ impl RuntimeSnapshot {
|
||||
})
|
||||
}
|
||||
|
||||
fn model_group(&self, provider: &ProviderKind, model: &str) -> Option<&ModelCapabilities> {
|
||||
self.provider_models
|
||||
.get(provider)?
|
||||
.get(model)
|
||||
.filter(|capabilities| !capabilities.reasoning_variants.is_empty())
|
||||
}
|
||||
|
||||
fn variant_allowed(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
variant: &super::ReasoningModelVariant,
|
||||
scope: &FrozenAccountScope,
|
||||
) -> bool {
|
||||
variant.accounts.iter().any(|account| {
|
||||
scope.account_provider(account) == Some(provider)
|
||||
&& scope.allows_model(account, variant.model.as_str())
|
||||
})
|
||||
}
|
||||
|
||||
fn native_catalog_model_allowed_for_scope(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
@@ -1244,6 +1299,12 @@ impl RuntimeSnapshot {
|
||||
scope: &FrozenAccountScope,
|
||||
) -> bool {
|
||||
let upstream_model = self.mapped_model(public_model.as_str());
|
||||
if let Some(group) = self.model_group(provider, &upstream_model) {
|
||||
return group
|
||||
.reasoning_variants
|
||||
.values()
|
||||
.any(|variant| self.variant_allowed(provider, variant, scope));
|
||||
}
|
||||
match self
|
||||
.model_catalog_accounts
|
||||
.get(provider)
|
||||
@@ -1461,7 +1522,13 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
.map_err(|_| RoutingError::InvalidIdentifier)?
|
||||
};
|
||||
if enforce_routing_policy && account_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
let grouped = self.providers.iter().any(|provider| {
|
||||
self.model_group(provider, upstream_model.as_str())
|
||||
.is_some()
|
||||
});
|
||||
if !grouped
|
||||
&& enforce_routing_policy
|
||||
&& account_scope.groups_deny_model(Some(upstream_model.as_str()))
|
||||
{
|
||||
return Err(RoutingError::GroupModelDenied);
|
||||
}
|
||||
@@ -1476,6 +1543,8 @@ impl RuntimeSnapshot {
|
||||
|| account_scope.provider_kinds().clone(),
|
||||
|provider| BTreeSet::from([provider.clone()]),
|
||||
);
|
||||
let mut invalid_variant = false;
|
||||
let mut group_model_denied = false;
|
||||
for provider in &providers {
|
||||
if !self.providers.contains(provider) {
|
||||
continue;
|
||||
@@ -1495,23 +1564,50 @@ 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 effort = operation.requested_reasoning_effort();
|
||||
let Some(variant) = effort
|
||||
.as_ref()
|
||||
.and_then(|effort| group.reasoning_variants.get(effort))
|
||||
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
|
||||
&& !account_scope.allows_provider_model(provider, upstream_model.as_str())
|
||||
&& !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));
|
||||
.and_then(|models| models.get(upstream_model));
|
||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||
let native_protocol = match operation {
|
||||
Operation::Generate(request) => request.requires_native_protocol(),
|
||||
Operation::CountTokens(request) => request.requires_native_protocol(),
|
||||
_ => false,
|
||||
};
|
||||
if native_protocol
|
||||
if operation.requires_native_protocol()
|
||||
&& capabilities.and_then(|model| model.generation_protocol)
|
||||
!= Some(operation.protocol())
|
||||
{
|
||||
@@ -1530,7 +1626,6 @@ impl RuntimeSnapshot {
|
||||
&& &model.id == public_model
|
||||
})
|
||||
.collect();
|
||||
let mut candidate_scope = Arc::clone(&account_scope);
|
||||
let emulated_features = if contributions.is_empty() {
|
||||
match capabilities {
|
||||
Some(capabilities) => {
|
||||
@@ -1562,14 +1657,14 @@ impl RuntimeSnapshot {
|
||||
})
|
||||
.flat_map(|model| model.accounts.iter())
|
||||
.filter(|account| {
|
||||
account_scope.account_provider(account) == Some(provider)
|
||||
&& account_scope.allows_model(account, upstream_model.as_str())
|
||||
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 = account_scope.as_ref().clone();
|
||||
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());
|
||||
@@ -1582,7 +1677,7 @@ impl RuntimeSnapshot {
|
||||
continue;
|
||||
}
|
||||
candidate_scope = Arc::new(
|
||||
account_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
candidate_scope.restricted_to(&Default::default(), &capable_accounts),
|
||||
);
|
||||
}
|
||||
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||
@@ -1607,6 +1702,12 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
|
||||
if candidates.is_empty() {
|
||||
if group_model_denied {
|
||||
return Err(RoutingError::GroupModelDenied);
|
||||
}
|
||||
if invalid_variant {
|
||||
return Err(RoutingError::InvalidReasoningVariant);
|
||||
}
|
||||
// 模型存在性必须包含被请求路由限制排除的 Provider;目录未知时不能断言模型不存在
|
||||
let mut scoped_providers = providers.intersection(&self.providers).peekable();
|
||||
if scoped_providers.peek().is_some()
|
||||
|
||||
@@ -81,6 +81,9 @@ pub enum RoutingError {
|
||||
/// 已启用的绑定分组均明确禁止请求模型
|
||||
#[error("{GROUP_MODEL_DENIED_MESSAGE}")]
|
||||
GroupModelDenied,
|
||||
/// 已知模型分组没有与本次请求匹配的推理档位
|
||||
#[error("model group requires a supported reasoning effort")]
|
||||
InvalidReasoningVariant,
|
||||
/// 快照中存在重复实体
|
||||
#[error("duplicate {entity} `{id}`")]
|
||||
DuplicateEntity {
|
||||
|
||||
@@ -26,6 +26,270 @@ use gateway_core::routing::{
|
||||
};
|
||||
use gateway_core::settings::SettingsValues;
|
||||
|
||||
#[test]
|
||||
fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
use gateway_core::{
|
||||
account::{AccountModelAccess, AccountModelAccessMode, ProviderAccountId},
|
||||
operation::{
|
||||
GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest,
|
||||
},
|
||||
routing::{
|
||||
ClientRoutingScope, FrozenAccountScope, ProviderModel, ReasoningModelVariant,
|
||||
RoutingContext, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory,
|
||||
RuntimeSnapshot,
|
||||
},
|
||||
validation::RoutingError,
|
||||
};
|
||||
use std::collections::BTreeSet;
|
||||
let provider = ProviderKind::new("alpha").unwrap();
|
||||
let declared = ProviderAccountId::new("acct_declared").unwrap();
|
||||
let other = ProviderAccountId::new("acct_other").unwrap();
|
||||
let group = gateway_core::routing::AccountGroupId::new(format!("grp_{:032x}", 1)).unwrap();
|
||||
let scope = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(
|
||||
RuntimeAccountDirectory::new(BTreeMap::from_iter(
|
||||
[declared.clone(), other.clone()].into_iter().map(|id| {
|
||||
(
|
||||
id,
|
||||
RuntimeAccount::new(provider.clone(), BTreeSet::from([group.clone()])),
|
||||
)
|
||||
}),
|
||||
))
|
||||
.with_group_model_access(BTreeMap::from([(
|
||||
group.clone(),
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Allowlist,
|
||||
vec!["family-medium".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
)])),
|
||||
),
|
||||
ClientRoutingScope::restricted(
|
||||
vec![RoutingGroupSnapshot::new(group.clone(), "Group".into())],
|
||||
BTreeSet::from([group]),
|
||||
BTreeSet::from([provider.clone()]),
|
||||
)
|
||||
.unwrap(),
|
||||
));
|
||||
let caps = || {
|
||||
ModelCapabilities::new(
|
||||
BTreeSet::from([OperationKind::Generate, OperationKind::CountTokens]),
|
||||
None,
|
||||
)
|
||||
.with_generation_protocol("genai")
|
||||
.with_upstream_feature_validation()
|
||||
};
|
||||
let variants = BTreeMap::from_iter(["medium", "high"].map(|level| {
|
||||
(
|
||||
level.into(),
|
||||
ReasoningModelVariant {
|
||||
model: UpstreamModelId::new(format!("family-{level}")).unwrap(),
|
||||
accounts: BTreeSet::from([declared.clone()]),
|
||||
},
|
||||
)
|
||||
}));
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
revision(1),
|
||||
SettingsValues::new(
|
||||
2,
|
||||
"smart",
|
||||
BTreeMap::from([("alias".into(), "family".into())]),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
vec![provider.clone()],
|
||||
vec![
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family").unwrap(),
|
||||
caps().with_reasoning_variants(variants),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family-medium").unwrap(),
|
||||
caps(),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family-high").unwrap(),
|
||||
caps(),
|
||||
),
|
||||
],
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
let operation = |level: &str, count: bool| {
|
||||
let body = serde_json::json!({"contents":[], "generationConfig":{"thinkingConfig":{"thinkingLevel":level}}});
|
||||
if count {
|
||||
let body = serde_json::json!({"generateContentRequest": body});
|
||||
Operation::CountTokens(
|
||||
TokenCountRequest::from_raw_json(
|
||||
RawJsonPayload::new(
|
||||
"genai",
|
||||
bytes::Bytes::from(serde_json::to_vec(&body).unwrap()),
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
)
|
||||
} else {
|
||||
Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
)
|
||||
}
|
||||
};
|
||||
let base = PublicModelId::new("family").unwrap();
|
||||
for count in [false, true] {
|
||||
for name in ["family", "alias"] {
|
||||
for level in ["MEDIUM", "medium"] {
|
||||
let request = operation(level, count);
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new(name).unwrap(),
|
||||
&request,
|
||||
scope.clone(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let candidate = &plan.candidates()[0];
|
||||
assert_eq!(
|
||||
candidate.upstream_model().unwrap().as_str(),
|
||||
"family-medium"
|
||||
);
|
||||
assert!(candidate.account_scope().allows(&declared));
|
||||
assert!(!candidate.account_scope().allows(&other));
|
||||
}
|
||||
}
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&base,
|
||||
&operation("HIGH", count),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::GroupModelDenied)
|
||||
));
|
||||
for level in ["", "unsupported"] {
|
||||
assert!(matches!(
|
||||
snapshot.plan(
|
||||
&base,
|
||||
&operation(level, count),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
),
|
||||
Err(RoutingError::InvalidReasoningVariant)
|
||||
));
|
||||
}
|
||||
let listed = snapshot.public_models_for_operation(&scope, &operation("", count));
|
||||
assert!(listed.contains(&base));
|
||||
let other_only =
|
||||
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
|
||||
assert!(
|
||||
!snapshot
|
||||
.public_models_for_operation(&other_only, &operation("", count))
|
||||
.contains(&base)
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&operation("MEDIUM", count),
|
||||
other_only,
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
// 完整型号不受正文中的其他档位重定向
|
||||
let direct = PublicModelId::new("family-medium").unwrap();
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.plan(
|
||||
&direct,
|
||||
&operation("HIGH", false),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.unwrap()
|
||||
.candidates()[0]
|
||||
.upstream_model()
|
||||
.unwrap()
|
||||
.as_str(),
|
||||
"family-medium"
|
||||
);
|
||||
let incompatible = Operation::Generate(
|
||||
GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("other-wire", Default::default()).unwrap(),
|
||||
)
|
||||
.requiring_native_protocol(),
|
||||
);
|
||||
assert!(
|
||||
!snapshot
|
||||
.public_models_for_operation(&scope, &incompatible)
|
||||
.contains(&base)
|
||||
);
|
||||
let blocked = Arc::new(FrozenAccountScope::new(
|
||||
Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([
|
||||
(
|
||||
declared.clone(),
|
||||
RuntimeAccount::new(provider.clone(), BTreeSet::new()).with_model_access(
|
||||
AccountModelAccess::new(
|
||||
AccountModelAccessMode::Allowlist,
|
||||
vec!["unrelated".into()],
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
),
|
||||
(
|
||||
other.clone(),
|
||||
RuntimeAccount::new(provider.clone(), BTreeSet::new()),
|
||||
),
|
||||
]))),
|
||||
ClientRoutingScope::all_accounts(),
|
||||
));
|
||||
assert!(
|
||||
!snapshot
|
||||
.public_models_for_operation(&blocked, &operation("", false))
|
||||
.contains(&base)
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&operation("MEDIUM", false),
|
||||
blocked,
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
// 同名插件模型也不能把分组候选重新扩大到未声明成员关系的账号
|
||||
let snapshot = snapshot.with_extensions(Some(ExtensionSetReference::new(
|
||||
ExtensionSetId::new("group-collision".into()).unwrap(),
|
||||
Arc::new(ModelLease(vec![gateway_core::routing::ContributedModel {
|
||||
owner: "fixture".into(),
|
||||
id: base.clone(),
|
||||
provider,
|
||||
accounts: BTreeSet::from([other.clone()]),
|
||||
capabilities: caps(),
|
||||
presentation: ModelPresentation::new(None, None),
|
||||
}])),
|
||||
)));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&operation("MEDIUM", false),
|
||||
scope,
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(plan.candidates()[0].account_scope().allows(&declared));
|
||||
assert!(!plan.candidates()[0].account_scope().allows(&other));
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestSnapshotStore {
|
||||
facts: Arc<Mutex<Result<SnapshotFacts, SnapshotStoreError>>>,
|
||||
|
||||
@@ -23,6 +23,23 @@ pub struct RequestObservation {
|
||||
pub compact: bool,
|
||||
}
|
||||
|
||||
/// 计数入口的生成封套优先于顶层内容,沿用生成请求的协议观测
|
||||
#[must_use]
|
||||
pub fn token_count_observation(
|
||||
protocol: &str,
|
||||
body: &Map<String, Value>,
|
||||
context: &Map<String, Value>,
|
||||
) -> RequestObservation {
|
||||
let body = if protocol == GENAI_PROTOCOL {
|
||||
body.get("generateContentRequest")
|
||||
.and_then(Value::as_object)
|
||||
.unwrap_or(body)
|
||||
} else {
|
||||
body
|
||||
};
|
||||
request_observation(protocol, body, context, None)
|
||||
}
|
||||
|
||||
/// 旧配置只由状态所属 Provider 提供,是否继承仍由当前协议的续接语义决定
|
||||
#[must_use]
|
||||
pub fn request_observation(
|
||||
|
||||
@@ -1,6 +1,35 @@
|
||||
//! 验证不同协议的共享请求事实
|
||||
|
||||
use gateway_protocol::request::{request_facts, request_observation};
|
||||
|
||||
#[test]
|
||||
fn token_count_observation_uses_the_nested_generation_request() {
|
||||
for (body, expected) in [
|
||||
(
|
||||
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"MEDIUM"}}}),
|
||||
Some("medium"),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"generation_config":{"thinking_config":{"thinking_level":"HIGH"}}}),
|
||||
Some("high"),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"HIGH"}},"generateContentRequest":{"generationConfig":{"thinkingConfig":{"thinkingLevel":"MEDIUM"}}}}),
|
||||
Some("medium"),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"HIGH"}},"generateContentRequest":{"contents":[]}}),
|
||||
None,
|
||||
),
|
||||
] {
|
||||
let observation = gateway_protocol::request::token_count_observation(
|
||||
"genai",
|
||||
body.as_object().unwrap(),
|
||||
&Default::default(),
|
||||
);
|
||||
assert_eq!(observation.reasoning_effort.as_deref(), expected);
|
||||
}
|
||||
}
|
||||
use serde_json::{Map, json};
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -12,7 +12,9 @@ use gateway_core::{
|
||||
account::{AccountCatalogObservation, ProviderAccountId, StoredAccountCatalog},
|
||||
error::{ProviderError, ProviderErrorKind as Kind},
|
||||
operation::OperationKind,
|
||||
routing::{ModelCapabilities, ProviderModelCapabilities, UpstreamModelId},
|
||||
routing::{
|
||||
ModelCapabilities, ProviderModelCapabilities, ReasoningModelVariant, UpstreamModelId,
|
||||
},
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
@@ -164,7 +166,21 @@ impl CatalogService {
|
||||
&self,
|
||||
) -> Result<Vec<ProviderModelCapabilities>, ProviderError> {
|
||||
let mut models: BTreeMap<UpstreamModelId, BTreeSet<ProviderAccountId>> = BTreeMap::new();
|
||||
let mut groups: BTreeMap<UpstreamModelId, BTreeMap<String, ReasoningModelVariant>> =
|
||||
BTreeMap::new();
|
||||
for (accounts, catalog) in self.catalogs().await? {
|
||||
for (group, level, target) in super::model_groups::variants(&catalog) {
|
||||
groups
|
||||
.entry(group)
|
||||
.or_default()
|
||||
.entry(level)
|
||||
.or_insert_with(|| ReasoningModelVariant {
|
||||
model: target,
|
||||
accounts: BTreeSet::new(),
|
||||
})
|
||||
.accounts
|
||||
.extend(accounts.iter().map(|a| a.account_id.clone()));
|
||||
}
|
||||
for key in catalog.models.into_keys() {
|
||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||
models
|
||||
@@ -173,9 +189,21 @@ impl CatalogService {
|
||||
.extend(accounts.iter().map(|a| a.account_id.clone()));
|
||||
}
|
||||
}
|
||||
// 上游已有同名实体时保留原生型号,不让其他账号的分组覆盖它
|
||||
groups.retain(|group, _| !models.contains_key(group));
|
||||
for (group, variants) in &groups {
|
||||
models.insert(
|
||||
group.clone(),
|
||||
variants
|
||||
.values()
|
||||
.flat_map(|v| v.accounts.iter().cloned())
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
Ok(models
|
||||
.into_iter()
|
||||
.map(|(model, accounts)| {
|
||||
let variants = groups.remove(&model).unwrap_or_default();
|
||||
ProviderModelCapabilities::new(
|
||||
model,
|
||||
ModelCapabilities::new(
|
||||
@@ -187,7 +215,8 @@ impl CatalogService {
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||
])
|
||||
.with_upstream_feature_validation(),
|
||||
.with_upstream_feature_validation()
|
||||
.with_reasoning_variants(variants),
|
||||
)
|
||||
.with_catalog_accounts(accounts)
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
mod authorization;
|
||||
pub(crate) mod catalog;
|
||||
mod documents;
|
||||
mod model_groups;
|
||||
pub(crate) mod oauth;
|
||||
pub(crate) mod quota;
|
||||
mod refresh;
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
//! 从上游分组声明提取实际存在的推理档位,不按型号前缀猜测成员
|
||||
|
||||
use crate::transport::Catalog;
|
||||
use gateway_core::routing::UpstreamModelId;
|
||||
|
||||
pub(super) fn variants(catalog: &Catalog) -> Vec<(UpstreamModelId, String, UpstreamModelId)> {
|
||||
let mut variants = Vec::new();
|
||||
let Some(groups) = catalog.grouped_models.as_object() else {
|
||||
return variants;
|
||||
};
|
||||
for (group, description) in groups {
|
||||
let Ok(group_id) = UpstreamModelId::new(group) else {
|
||||
continue;
|
||||
};
|
||||
let Some(levels) = description["supportedThinkingLevels"].as_array() else {
|
||||
continue;
|
||||
};
|
||||
for level in levels {
|
||||
let Some(suffix) = level["thinkingSuffix"].as_str() else {
|
||||
continue;
|
||||
};
|
||||
if suffix.is_empty()
|
||||
|| !suffix
|
||||
.split('-')
|
||||
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let level = suffix.to_ascii_lowercase();
|
||||
let target = format!("{group}-{level}");
|
||||
if catalog.models.contains_key(&target)
|
||||
&& let Ok(target) = UpstreamModelId::new(target)
|
||||
{
|
||||
variants.push((group_id.clone(), level, target));
|
||||
}
|
||||
}
|
||||
}
|
||||
variants
|
||||
}
|
||||
@@ -20,6 +20,8 @@ const MAX_CONTROL_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
|
||||
pub(crate) struct Catalog {
|
||||
pub(crate) project: String,
|
||||
pub(crate) models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
pub(crate) grouped_models: serde_json::Value,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -101,6 +103,8 @@ impl CloudCodeClient {
|
||||
#[derive(Deserialize)]
|
||||
struct Models {
|
||||
models: BTreeMap<String, Model>,
|
||||
#[serde(rename = "groupedModels", default)]
|
||||
grouped_models: serde_json::Value,
|
||||
}
|
||||
let models: Models = control(
|
||||
self.post("fetchAvailableModels", token)
|
||||
@@ -118,6 +122,7 @@ impl CloudCodeClient {
|
||||
Ok(Catalog {
|
||||
project,
|
||||
models: models.models,
|
||||
grouped_models: models.grouped_models,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
mod authorization;
|
||||
#[path = "../../src/credential/documents.rs"]
|
||||
mod documents;
|
||||
#[path = "../../src/credential/model_groups.rs"]
|
||||
mod model_groups;
|
||||
#[path = "../../src/credential/oauth.rs"]
|
||||
pub(crate) mod oauth;
|
||||
#[path = "../../src/credential/refresh.rs"]
|
||||
|
||||
@@ -195,6 +195,122 @@ async fn mock_project(upstream: &MockServer) {
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
routing::{ConfigRevision, ProviderModel, PublicModelId, RoutingContext, RuntimeSnapshot},
|
||||
settings::SettingsValues,
|
||||
};
|
||||
let upstream = MockServer::start().await;
|
||||
let fixture = Fixture::new(&upstream.uri());
|
||||
*fixture.store.primary().catalog.lock().unwrap() = None;
|
||||
mock_project(&upstream).await;
|
||||
Mock::given(path("/v1internal:fetchAvailableModels"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
|
||||
"models": {
|
||||
"gemini-4-hydrogen-medium": {"displayName":"Hydrogen Medium"},
|
||||
"gemini-4-hydrogen-high": {"displayName":"Hydrogen High"},
|
||||
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"}
|
||||
},
|
||||
"groupedModels": {
|
||||
"gemini-4-hydrogen": {"supportedThinkingLevels":[
|
||||
{"thinkingSuffix":"MEDIUM"}, {"thinkingSuffix":"high"},
|
||||
{"thinkingSuffix":"low"}, {"thinkingSuffix":"../sonar"}
|
||||
]},
|
||||
"unknown-family": {"supportedThinkingLevels":[{"thinkingSuffix":"medium"}]}
|
||||
}
|
||||
})))
|
||||
.expect(1)
|
||||
.mount(&upstream)
|
||||
.await;
|
||||
fixture
|
||||
.catalog
|
||||
.reconcile(&CancellationToken::new())
|
||||
.await
|
||||
.unwrap();
|
||||
let kind = ProviderKind::new("antigravity").unwrap();
|
||||
let models = fixture.provider.query_model_capabilities().await.unwrap();
|
||||
assert_eq!(models.len(), 4);
|
||||
let group = models
|
||||
.iter()
|
||||
.find(|model| model.upstream_model().as_str() == "gemini-4-hydrogen")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
group
|
||||
.capabilities()
|
||||
.reasoning_variants()
|
||||
.keys()
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["high", "medium"]
|
||||
);
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
SettingsValues::new(2, "smart", Default::default(), None, None),
|
||||
vec![kind.clone()],
|
||||
models
|
||||
.iter()
|
||||
.map(|model| {
|
||||
ProviderModel::new(
|
||||
kind.clone(),
|
||||
model.upstream_model().clone(),
|
||||
model.capabilities().clone(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
for stream in [false, true] {
|
||||
let response = json!({"response":{"candidates":[{"content":{"parts":[{"text":"OK"}]},"finishReason":"STOP"}]}});
|
||||
let path_name = if stream {
|
||||
"/v1internal:streamGenerateContent"
|
||||
} else {
|
||||
"/v1internal:generateContent"
|
||||
};
|
||||
let template = if stream {
|
||||
ResponseTemplate::new(200)
|
||||
.set_body_raw(format!("data: {response}\n\n"), "text/event-stream")
|
||||
} else {
|
||||
ResponseTemplate::new(200).set_body_json(response)
|
||||
};
|
||||
Mock::given(path(path_name))
|
||||
.and(body_partial_json(json!({"model":"gemini-4-hydrogen-medium", "project":"probe-project", "request":{"generationConfig":{"maxOutputTokens":65536,"thinkingConfig":{"thinkingLevel":"MEDIUM","includeThoughts":true}}}})))
|
||||
.respond_with(template).expect(1).mount(&upstream).await;
|
||||
let body = json!({"contents":[{"role":"user","parts":[{"text":"Reply only OK."}]}],"generationConfig":{"maxOutputTokens":65536,"thinkingConfig":{"thinkingLevel":"MEDIUM","includeThoughts":true}}});
|
||||
let operation = 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 = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new("gemini-4-hydrogen").unwrap(),
|
||||
&operation,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let request = ProviderRequest::new(operation, plan.candidates()[0].clone());
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(request, context(frozen_profile(), CancellationToken::new()))
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(events.iter().any(|event| event.has_client_event()));
|
||||
released(&fixture).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disabled_account_probe_discovers_its_own_project_on_first_poll() {
|
||||
let upstream = MockServer::start().await;
|
||||
|
||||
@@ -250,6 +250,8 @@ Messages 与 Responses 的转换边界见 [Messages 请求](#messages-请求),
|
||||
|
||||
客户端用 `Authorization: Bearer <Client Key>` 访问以下 GenAI 短路径。模型名取自 URL,入口只在当前 Key 的账号范围内选择声明 GenAI 协议的原生模型。目前由 Antigravity 使用 OAuth 账号查询上游项目和可用模型。目录与凭据版本绑定,调度选定账号后,网关把原生正文、项目和模型发送到该注册对应的资源服务。个人账号的登录可用性见下文的 Antigravity OAuth。
|
||||
|
||||
上游目录声明的模型分组支持使用基础模型名,并通过 `generationConfig.thinkingConfig.thinkingLevel` 指定档位,例如 `gemini-4-hydrogen` 配合 `MEDIUM`。网关只选择该账号目录明确列出的分组成员,账号和分组模型限制按最终型号校验;目录中至少有一个可访问档位时才显示基础模型名。缺少或不支持的档位返回 400,显式完整型号及指向完整型号的模型映射保持原目标。分组能力随上游目录刷新,旧缓存未包含分组时仍只提供完整型号
|
||||
|
||||
| 方法 | 路径 | 交付 |
|
||||
| --- | --- | --- |
|
||||
| POST | `/v1beta/models/{model}:generateContent` | 原生 JSON |
|
||||
|
||||
@@ -715,6 +715,8 @@ Core 按映射后的模型冻结 Provider 归属:已知模型只在明确声
|
||||
未被任何目录识别的模型只有一个 Provider 透传候选时才交由上游验证,多个未知候选不按名称顺序猜选平台。
|
||||
OpenAI Provider 在选号时排除 Grok 模型的 ChatGPT OAuth 账号,API Key 兼容上游仍可透传
|
||||
|
||||
Provider 可从上游目录声明模型分组的推理档位、目标型号和来源账号。Core 使用协议层提取的显式档位解析目标,再按目标型号收窄账号范围并检查权限;目录展示复用成员的授权事实,不从模型前缀推测分组或默认档位。Antigravity 保存上游分组声明,完整型号不参与分组改写
|
||||
|
||||
账号选择综合启停状态、credential/quota 事实、Redis cooldown、并发上限、权重和会话亲和。
|
||||
默认账号并发上限为 `0` 时表示无限;账号独立正数上限仍优先,未设置则继承默认值。
|
||||
无限并发只跳过并发上限判断,保留在途租约计数及其他准入约束;含无限账号的容量不投影有限占用比例。
|
||||
|
||||
Reference in New Issue
Block a user