mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-26 08:00:48 +00:00
feat(antigravity): expose scoped model groups in the Codex catalog
Project reasoning variants, descriptions, image support, and context windows from the models available to each client key. Apply output limits to the selected model and account. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -424,12 +424,17 @@ impl FrozenAccountScope {
|
||||
#[must_use]
|
||||
pub fn excluding_account(&self, account: ProviderAccountId) -> Self {
|
||||
let mut restricted = self.clone();
|
||||
let mut excluded = self.excluded_account_ids.as_ref().clone();
|
||||
excluded.insert(account);
|
||||
restricted.excluded_account_ids = Arc::new(excluded);
|
||||
restricted.exclude_accounts([account]);
|
||||
restricted
|
||||
}
|
||||
|
||||
pub(crate) fn exclude_accounts(
|
||||
&mut self,
|
||||
accounts: impl IntoIterator<Item = ProviderAccountId>,
|
||||
) {
|
||||
Arc::make_mut(&mut self.excluded_account_ids).extend(accounts);
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn allows(&self, account_id: &ProviderAccountId) -> bool {
|
||||
self.allows_with_policy(account_id, |_| true)
|
||||
|
||||
@@ -19,6 +19,48 @@ pub struct ReasoningModelVariant {
|
||||
pub accounts: BTreeSet<ProviderAccountId>,
|
||||
}
|
||||
|
||||
/// 具体型号在单个账号目录中声明的能力与说明
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AccountModelMetadata {
|
||||
pub description: Option<String>,
|
||||
pub context_window_tokens: Option<u64>,
|
||||
pub max_context_window_tokens: Option<u64>,
|
||||
pub image_input: bool,
|
||||
pub max_output_tokens: Option<u64>,
|
||||
}
|
||||
|
||||
impl ModelPresentation {
|
||||
/// 分组向客户端承诺的能力必须覆盖每个可选档位和账号
|
||||
pub(super) fn apply_member_metadata<'a>(
|
||||
&mut self,
|
||||
mut members: impl Iterator<Item = Option<&'a AccountModelMetadata>>,
|
||||
) {
|
||||
let Some(first) = members.next() else {
|
||||
return;
|
||||
};
|
||||
let mut has_metadata = first.is_some();
|
||||
let mut description = first.and_then(|m| m.description.as_deref());
|
||||
let mut window = first.and_then(|m| m.context_window_tokens);
|
||||
let mut max_window = first.and_then(|m| m.max_context_window_tokens);
|
||||
let mut images = first.is_some_and(|m| m.image_input);
|
||||
for member in members {
|
||||
has_metadata |= member.is_some();
|
||||
if description != member.and_then(|m| m.description.as_deref()) {
|
||||
description = None;
|
||||
}
|
||||
window = window.min(member.and_then(|m| m.context_window_tokens));
|
||||
max_window = max_window.min(member.and_then(|m| m.max_context_window_tokens));
|
||||
images &= member.is_some_and(|m| m.image_input);
|
||||
}
|
||||
if has_metadata {
|
||||
self.description = description.map(str::to_owned);
|
||||
self.context_window_tokens = window;
|
||||
self.max_context_window_tokens = max_window;
|
||||
self.image_input = images;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 扩展集合持有的直接模型别名;执行与元数据仍归属内置 Provider
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContributedModelAlias {
|
||||
|
||||
@@ -11,9 +11,9 @@ pub use crate::account::scope::{
|
||||
};
|
||||
pub use crate::identity::ProviderKind;
|
||||
pub use catalog::{
|
||||
ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, ProviderCatalogPort,
|
||||
ProviderCatalogUnavailable, ProviderModelCapabilities, ProviderModelContent,
|
||||
ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant,
|
||||
AccountModelMetadata, ContributedModel, ContributedModelAlias, ProviderCatalogGeneration,
|
||||
ProviderCatalogPort, ProviderCatalogUnavailable, ProviderModelCapabilities,
|
||||
ProviderModelContent, ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant,
|
||||
};
|
||||
pub use snapshot::RuntimeSnapshot;
|
||||
|
||||
@@ -160,6 +160,7 @@ pub struct ModelCapabilities {
|
||||
generation_protocol: Option<&'static str>,
|
||||
translated_generation_protocols: BTreeSet<&'static str>,
|
||||
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
account_metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||
}
|
||||
|
||||
/// Provider 为客户端模型目录提供的展示与交互能力
|
||||
@@ -435,6 +436,7 @@ impl ModelCapabilities {
|
||||
generation_protocol: None,
|
||||
translated_generation_protocols: BTreeSet::new(),
|
||||
reasoning_variants: BTreeMap::new(),
|
||||
account_metadata: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -459,6 +461,15 @@ impl ModelCapabilities {
|
||||
&self.reasoning_variants
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_account_metadata(
|
||||
mut self,
|
||||
metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||
) -> Self {
|
||||
self.account_metadata = metadata;
|
||||
self
|
||||
}
|
||||
|
||||
/// 将请求形态 feature 的最终合法性判断交给上游 wire API
|
||||
#[must_use]
|
||||
pub const fn with_upstream_feature_validation(mut self) -> Self {
|
||||
|
||||
@@ -958,32 +958,35 @@ impl RuntimeSnapshot {
|
||||
let mut profiles = BTreeMap::new();
|
||||
for (model, presentation) in presentations {
|
||||
if let Ok(public_model) = PublicModelId::new(model.as_str().to_owned()) {
|
||||
profiles.insert(public_model, presentation.clone());
|
||||
profiles.insert(public_model, presentation);
|
||||
}
|
||||
}
|
||||
// 映射覆盖同名模型时,只展示目标画像,包括目标没有画像的情况
|
||||
for alias in self.settings.values.model_mappings.keys() {
|
||||
let target = self.mapped_model(alias);
|
||||
let Some(presentation) = presentations.iter().find_map(|(model, presentation)| {
|
||||
(model.as_str() == target).then_some(presentation)
|
||||
}) else {
|
||||
let Ok(public_model) = PublicModelId::new(alias.clone()) else {
|
||||
continue;
|
||||
};
|
||||
if let Ok(public_model) = PublicModelId::new(alias.clone()) {
|
||||
profiles.insert(public_model, presentation.clone());
|
||||
let target = self.mapped_model(alias);
|
||||
if let Some(presentation) = presentations.get(target.as_str()) {
|
||||
profiles.insert(public_model, presentation);
|
||||
} else {
|
||||
profiles.remove(&public_model);
|
||||
}
|
||||
}
|
||||
for alias in self
|
||||
.model_aliases()
|
||||
.iter()
|
||||
.filter(|alias| &alias.provider == provider)
|
||||
{
|
||||
if let Some(presentation) = presentations.get(&alias.target) {
|
||||
profiles.insert(alias.id.clone(), presentation.clone());
|
||||
for alias in self.model_aliases() {
|
||||
if &alias.provider == provider
|
||||
&& let Some(presentation) = presentations.get(&alias.target)
|
||||
{
|
||||
profiles.insert(alias.id.clone(), presentation);
|
||||
} else {
|
||||
profiles.remove(&alias.id);
|
||||
}
|
||||
}
|
||||
profiles
|
||||
.into_iter()
|
||||
.map(|(model, presentation)| super::PublicModelProfile::new(model, presentation))
|
||||
.map(|(model, presentation)| {
|
||||
super::PublicModelProfile::new(model, presentation.clone())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
@@ -1137,8 +1140,30 @@ impl RuntimeSnapshot {
|
||||
scope: &FrozenAccountScope,
|
||||
) -> Vec<super::PublicModelProfile> {
|
||||
let mut profiles = self.public_model_profiles_for_provider(provider);
|
||||
profiles.retain(|profile| {
|
||||
self.native_catalog_model_allowed_for_scope(provider, profile.model(), scope)
|
||||
profiles.retain_mut(|profile| {
|
||||
let target = self.mapped_model(profile.model.as_str());
|
||||
let Some(group) = self.model_group(provider, &target) else {
|
||||
return self.native_catalog_model_allowed_for_scope(
|
||||
provider,
|
||||
profile.model(),
|
||||
scope,
|
||||
);
|
||||
};
|
||||
let models = &self.provider_models[provider];
|
||||
let mut members = group
|
||||
.reasoning_variants
|
||||
.values()
|
||||
.flat_map(|variant| {
|
||||
let model = models.get(&variant.model);
|
||||
Self::variant_accounts(provider, variant, scope)
|
||||
.map(move |id| model.and_then(|m| m.account_metadata.get(id)))
|
||||
})
|
||||
.peekable();
|
||||
if members.peek().is_none() {
|
||||
return false;
|
||||
}
|
||||
profile.presentation.apply_member_metadata(members);
|
||||
true
|
||||
});
|
||||
// Provider 画像按公开 ID 排序,追加的插件画像保留注册顺序,不参与二分查找
|
||||
let provider_count = profiles.len();
|
||||
@@ -1150,6 +1175,30 @@ impl RuntimeSnapshot {
|
||||
Err(_) => profiles.push(model.public_profile()),
|
||||
}
|
||||
}
|
||||
// 别名及适配器画像也按路由选中的分组成员裁剪,默认档位必须能在当前范围执行
|
||||
profiles.retain_mut(|profile| {
|
||||
let Some(group) =
|
||||
self.model_group(provider, &self.mapped_model(profile.model.as_str()))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let presentation = &mut profile.presentation;
|
||||
presentation.supported_reasoning_efforts.retain(|effort| {
|
||||
group
|
||||
.reasoning_variants
|
||||
.get(effort)
|
||||
.is_some_and(|variant| self.variant_allowed(provider, variant, scope))
|
||||
});
|
||||
let efforts = &presentation.supported_reasoning_efforts;
|
||||
if !presentation
|
||||
.default_reasoning_effort
|
||||
.as_ref()
|
||||
.is_some_and(|default| efforts.contains(default))
|
||||
{
|
||||
presentation.default_reasoning_effort = efforts.first().cloned();
|
||||
}
|
||||
!efforts.is_empty()
|
||||
});
|
||||
profiles
|
||||
}
|
||||
|
||||
@@ -1286,7 +1335,17 @@ impl RuntimeSnapshot {
|
||||
variant: &super::ReasoningModelVariant,
|
||||
scope: &FrozenAccountScope,
|
||||
) -> bool {
|
||||
variant.accounts.iter().any(|account| {
|
||||
Self::variant_accounts(provider, variant, scope)
|
||||
.next()
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn variant_accounts<'a>(
|
||||
provider: &'a ProviderKind,
|
||||
variant: &'a super::ReasoningModelVariant,
|
||||
scope: &'a FrozenAccountScope,
|
||||
) -> impl Iterator<Item = &'a ProviderAccountId> {
|
||||
variant.accounts.iter().filter(move |account| {
|
||||
scope.account_provider(account) == Some(provider)
|
||||
&& scope.allows_model(account, variant.model.as_str())
|
||||
})
|
||||
@@ -1685,6 +1744,33 @@ impl RuntimeSnapshot {
|
||||
}
|
||||
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);
|
||||
}
|
||||
}
|
||||
candidates.push(ProviderCandidate {
|
||||
requires_direct_authentication: direct_model.is_some(),
|
||||
provider: provider.clone(),
|
||||
|
||||
@@ -34,9 +34,9 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
GenerateRequest, Operation, ProtocolPayload, RawJsonPayload, TokenCountRequest,
|
||||
},
|
||||
routing::{
|
||||
ClientRoutingScope, FrozenAccountScope, ProviderModel, ReasoningModelVariant,
|
||||
RoutingContext, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory,
|
||||
RuntimeSnapshot,
|
||||
AccountModelMetadata, ClientRoutingScope, FrozenAccountScope, ProviderModel,
|
||||
ReasoningModelVariant, RoutingContext, RoutingGroupSnapshot, RuntimeAccount,
|
||||
RuntimeAccountDirectory, RuntimeSnapshot,
|
||||
},
|
||||
validation::RoutingError,
|
||||
};
|
||||
@@ -44,16 +44,19 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
let provider = ProviderKind::new("alpha").unwrap();
|
||||
let declared = ProviderAccountId::new("acct_declared").unwrap();
|
||||
let other = ProviderAccountId::new("acct_other").unwrap();
|
||||
let high_only = ProviderAccountId::new("acct_high").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()])),
|
||||
)
|
||||
}),
|
||||
[declared.clone(), other.clone(), high_only.clone()]
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
(
|
||||
id,
|
||||
RuntimeAccount::new(provider.clone(), BTreeSet::from([group.clone()])),
|
||||
)
|
||||
}),
|
||||
))
|
||||
.with_group_model_access(BTreeMap::from([(
|
||||
group.clone(),
|
||||
@@ -84,7 +87,11 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
level.into(),
|
||||
ReasoningModelVariant {
|
||||
model: UpstreamModelId::new(format!("family-{level}")).unwrap(),
|
||||
accounts: BTreeSet::from([declared.clone()]),
|
||||
accounts: if level == "medium" {
|
||||
BTreeSet::from([declared.clone()])
|
||||
} else {
|
||||
BTreeSet::from([declared.clone(), high_only.clone()])
|
||||
},
|
||||
},
|
||||
)
|
||||
}));
|
||||
@@ -93,7 +100,10 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
SettingsValues::new(
|
||||
2,
|
||||
"smart",
|
||||
BTreeMap::from([("alias".into(), "family".into())]),
|
||||
BTreeMap::from([
|
||||
("alias".into(), "family".into()),
|
||||
("pinned".into(), "family-medium".into()),
|
||||
]),
|
||||
None,
|
||||
None,
|
||||
),
|
||||
@@ -103,17 +113,57 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family").unwrap(),
|
||||
caps().with_reasoning_variants(variants),
|
||||
)
|
||||
.with_presentation(
|
||||
ModelPresentation::default()
|
||||
.with_reasoning(Some("high".into()), vec!["medium".into(), "high".into()]),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family-medium").unwrap(),
|
||||
caps(),
|
||||
caps().with_account_metadata(BTreeMap::from([
|
||||
(
|
||||
declared.clone(),
|
||||
AccountModelMetadata {
|
||||
context_window_tokens: Some(1000),
|
||||
max_context_window_tokens: Some(1500),
|
||||
image_input: true,
|
||||
description: Some("Medium".into()),
|
||||
max_output_tokens: Some(25),
|
||||
},
|
||||
),
|
||||
(other.clone(), AccountModelMetadata::default()),
|
||||
])),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("family-high").unwrap(),
|
||||
caps(),
|
||||
caps().with_account_metadata(BTreeMap::from([
|
||||
(
|
||||
declared.clone(),
|
||||
AccountModelMetadata {
|
||||
max_context_window_tokens: Some(2000),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
(
|
||||
high_only.clone(),
|
||||
AccountModelMetadata {
|
||||
context_window_tokens: Some(800),
|
||||
max_context_window_tokens: Some(1800),
|
||||
image_input: true,
|
||||
description: Some("High".into()),
|
||||
max_output_tokens: Some(100),
|
||||
},
|
||||
),
|
||||
])),
|
||||
),
|
||||
ProviderModel::new(
|
||||
provider.clone(),
|
||||
UpstreamModelId::new("pinned").unwrap(),
|
||||
caps(),
|
||||
)
|
||||
.with_presentation(ModelPresentation::default()),
|
||||
],
|
||||
vec![],
|
||||
)
|
||||
@@ -143,6 +193,93 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
}
|
||||
};
|
||||
let base = PublicModelId::new("family").unwrap();
|
||||
let profiles = snapshot.public_model_profiles_for_scope(&scope);
|
||||
assert_eq!(
|
||||
profiles
|
||||
.iter()
|
||||
.map(|profile| profile.model().as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["alias", "family"]
|
||||
);
|
||||
for profile in &profiles {
|
||||
assert_eq!(profile.presentation().context_window_tokens(), Some(1000));
|
||||
assert_eq!(
|
||||
profile.presentation().max_context_window_tokens(),
|
||||
Some(1500)
|
||||
);
|
||||
assert!(profile.presentation().image_input());
|
||||
assert_eq!(profile.presentation().description(), Some("Medium"));
|
||||
assert_eq!(
|
||||
profile.presentation().supported_reasoning_efforts(),
|
||||
["medium"]
|
||||
);
|
||||
assert_eq!(
|
||||
profile.presentation().default_reasoning_effort(),
|
||||
Some("medium")
|
||||
);
|
||||
}
|
||||
let all = FrozenAccountScope::new(
|
||||
Arc::clone(scope.directory()),
|
||||
ClientRoutingScope::all_accounts(),
|
||||
);
|
||||
let mixed = snapshot.public_model_profiles_for_scope(&all);
|
||||
assert!(mixed.iter().all(|p| !p.presentation().image_input()
|
||||
&& p.presentation().context_window_tokens().is_none()
|
||||
&& p.presentation().max_context_window_tokens() == Some(1500)
|
||||
&& p.presentation().description().is_none()));
|
||||
let only_high_scope = all.restricted_to(&BTreeSet::new(), &BTreeSet::from([high_only]));
|
||||
let only_high = snapshot.public_model_profiles_for_scope(&only_high_scope);
|
||||
assert_eq!(only_high.len(), 2);
|
||||
for profile in only_high {
|
||||
assert_eq!(
|
||||
profile.presentation().supported_reasoning_efforts(),
|
||||
["high"]
|
||||
);
|
||||
assert_eq!(profile.presentation().context_window_tokens(), Some(800));
|
||||
assert_eq!(
|
||||
profile.presentation().max_context_window_tokens(),
|
||||
Some(1800)
|
||||
);
|
||||
assert!(profile.presentation().image_input());
|
||||
assert_eq!(profile.presentation().description(), Some("High"));
|
||||
}
|
||||
// 显式输出只约束返回已知上限的账号,旧目录仍能由上游校验
|
||||
let output_request = |tokens| {
|
||||
let body = serde_json::json!({"contents":[],"generationConfig":{"maxOutputTokens":tokens,"thinkingConfig":{"thinkingLevel":"MEDIUM"}}});
|
||||
Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("genai", body.as_object().unwrap().clone()).unwrap(),
|
||||
))
|
||||
};
|
||||
assert!(
|
||||
snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&output_request(25),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.plan(
|
||||
&base,
|
||||
&output_request(26),
|
||||
scope.clone(),
|
||||
&RoutingContext::default()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
let direct = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new("family-medium").unwrap(),
|
||||
&output_request(26),
|
||||
scope.clone(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!direct.candidates()[0].account_scope().allows(&declared));
|
||||
assert!(direct.candidates()[0].account_scope().allows(&other));
|
||||
for count in [false, true] {
|
||||
for name in ["family", "alias"] {
|
||||
for level in ["MEDIUM", "medium"] {
|
||||
@@ -256,6 +393,11 @@ fn reasoning_groups_resolve_before_account_and_group_model_policies() {
|
||||
.public_models_for_operation(&blocked, &operation("", false))
|
||||
.contains(&base)
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.public_model_profiles_for_scope(&blocked)
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
snapshot
|
||||
.plan(
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use crate::{
|
||||
credential::{CredentialService, oauth::error},
|
||||
transport::{Catalog, CloudCodeClient, unsent},
|
||||
transport::{Catalog, CloudCodeClient, Model, unsent},
|
||||
};
|
||||
use gateway_admin::{
|
||||
model::provider_credentials::{ProviderModel, ProviderModels},
|
||||
@@ -13,11 +13,11 @@ use gateway_core::{
|
||||
error::{ProviderError, ProviderErrorKind as Kind},
|
||||
operation::OperationKind,
|
||||
routing::{
|
||||
ModelCapabilities, ProviderModelCapabilities, ReasoningModelVariant, UpstreamModelId,
|
||||
AccountModelMetadata, ModelCapabilities, ProviderModelCapabilities, UpstreamModelId,
|
||||
},
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
collections::BTreeMap,
|
||||
sync::{
|
||||
Arc, Mutex,
|
||||
atomic::{AtomicU64, AtomicUsize, Ordering},
|
||||
@@ -165,62 +165,61 @@ impl CatalogService {
|
||||
pub(crate) async fn capabilities(
|
||||
&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 mut members =
|
||||
BTreeMap::<UpstreamModelId, BTreeMap<ProviderAccountId, AccountModelMetadata>>::new();
|
||||
let mut groups = BTreeMap::new();
|
||||
let mut catalogs = self.catalogs().await?;
|
||||
// 多个账号的目录有交集时,按稳定来源顺序合并展示名和档位顺序
|
||||
catalogs.sort_by(|(left, _), (right, _)| {
|
||||
left.first()
|
||||
.map(|a| &a.account_id)
|
||||
.cmp(&right.first().map(|a| &a.account_id))
|
||||
});
|
||||
for (accounts, catalog) in catalogs {
|
||||
super::model_groups::collect(&mut groups, &catalog, &accounts);
|
||||
for (key, model) in catalog.models {
|
||||
let id = UpstreamModelId::new(key).map_err(|_| unsent(Kind::Protocol))?;
|
||||
models
|
||||
.entry(id)
|
||||
.or_default()
|
||||
.extend(accounts.iter().map(|a| a.account_id.clone()));
|
||||
let metadata = account_metadata(model);
|
||||
members.entry(id).or_default().extend(
|
||||
accounts
|
||||
.iter()
|
||||
.map(|a| (a.account_id.clone(), metadata.clone())),
|
||||
);
|
||||
}
|
||||
}
|
||||
let capabilities = ModelCapabilities::new(
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||
])
|
||||
.with_upstream_feature_validation();
|
||||
let mut models = BTreeMap::new();
|
||||
for (id, metadata) in members {
|
||||
let accounts = metadata.keys().cloned().collect();
|
||||
let model = ProviderModelCapabilities::new(
|
||||
id.clone(),
|
||||
capabilities.clone().with_account_metadata(metadata),
|
||||
);
|
||||
models.insert(id, model.with_catalog_accounts(accounts));
|
||||
}
|
||||
// 上游已有同名实体时保留原生型号,不让其他账号的分组覆盖它
|
||||
groups.retain(|group, _| !models.contains_key(group));
|
||||
for (group, variants) in &groups {
|
||||
models.insert(
|
||||
group.clone(),
|
||||
variants
|
||||
for (id, group) in groups {
|
||||
models.entry(id.clone()).or_insert_with(|| {
|
||||
let accounts = group
|
||||
.variants
|
||||
.values()
|
||||
.flat_map(|v| v.accounts.iter().cloned())
|
||||
.collect(),
|
||||
);
|
||||
.collect();
|
||||
group
|
||||
.into_model(id, capabilities.clone())
|
||||
.with_catalog_accounts(accounts)
|
||||
});
|
||||
}
|
||||
Ok(models
|
||||
.into_iter()
|
||||
.map(|(model, accounts)| {
|
||||
let variants = groups.remove(&model).unwrap_or_default();
|
||||
ProviderModelCapabilities::new(
|
||||
model,
|
||||
ModelCapabilities::new(
|
||||
[OperationKind::Generate, OperationKind::CountTokens].into(),
|
||||
None,
|
||||
)
|
||||
.with_generation_protocol(gateway_protocol::genai::GENAI_PROTOCOL)
|
||||
.with_translated_generation_protocols([
|
||||
gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
gateway_protocol::anthropic::ANTHROPIC_PROTOCOL,
|
||||
])
|
||||
.with_upstream_feature_validation()
|
||||
.with_reasoning_variants(variants),
|
||||
)
|
||||
.with_catalog_accounts(accounts)
|
||||
})
|
||||
.collect())
|
||||
Ok(models.into_values().collect())
|
||||
}
|
||||
|
||||
pub(crate) async fn account_models(
|
||||
@@ -301,6 +300,32 @@ impl CatalogService {
|
||||
}
|
||||
}
|
||||
|
||||
fn account_metadata(model: Model) -> AccountModelMetadata {
|
||||
let description = model
|
||||
.description
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty());
|
||||
let tag = model
|
||||
.tag_description
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty());
|
||||
let description = match (description, tag) {
|
||||
(Some(text), Some(tag)) if text != tag => Some(format!("{text} {tag}")),
|
||||
_ => description.or(tag).map(str::to_owned),
|
||||
};
|
||||
// AGY 只声明一个上下文窗口,默认值与可覆盖上限都取 maxTokens
|
||||
let context_window = model.context_window.filter(|n| *n > 0);
|
||||
AccountModelMetadata {
|
||||
description,
|
||||
context_window_tokens: context_window,
|
||||
max_context_window_tokens: context_window,
|
||||
max_output_tokens: model.max_output_tokens.filter(|n| *n > 0),
|
||||
image_input: model.supports_images == Some(true),
|
||||
}
|
||||
}
|
||||
|
||||
fn admin_models(
|
||||
catalog: Catalog,
|
||||
observed: SystemTime,
|
||||
|
||||
@@ -1,14 +1,50 @@
|
||||
//! 从上游分组声明提取实际存在的推理档位,不按型号前缀猜测成员
|
||||
//! 从上游分组声明提取展示名、档位顺序及实际存在的成员
|
||||
|
||||
use crate::transport::Catalog;
|
||||
use gateway_core::routing::UpstreamModelId;
|
||||
use gateway_core::{
|
||||
account::AccountCatalogObservation,
|
||||
routing::{
|
||||
ModelCapabilities, ModelPresentation, ProviderModelCapabilities, ReasoningModelVariant,
|
||||
UpstreamModelId,
|
||||
},
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
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;
|
||||
#[derive(Default)]
|
||||
pub(super) struct ModelGroup {
|
||||
display_name: Option<String>,
|
||||
efforts: Vec<String>,
|
||||
pub(super) variants: BTreeMap<String, ReasoningModelVariant>,
|
||||
}
|
||||
|
||||
impl ModelGroup {
|
||||
pub(super) fn into_model(
|
||||
self,
|
||||
model: UpstreamModelId,
|
||||
capabilities: ModelCapabilities,
|
||||
) -> ProviderModelCapabilities {
|
||||
let default = self
|
||||
.efforts
|
||||
.iter()
|
||||
.find(|level| *level == "medium")
|
||||
.or_else(|| self.efforts.first())
|
||||
.cloned();
|
||||
let presentation =
|
||||
ModelPresentation::new(self.display_name, None).with_reasoning(default, self.efforts);
|
||||
ProviderModelCapabilities::new(model, capabilities.with_reasoning_variants(self.variants))
|
||||
.with_presentation(presentation)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn collect(
|
||||
groups: &mut BTreeMap<UpstreamModelId, ModelGroup>,
|
||||
catalog: &Catalog,
|
||||
accounts: &[AccountCatalogObservation],
|
||||
) {
|
||||
let Some(declarations) = catalog.grouped_models.as_object() else {
|
||||
return;
|
||||
};
|
||||
for (group, description) in groups {
|
||||
for (group, description) in declarations {
|
||||
let Ok(group_id) = UpstreamModelId::new(group) else {
|
||||
continue;
|
||||
};
|
||||
@@ -19,10 +55,9 @@ pub(super) fn variants(catalog: &Catalog) -> Vec<(UpstreamModelId, String, Upstr
|
||||
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()))
|
||||
if !suffix
|
||||
.split('-')
|
||||
.all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_alphanumeric()))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -31,9 +66,27 @@ pub(super) fn variants(catalog: &Catalog) -> Vec<(UpstreamModelId, String, Upstr
|
||||
if catalog.models.contains_key(&target)
|
||||
&& let Ok(target) = UpstreamModelId::new(target)
|
||||
{
|
||||
variants.push((group_id.clone(), level, target));
|
||||
let entry = groups.entry(group_id.clone()).or_default();
|
||||
if entry.display_name.is_none() {
|
||||
entry.display_name = description["displayName"]
|
||||
.as_str()
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(str::to_owned);
|
||||
}
|
||||
entry
|
||||
.variants
|
||||
.entry(level.clone())
|
||||
.or_insert_with(|| {
|
||||
entry.efforts.push(level);
|
||||
ReasoningModelVariant {
|
||||
model: target,
|
||||
accounts: Default::default(),
|
||||
}
|
||||
})
|
||||
.accounts
|
||||
.extend(accounts.iter().map(|account| account.account_id.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
variants
|
||||
}
|
||||
|
||||
@@ -30,6 +30,16 @@ pub(crate) struct Model {
|
||||
pub(crate) name: String,
|
||||
#[serde(rename = "quotaInfo", default)]
|
||||
pub(crate) quota: Option<super::account::ModelQuota>,
|
||||
#[serde(default)]
|
||||
pub(crate) description: Option<String>,
|
||||
#[serde(rename = "tagDescription", default)]
|
||||
pub(crate) tag_description: Option<String>,
|
||||
#[serde(rename = "maxTokens", default)]
|
||||
pub(crate) context_window: Option<u64>,
|
||||
#[serde(rename = "maxOutputTokens", default)]
|
||||
pub(crate) max_output_tokens: Option<u64>,
|
||||
#[serde(rename = "supportsImages", default)]
|
||||
pub(crate) supports_images: Option<bool>,
|
||||
}
|
||||
|
||||
pub(crate) struct CloudCodeClient {
|
||||
|
||||
@@ -6,7 +6,7 @@ mod failure;
|
||||
mod headers;
|
||||
mod pool;
|
||||
mod response;
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, unwrap_frame};
|
||||
pub(crate) use client::{Catalog, CloudCodeClient, Model, unwrap_frame};
|
||||
pub(crate) use count::count_events;
|
||||
pub(crate) use failure::{sent, unsent};
|
||||
pub(crate) use headers::request_headers;
|
||||
|
||||
@@ -196,7 +196,7 @@ async fn mock_project(upstream: &MockServer) {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
|
||||
async fn model_group_menu_routes_responses_and_native_generation_to_declared_members() {
|
||||
use gateway_core::{
|
||||
engine::provider::ProviderRequest,
|
||||
operation::{GenerateRequest, Operation, ProtocolPayload},
|
||||
@@ -210,12 +210,12 @@ async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
|
||||
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-medium": {"displayName":"Hydrogen Medium","maxTokens":1048576,"maxOutputTokens":65536,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-high": {"displayName":"Hydrogen High","maxTokens":900000,"maxOutputTokens":262144,"supportsImages":true,"tagDescription":"Leaving on Nov 30."},
|
||||
"gemini-4-hydrogen-sonar": {"displayName":"Hydrogen Sonar"}
|
||||
},
|
||||
"groupedModels": {
|
||||
"gemini-4-hydrogen": {"supportedThinkingLevels":[
|
||||
"gemini-4-hydrogen": {"displayName":"Gemini 4 Hydrogen","supportedThinkingLevels":[
|
||||
{"thinkingSuffix":"MEDIUM"}, {"thinkingSuffix":"high"},
|
||||
{"thinkingSuffix":"low"}, {"thinkingSuffix":"../sonar"}
|
||||
]},
|
||||
@@ -237,14 +237,16 @@ async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
|
||||
.iter()
|
||||
.find(|model| model.upstream_model().as_str() == "gemini-4-hydrogen")
|
||||
.unwrap();
|
||||
let menu = group.presentation().unwrap();
|
||||
assert_eq!(menu.display_name(), Some("Gemini 4 Hydrogen"));
|
||||
assert_eq!(menu.supported_reasoning_efforts(), ["medium", "high"]);
|
||||
assert_eq!(menu.default_reasoning_effort(), Some("medium"));
|
||||
assert_eq!(
|
||||
group
|
||||
.capabilities()
|
||||
.reasoning_variants()
|
||||
.keys()
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["high", "medium"]
|
||||
models
|
||||
.iter()
|
||||
.filter(|entry| entry.presentation().is_some())
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
let snapshot = RuntimeSnapshot::new(
|
||||
ConfigRevision::new(1).unwrap(),
|
||||
@@ -253,16 +255,29 @@ async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
|
||||
models
|
||||
.iter()
|
||||
.map(|model| {
|
||||
ProviderModel::new(
|
||||
let entry = ProviderModel::new(
|
||||
kind.clone(),
|
||||
model.upstream_model().clone(),
|
||||
model.capabilities().clone(),
|
||||
)
|
||||
);
|
||||
match model.presentation() {
|
||||
Some(presentation) => entry.with_presentation(presentation.clone()),
|
||||
None => entry,
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
let profiles = snapshot.public_model_profiles_for_scope(&fixture.store.account_scope());
|
||||
let menu = profiles[0].presentation();
|
||||
assert!(menu.image_input());
|
||||
assert_eq!(menu.context_window_tokens(), Some(900000));
|
||||
assert_eq!(
|
||||
menu.max_context_window_tokens(),
|
||||
menu.context_window_tokens()
|
||||
);
|
||||
assert_eq!(menu.description(), Some("Leaving on Nov 30."));
|
||||
for stream in [false, true] {
|
||||
let response = json!({"response":{"candidates":[{"content":{"parts":[{"text":"OK"}]},"finishReason":"STOP"}]}});
|
||||
let path_name = if stream {
|
||||
@@ -309,6 +324,43 @@ async fn native_model_groups_use_the_declared_effort_for_generate_and_stream() {
|
||||
assert!(events.iter().any(|event| event.has_client_event()));
|
||||
released(&fixture).await;
|
||||
}
|
||||
Mock::given(path("/v1internal:streamGenerateContent"))
|
||||
.and(body_partial_json(json!({"model":"gemini-4-hydrogen-high","request":{"contents":[{"role":"user","parts":[{"inlineData":{"mimeType":"image/png","data":"AA=="}}]}]}})))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_raw(
|
||||
"data: {\"response\":{\"candidates\":[{\"content\":{\"parts\":[{\"text\":\"OK\"}]},\"finishReason\":\"STOP\"}]}}\n\n",
|
||||
"text/event-stream",
|
||||
)).expect(1).mount(&upstream).await;
|
||||
let body = json!({"model":group.upstream_model().as_str(),"input":[{"role":"user","content":[{"type":"input_image","image_url":"data:image/png;base64,AA=="}]}],"reasoning":{"effort":"high"}});
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||
ProtocolPayload::json_object("openai", body.as_object().unwrap().clone()).unwrap(),
|
||||
));
|
||||
let plan = snapshot
|
||||
.plan(
|
||||
&PublicModelId::new(group.upstream_model().as_str()).unwrap(),
|
||||
&operation,
|
||||
fixture.store.account_scope(),
|
||||
&RoutingContext::default(),
|
||||
)
|
||||
.unwrap();
|
||||
let events = fixture
|
||||
.provider
|
||||
.clone()
|
||||
.execute(
|
||||
ProviderRequest::new(operation, plan.candidates()[0].clone()),
|
||||
context(frozen_profile(), CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.try_collect::<Vec<_>>()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
events
|
||||
.iter()
|
||||
.flat_map(|event| event.canonical_facts())
|
||||
.any(|fact| matches!(fact, gateway_core::event::GatewayEvent::Completed(_)))
|
||||
);
|
||||
released(&fixture).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
+9
-1
@@ -763,6 +763,14 @@ API Key 上游返回完整 Codex `models` 目录时沿用该合同;仅返回
|
||||
xAI 没有 Codex 原生目录,使用官方 CLI proxy 当前目录生成通用画像。推理菜单读取
|
||||
`reasoning_efforts` 对象列表,默认值只取菜单中的显式标记;缺失时保持未知
|
||||
|
||||
Antigravity 在 Codex 目录中按上游声明的分组展示基础模型。思考菜单只列出当前 Key 可调用的成员档位,
|
||||
默认选中 `medium`,不可用时选首个可用档位。例如对 `gemini-4-hydrogen` 发送 `reasoning.effort: "high"`,
|
||||
会路由到 `gemini-4-hydrogen-high`。普通模型列表仍提供可直接调用的完整型号
|
||||
|
||||
分组中的可用档位和账号都支持图片时,Codex 可发送图片。网关取可用成员中最小的 `maxTokens` 作为该组的默认上下文窗口和可覆盖上限,
|
||||
有成员未声明时保持未知。成员说明一致时,选模列表显示上游用途说明或下线提示。
|
||||
显式请求的输出 Token 数按实际型号和账号的 `maxOutputTokens` 选路,未声明上限的账号交由上游校验
|
||||
|
||||
已知模型只路由到明确提供该模型的 Provider,账号不可用时不转发给其他平台的未知模型通道。
|
||||
未知模型只在当前范围与路由约束下存在唯一 Provider 透传候选时发送;无法确定归属时返回不可用错误,
|
||||
可通过 Client Key 分组限定目标平台。Provider 在选号时检查账号模型政策与目录资格,
|
||||
@@ -774,7 +782,7 @@ OpenAI 聚合当前 Key 范围内合格 OAuth 和 API Key 账号的目录。每
|
||||
|
||||
后台刷新失败或超时保留该账号最后成功的结果。当前范围没有任何可用的已知目录时返回 `503 model_catalog_unavailable`。
|
||||
成功读取但全部条目被账号政策过滤时返回空列表。
|
||||
目录保留完整的原生 Codex 模型对象。对于 OpenAI API Key 普通模型列表和 xAI 目录生成的通用画像,
|
||||
目录保留完整的原生 Codex 模型对象。对于 Provider 生成的通用画像,
|
||||
当前 Key 可访问的适配器若声明了同名模型,其画像在原位置替换通用画像。仅由插件提供的可见模型按声明顺序追加到所属 Provider 的条目之后
|
||||
|
||||
服务启动时批量恢复账号目录;目录读取只检查本地账号资格和 Client Key 范围,不等待上游查询。
|
||||
|
||||
Reference in New Issue
Block a user