mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 00:00:49 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8c742bd593 | ||
|
|
bc3dbb60c0 | ||
|
|
fca416f39c | ||
|
|
88da70a77b | ||
|
|
24fed4ba3a | ||
|
|
daa8292860 | ||
|
|
9961ffeeb9 | ||
|
|
8bee00c139 | ||
|
|
2c6d4a8eb6 | ||
|
|
88da31137b | ||
|
|
3da3338908 | ||
|
|
ef45165d8d | ||
|
|
75c51b9955 | ||
|
|
319b3be0f8 | ||
|
|
6de36f4b54 | ||
|
|
74ac905abf | ||
|
|
a6bdeb17f2 | ||
|
|
ce966d3d04 | ||
|
|
20d04ae57a | ||
|
|
3141bb1a9e | ||
|
|
add1f9f40f | ||
|
|
080d3867f1 | ||
|
|
0bf3c8daaf | ||
|
|
9d3d7ef223 | ||
|
|
c843a4d380 |
@@ -17,7 +17,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
> [!NOTE]
|
> [!NOTE]
|
||||||
> 生成请求支持 [OpenAI Responses](docs/api.md#responses-请求与传输)、[Chat Completions](docs/api.md#chat-completions-请求) 和 [Anthropic Messages](docs/api.md#messages-请求) 三种协议
|
> 支持 OpenAI(Codex)、xAI(Grok)和 Google Antigravity 账号,以及兼容 OpenAI Responses 或 Anthropic Messages 的 API Key 服务,详见[账号接入](docs/api.md#账号能力导入与-oauth)
|
||||||
|
|
||||||
## 快速预览
|
## 快速预览
|
||||||
|
|
||||||
|
|||||||
Generated
+2
@@ -1950,7 +1950,9 @@ dependencies = [
|
|||||||
"memchr",
|
"memchr",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
"url",
|
||||||
"uuid",
|
"uuid",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
//! 多 Provider 账号目录与连接测试的公共事实
|
//! 多 Provider 账号目录与连接测试的公共事实
|
||||||
|
|
||||||
use std::{collections::BTreeMap, pin::Pin};
|
use std::{
|
||||||
|
collections::{BTreeMap, BTreeSet},
|
||||||
|
pin::Pin,
|
||||||
|
};
|
||||||
|
|
||||||
use chrono::{DateTime, Utc};
|
use chrono::{DateTime, Utc};
|
||||||
use futures::Stream;
|
use futures::Stream;
|
||||||
@@ -192,6 +195,8 @@ pub struct AccountUsage {
|
|||||||
/// `key` 只用于把聚合结果关联回调用方的窗口,不承载 Provider 私有语义
|
/// `key` 只用于把聚合结果关联回调用方的窗口,不承载 Provider 私有语义
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct AccountUsageWindowQuery {
|
pub struct AccountUsageWindowQuery {
|
||||||
|
/// 指定时只汇总这些上游模型的请求
|
||||||
|
pub models: Option<BTreeSet<String>>,
|
||||||
pub account_id: String,
|
pub account_id: String,
|
||||||
pub key: String,
|
pub key: String,
|
||||||
pub range: TimeRange,
|
pub range: TimeRange,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! Provider 管理能力交换的中立 Command 与 Result
|
//! Provider 管理能力交换的中立 Command 与 Result
|
||||||
|
|
||||||
use std::{fmt, pin::Pin};
|
use std::{collections::BTreeSet, fmt, pin::Pin};
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
@@ -774,11 +774,13 @@ impl fmt::Debug for RotateCredential {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// 通用账号用量能否可靠归属到一个 Provider quota 窗口
|
/// 通用账号用量能否可靠归属到一个 Provider quota 窗口
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum QuotaLocalUsageAttribution {
|
pub enum QuotaLocalUsageAttribution {
|
||||||
/// 窗口覆盖账号的全部请求,可按账号与时间范围聚合
|
/// 窗口覆盖账号的全部请求,可按账号与时间范围聚合
|
||||||
AccountWide,
|
AccountWide,
|
||||||
/// 窗口需要 Provider / 模型级归属,通用账号聚合不可用
|
/// Provider 已确认该窗口覆盖的上游模型 ID
|
||||||
|
Models(BTreeSet<String>),
|
||||||
|
/// 缺少可用于归属本地用量的事实
|
||||||
Unavailable,
|
Unavailable,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -828,12 +830,46 @@ impl ProviderQuotaWindow {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 账号用量统计周期,完整周/月额度优先,缺少可归属窗口时使用本地滚动日统计
|
/// 账号用量统计周期,区分上游额度周期与独立的本地统计范围
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
pub enum AccountUsagePeriod {
|
pub enum AccountUsagePeriod {
|
||||||
Weekly,
|
Weekly,
|
||||||
Monthly,
|
Monthly,
|
||||||
Daily,
|
Daily,
|
||||||
|
RecentWeek,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 缺少可归属整号的额度窗口时,Provider 选择的本地用量范围
|
||||||
|
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub enum AccountUsageLookback {
|
||||||
|
#[default]
|
||||||
|
RollingDay,
|
||||||
|
RecentWeek,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AccountUsageLookback {
|
||||||
|
pub(crate) fn range(
|
||||||
|
self,
|
||||||
|
now: DateTime<Utc>,
|
||||||
|
timezone: gateway_core::time::DeploymentTimeZone,
|
||||||
|
) -> Result<super::observability::TimeRange, super::AdminModelError> {
|
||||||
|
use super::observability::{CalendarPeriod, TimeRange};
|
||||||
|
|
||||||
|
match self {
|
||||||
|
Self::RollingDay => Ok(TimeRange {
|
||||||
|
start: now - chrono::Duration::hours(24),
|
||||||
|
end: now,
|
||||||
|
}),
|
||||||
|
Self::RecentWeek => TimeRange::calendar_at(CalendarPeriod::SevenDays, now, timezone),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn period(self) -> AccountUsagePeriod {
|
||||||
|
match self {
|
||||||
|
Self::RollingDay => AccountUsagePeriod::Daily,
|
||||||
|
Self::RecentWeek => AccountUsagePeriod::RecentWeek,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Provider 解释 quota 所需的公共请求事实
|
/// Provider 解释 quota 所需的公共请求事实
|
||||||
@@ -1152,7 +1188,7 @@ impl ProviderQuota {
|
|||||||
fn quota_usage_priority(window: &ProviderQuotaWindow) -> (u8, u8) {
|
fn quota_usage_priority(window: &ProviderQuotaWindow) -> (u8, u8) {
|
||||||
let attribution = match window.local_usage_attribution {
|
let attribution = match window.local_usage_attribution {
|
||||||
QuotaLocalUsageAttribution::AccountWide => 0,
|
QuotaLocalUsageAttribution::AccountWide => 0,
|
||||||
QuotaLocalUsageAttribution::Unavailable => 1,
|
QuotaLocalUsageAttribution::Models(_) | QuotaLocalUsageAttribution::Unavailable => 1,
|
||||||
};
|
};
|
||||||
let duration = match window.group.as_str() {
|
let duration = match window.group.as_str() {
|
||||||
"shortTerm" if window.window_seconds.is_some_and(is_week_window) => 1,
|
"shortTerm" if window.window_seconds.is_some_and(is_week_window) => 1,
|
||||||
|
|||||||
@@ -152,6 +152,11 @@ struct ProviderAdminDiagnostic {
|
|||||||
/// 运行时资源通知只在事务成功后发生
|
/// 运行时资源通知只在事务成功后发生
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait ProviderAdmin: Send + Sync {
|
pub trait ProviderAdmin: Send + Sync {
|
||||||
|
/// 独立本地统计不借用模型分组额度的重置时间
|
||||||
|
fn account_usage_lookback(&self) -> crate::model::provider_credentials::AccountUsageLookback {
|
||||||
|
Default::default()
|
||||||
|
}
|
||||||
|
|
||||||
fn compile_privacy_policy(
|
fn compile_privacy_policy(
|
||||||
&self,
|
&self,
|
||||||
_policy: &gateway_core::settings::privacy::CodexPrivacyPolicy,
|
_policy: &gateway_core::settings::privacy::CodexPrivacyPolicy,
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ use std::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use chrono::{Duration, Utc};
|
use chrono::Utc;
|
||||||
use futures::StreamExt as _;
|
use futures::StreamExt as _;
|
||||||
use gateway_core::{
|
use gateway_core::{
|
||||||
account::ProviderAccountId,
|
account::ProviderAccountId,
|
||||||
@@ -30,11 +30,11 @@ use crate::{
|
|||||||
observability::TimeRange,
|
observability::TimeRange,
|
||||||
provider_credentials::{
|
provider_credentials::{
|
||||||
AccountDirectoryItem, AccountDirectoryPage, AccountExportBundle, AccountPersonalInfo,
|
AccountDirectoryItem, AccountDirectoryPage, AccountExportBundle, AccountPersonalInfo,
|
||||||
AccountRefreshResult, AccountUsagePeriod, ConsumeProviderResetCredit,
|
AccountRefreshResult, AccountUsageLookback, AccountUsagePeriod,
|
||||||
PrepareCredentialRefresh, ProviderModelCatalogDocument, ProviderModels,
|
ConsumeProviderResetCredit, PrepareCredentialRefresh, ProviderModelCatalogDocument,
|
||||||
ProviderProfileAvatar, ProviderQuota, ProviderQuotaReadRequest, ProviderQuotaRequest,
|
ProviderModels, ProviderProfileAvatar, ProviderQuota, ProviderQuotaReadRequest,
|
||||||
ProviderQuotaWindow, ProviderResetCreditResult, ProviderResetCredits,
|
ProviderQuotaRequest, ProviderQuotaWindow, ProviderResetCreditResult,
|
||||||
QuotaLocalUsageAttribution,
|
ProviderResetCredits, QuotaLocalUsageAttribution,
|
||||||
},
|
},
|
||||||
quota_forecast::{
|
quota_forecast::{
|
||||||
AccountQuotaForecastReport, account_quota_forecasts, quota_forecast_source_window,
|
AccountQuotaForecastReport, account_quota_forecasts, quota_forecast_source_window,
|
||||||
@@ -387,12 +387,11 @@ impl DefaultAccountsService {
|
|||||||
for (item, quota) in accounts.iter().zip(quotas) {
|
for (item, quota) in accounts.iter().zip(quotas) {
|
||||||
for window in &mut quota.windows {
|
for window in &mut quota.windows {
|
||||||
if window.local_usage.is_none()
|
if window.local_usage.is_none()
|
||||||
&& window.local_usage_attribution == QuotaLocalUsageAttribution::AccountWide
|
&& window.local_usage_attribution != QuotaLocalUsageAttribution::Unavailable
|
||||||
{
|
{
|
||||||
let key = (item.account.id.clone(), window.key.clone());
|
window.local_usage = usage_by_window
|
||||||
if let Some(usage) = usage_by_window.get(&key) {
|
.get(&(item.account.id.clone(), window.key.clone()))
|
||||||
window.local_usage = Some(usage.clone());
|
.cloned();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -426,6 +425,7 @@ impl DefaultAccountsService {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
Some(AccountUsageWindowQuery {
|
Some(AccountUsageWindowQuery {
|
||||||
|
models: None,
|
||||||
account_id: item.account.id.clone(),
|
account_id: item.account.id.clone(),
|
||||||
key: "account-lifetime".to_owned(),
|
key: "account-lifetime".to_owned(),
|
||||||
range: TimeRange {
|
range: TimeRange {
|
||||||
@@ -457,10 +457,10 @@ impl DefaultAccountsService {
|
|||||||
let (stored, provider) = self.provider_for_account(account_id).await?;
|
let (stored, provider) = self.provider_for_account(account_id).await?;
|
||||||
let account = &stored.account;
|
let account = &stored.account;
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
let rolling_range = TimeRange {
|
let lookback = provider.account_usage_lookback();
|
||||||
start: now - Duration::hours(24),
|
let rolling_range = lookback
|
||||||
end: now,
|
.range(now, self.timezone)
|
||||||
};
|
.map_err(|_| AdminError::internal("时间超出支持范围"))?;
|
||||||
let ids = vec![account.id.clone()];
|
let ids = vec![account.id.clone()];
|
||||||
let rolling_usage = self
|
let rolling_usage = self
|
||||||
.accounts
|
.accounts
|
||||||
@@ -510,6 +510,7 @@ impl DefaultAccountsService {
|
|||||||
"a,
|
"a,
|
||||||
rolling_usage,
|
rolling_usage,
|
||||||
api_key_usage,
|
api_key_usage,
|
||||||
|
lookback,
|
||||||
);
|
);
|
||||||
Ok(AccountDirectoryItem {
|
Ok(AccountDirectoryItem {
|
||||||
protection_rules: stored.protection_rules,
|
protection_rules: stored.protection_rules,
|
||||||
@@ -574,10 +575,6 @@ impl AccountsService for DefaultAccountsService {
|
|||||||
.await
|
.await
|
||||||
.map_err(|error| map_store_error(error, "account directory"))?;
|
.map_err(|error| map_store_error(error, "account directory"))?;
|
||||||
let now = Utc::now();
|
let now = Utc::now();
|
||||||
let rolling_range = TimeRange {
|
|
||||||
start: now - Duration::hours(24),
|
|
||||||
end: now,
|
|
||||||
};
|
|
||||||
let ids = page
|
let ids = page
|
||||||
.items
|
.items
|
||||||
.iter()
|
.iter()
|
||||||
@@ -595,15 +592,33 @@ impl AccountsService for DefaultAccountsService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let rolling_usage = self
|
let mut usage_groups = BTreeMap::<AccountUsageLookback, Vec<String>>::new();
|
||||||
.accounts
|
for item in &page.items {
|
||||||
.load_account_usage(rolling_range, &ids)
|
let lookback = providers
|
||||||
.await
|
.require(&item.account.provider_kind)
|
||||||
.map_err(|error| map_store_error(error, "rolling account usage"))?;
|
.map(|provider| provider.account_usage_lookback())
|
||||||
let mut rolling_usage = rolling_usage
|
.unwrap_or_default();
|
||||||
.into_iter()
|
usage_groups
|
||||||
.map(|usage| (usage.account_id.clone(), usage))
|
.entry(lookback)
|
||||||
.collect::<BTreeMap<_, _>>();
|
.or_default()
|
||||||
|
.push(item.account.id.clone());
|
||||||
|
}
|
||||||
|
let mut rolling_usage = BTreeMap::new();
|
||||||
|
for (lookback, ids) in usage_groups {
|
||||||
|
let range = lookback
|
||||||
|
.range(now, self.timezone)
|
||||||
|
.map_err(|_| AdminError::internal("时间超出支持范围"))?;
|
||||||
|
let usages = self
|
||||||
|
.accounts
|
||||||
|
.load_account_usage(range, &ids)
|
||||||
|
.await
|
||||||
|
.map_err(|error| map_store_error(error, "local account usage"))?;
|
||||||
|
rolling_usage.extend(
|
||||||
|
usages
|
||||||
|
.into_iter()
|
||||||
|
.map(|usage| (usage.account_id.clone(), usage)),
|
||||||
|
);
|
||||||
|
}
|
||||||
let mut quotas = self.read_quotas(&page.items, &rolling_usage).await;
|
let mut quotas = self.read_quotas(&page.items, &rolling_usage).await;
|
||||||
self.attach_quota_local_usage(&page.items, &mut quotas)
|
self.attach_quota_local_usage(&page.items, &mut quotas)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -615,10 +630,13 @@ impl AccountsService for DefaultAccountsService {
|
|||||||
.map(|(mut item, quota)| {
|
.map(|(mut item, quota)| {
|
||||||
let id = ProviderAccountId::new(item.account.id.clone())
|
let id = ProviderAccountId::new(item.account.id.clone())
|
||||||
.map_err(|_| AdminError::invalid("服务商账号 ID 不合法"))?;
|
.map_err(|_| AdminError::invalid("服务商账号 ID 不合法"))?;
|
||||||
let capabilities = providers
|
let (capabilities, lookback) = providers
|
||||||
.require(&item.account.provider_kind)
|
.require(&item.account.provider_kind)
|
||||||
.map(|provider| {
|
.map(|provider| {
|
||||||
provider.account_capabilities(&id, &item.account.authentication_kind)
|
(
|
||||||
|
provider.account_capabilities(&id, &item.account.authentication_kind),
|
||||||
|
provider.account_usage_lookback(),
|
||||||
|
)
|
||||||
})
|
})
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
let (usage, usage_period) = resolve_account_usage(
|
let (usage, usage_period) = resolve_account_usage(
|
||||||
@@ -626,6 +644,7 @@ impl AccountsService for DefaultAccountsService {
|
|||||||
"a,
|
"a,
|
||||||
rolling_usage.remove(&item.account.id),
|
rolling_usage.remove(&item.account.id),
|
||||||
api_key_usage.remove(&item.account.id),
|
api_key_usage.remove(&item.account.id),
|
||||||
|
lookback,
|
||||||
);
|
);
|
||||||
Ok(AccountDirectoryItem {
|
Ok(AccountDirectoryItem {
|
||||||
protection_rules: item.protection_rules,
|
protection_rules: item.protection_rules,
|
||||||
@@ -1348,6 +1367,7 @@ fn resolve_account_usage(
|
|||||||
quota: &ProviderQuota,
|
quota: &ProviderQuota,
|
||||||
rolling_usage: Option<AccountUsage>,
|
rolling_usage: Option<AccountUsage>,
|
||||||
api_key_usage: Option<AccountUsage>,
|
api_key_usage: Option<AccountUsage>,
|
||||||
|
lookback: AccountUsageLookback,
|
||||||
) -> (Option<AccountUsage>, Option<AccountUsagePeriod>) {
|
) -> (Option<AccountUsage>, Option<AccountUsagePeriod>) {
|
||||||
if authentication_kind == "api_key" {
|
if authentication_kind == "api_key" {
|
||||||
return (api_key_usage, None);
|
return (api_key_usage, None);
|
||||||
@@ -1356,7 +1376,7 @@ fn resolve_account_usage(
|
|||||||
return (window.local_usage.clone(), Some(period));
|
return (window.local_usage.clone(), Some(period));
|
||||||
}
|
}
|
||||||
// 模型分组额度无法归属整号用量,本地统计独立回退,不能为此合成上游额度桶
|
// 模型分组额度无法归属整号用量,本地统计独立回退,不能为此合成上游额度桶
|
||||||
(rolling_usage, Some(AccountUsagePeriod::Daily))
|
(rolling_usage, Some(lookback.period()))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn map_reset_credits_error_after_refresh(
|
fn map_reset_credits_error_after_refresh(
|
||||||
@@ -1377,13 +1397,16 @@ fn quota_usage_window(
|
|||||||
account_id: &str,
|
account_id: &str,
|
||||||
window: &ProviderQuotaWindow,
|
window: &ProviderQuotaWindow,
|
||||||
) -> Option<AccountUsageWindowQuery> {
|
) -> Option<AccountUsageWindowQuery> {
|
||||||
if window.local_usage_attribution != QuotaLocalUsageAttribution::AccountWide {
|
let models = match &window.local_usage_attribution {
|
||||||
return None;
|
QuotaLocalUsageAttribution::AccountWide => None,
|
||||||
}
|
QuotaLocalUsageAttribution::Models(ids) => Some(ids.clone()),
|
||||||
|
QuotaLocalUsageAttribution::Unavailable => return None,
|
||||||
|
};
|
||||||
let (start, reset_at) = window.observed_bounds()?;
|
let (start, reset_at) = window.observed_bounds()?;
|
||||||
let range = TimeRange::new(start, reset_at).ok()?;
|
let range = TimeRange::new(start, reset_at).ok()?;
|
||||||
// 上游百分比以该 reset 边界定义;以当前时间回推会让本地 Token 属于另一窗口
|
// 上游百分比以该 reset 边界定义;以当前时间回推会让本地 Token 属于另一窗口
|
||||||
Some(AccountUsageWindowQuery {
|
Some(AccountUsageWindowQuery {
|
||||||
|
models,
|
||||||
account_id: account_id.to_owned(),
|
account_id: account_id.to_owned(),
|
||||||
key: window.key.clone(),
|
key: window.key.clone(),
|
||||||
range,
|
range,
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ pub(super) type EventLog = Arc<Mutex<Vec<&'static str>>>;
|
|||||||
|
|
||||||
pub(super) struct FakeProviderAdmin {
|
pub(super) struct FakeProviderAdmin {
|
||||||
kind: ProviderKind,
|
kind: ProviderKind,
|
||||||
|
usage_lookback: Mutex<gateway_admin::model::provider_credentials::AccountUsageLookback>,
|
||||||
capabilities: Mutex<gateway_admin::model::accounts::ProviderAccountCapabilities>,
|
capabilities: Mutex<gateway_admin::model::accounts::ProviderAccountCapabilities>,
|
||||||
events: EventLog,
|
events: EventLog,
|
||||||
failure: Mutex<Option<ProviderAdminError>>,
|
failure: Mutex<Option<ProviderAdminError>>,
|
||||||
@@ -104,6 +105,7 @@ impl FakeProviderAdmin {
|
|||||||
pub(super) fn new(kind: &str, events: EventLog) -> Arc<Self> {
|
pub(super) fn new(kind: &str, events: EventLog) -> Arc<Self> {
|
||||||
Arc::new(Self {
|
Arc::new(Self {
|
||||||
kind: ProviderKind::new(kind).expect("provider kind"),
|
kind: ProviderKind::new(kind).expect("provider kind"),
|
||||||
|
usage_lookback: Mutex::default(),
|
||||||
capabilities: Mutex::default(),
|
capabilities: Mutex::default(),
|
||||||
events,
|
events,
|
||||||
failure: Mutex::new(None),
|
failure: Mutex::new(None),
|
||||||
@@ -281,6 +283,12 @@ impl FakeProviderAdmin {
|
|||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl ProviderAdmin for FakeProviderAdmin {
|
impl ProviderAdmin for FakeProviderAdmin {
|
||||||
|
fn account_usage_lookback(
|
||||||
|
&self,
|
||||||
|
) -> gateway_admin::model::provider_credentials::AccountUsageLookback {
|
||||||
|
*self.usage_lookback.lock().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
fn peer_authentication_kinds(&self) -> &[&str] {
|
fn peer_authentication_kinds(&self) -> &[&str] {
|
||||||
&["api_key"]
|
&["api_key"]
|
||||||
}
|
}
|
||||||
@@ -618,6 +626,7 @@ pub(super) struct FakeAccountStore {
|
|||||||
import_settings: Mutex<Vec<Option<gateway_admin::model::accounts::AccountImportSettings>>>,
|
import_settings: Mutex<Vec<Option<gateway_admin::model::accounts::AccountImportSettings>>>,
|
||||||
quota_window_usage: Mutex<Vec<AccountUsageWindowResult>>,
|
quota_window_usage: Mutex<Vec<AccountUsageWindowResult>>,
|
||||||
rolling_usage: Mutex<Vec<AccountUsage>>,
|
rolling_usage: Mutex<Vec<AccountUsage>>,
|
||||||
|
usage_queries: Mutex<Vec<(TimeRange, Vec<String>)>>,
|
||||||
quota_window_queries: Mutex<Vec<AccountUsageWindowQuery>>,
|
quota_window_queries: Mutex<Vec<AccountUsageWindowQuery>>,
|
||||||
quota_forecast_history: Mutex<QuotaForecastHistory>,
|
quota_forecast_history: Mutex<QuotaForecastHistory>,
|
||||||
update_commands: Mutex<Vec<UpdateAccount>>,
|
update_commands: Mutex<Vec<UpdateAccount>>,
|
||||||
@@ -642,6 +651,7 @@ impl FakeAccountStore {
|
|||||||
import_settings: Mutex::new(Vec::new()),
|
import_settings: Mutex::new(Vec::new()),
|
||||||
quota_window_usage: Mutex::new(Vec::new()),
|
quota_window_usage: Mutex::new(Vec::new()),
|
||||||
rolling_usage: Mutex::new(Vec::new()),
|
rolling_usage: Mutex::new(Vec::new()),
|
||||||
|
usage_queries: Mutex::default(),
|
||||||
quota_window_queries: Mutex::new(Vec::new()),
|
quota_window_queries: Mutex::new(Vec::new()),
|
||||||
quota_forecast_history: Mutex::new(QuotaForecastHistory::default()),
|
quota_forecast_history: Mutex::new(QuotaForecastHistory::default()),
|
||||||
update_commands: Mutex::new(Vec::new()),
|
update_commands: Mutex::new(Vec::new()),
|
||||||
@@ -827,10 +837,21 @@ impl AccountStore for FakeAccountStore {
|
|||||||
|
|
||||||
async fn load_account_usage(
|
async fn load_account_usage(
|
||||||
&self,
|
&self,
|
||||||
_: TimeRange,
|
range: TimeRange,
|
||||||
_: &[String],
|
ids: &[String],
|
||||||
) -> AdminStoreResult<Vec<AccountUsage>> {
|
) -> AdminStoreResult<Vec<AccountUsage>> {
|
||||||
Ok(self.rolling_usage.lock().unwrap().clone())
|
self.usage_queries
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.push((range, ids.to_vec()));
|
||||||
|
Ok(self
|
||||||
|
.rolling_usage
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.iter()
|
||||||
|
.filter(|usage| ids.contains(&usage.account_id))
|
||||||
|
.cloned()
|
||||||
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn load_account_usage_by_windows(
|
async fn load_account_usage_by_windows(
|
||||||
@@ -3001,14 +3022,25 @@ async fn api_key_list_and_detail_should_accumulate_local_usage_without_subscript
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn accounts_list_and_detail_keep_rolling_usage_separate_from_group_quotas() {
|
async fn accounts_list_and_detail_keep_recent_week_usage_separate_from_group_quotas() {
|
||||||
use gateway_admin::model::provider_credentials::AccountUsagePeriod;
|
use gateway_admin::model::provider_credentials::{AccountUsageLookback, AccountUsagePeriod};
|
||||||
|
|
||||||
let provider = FakeProviderAdmin::new("antigravity", events());
|
let provider = FakeProviderAdmin::new("antigravity", events());
|
||||||
|
*provider.usage_lookback.lock().unwrap() = AccountUsageLookback::RecentWeek;
|
||||||
let store = FakeAccountStore::new("antigravity", events());
|
let store = FakeAccountStore::new("antigravity", events());
|
||||||
let expected_usage = quota_local_usage("acct_test", 139);
|
let expected_usage = quota_local_usage("acct_test", 139);
|
||||||
*store.rolling_usage.lock().unwrap() = vec![expected_usage.clone()];
|
let mut daily_account = account_record("xai");
|
||||||
let services = accounts_service(provider.clone(), store.clone()).await;
|
daily_account.id = "acct_daily".to_owned();
|
||||||
|
store.accounts.lock().unwrap().push(daily_account);
|
||||||
|
let daily_usage = quota_local_usage("acct_daily", 23);
|
||||||
|
*store.rolling_usage.lock().unwrap() = vec![expected_usage.clone(), daily_usage.clone()];
|
||||||
|
let services = super::AdminHarness::new()
|
||||||
|
.accounts(store.clone())
|
||||||
|
.settings(Arc::new(StaticSettingsStore::default()))
|
||||||
|
.provider(provider.clone())
|
||||||
|
.provider(FakeProviderAdmin::new("xai", events()))
|
||||||
|
.build()
|
||||||
|
.await;
|
||||||
let grouped_window = ProviderQuotaWindow {
|
let grouped_window = ProviderQuotaWindow {
|
||||||
upstream: None,
|
upstream: None,
|
||||||
key: "gemini-weekly".to_owned(),
|
key: "gemini-weekly".to_owned(),
|
||||||
@@ -3048,12 +3080,38 @@ async fn accounts_list_and_detail_keep_rolling_usage_separate_from_group_quotas(
|
|||||||
.quota(&ProviderAccountId::new("acct_test").unwrap(), false)
|
.quota(&ProviderAccountId::new("acct_test").unwrap(), false)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
for item in [&page.items[0], &detail] {
|
let refreshed = services
|
||||||
|
.accounts()
|
||||||
|
.quota(&ProviderAccountId::new("acct_test").unwrap(), true)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
for item in [&page.items[0], &detail, &refreshed] {
|
||||||
assert_eq!(item.quota.windows, windows);
|
assert_eq!(item.quota.windows, windows);
|
||||||
assert_eq!(item.usage.as_ref(), Some(&expected_usage));
|
assert_eq!(item.usage.as_ref(), Some(&expected_usage));
|
||||||
assert_eq!(item.usage_period, Some(AccountUsagePeriod::Daily));
|
assert_eq!(item.usage_period, Some(AccountUsagePeriod::RecentWeek));
|
||||||
}
|
}
|
||||||
assert!(store.quota_window_queries().is_empty());
|
assert!(store.quota_window_queries().is_empty());
|
||||||
|
let daily = page
|
||||||
|
.items
|
||||||
|
.iter()
|
||||||
|
.find(|item| item.account.id == "acct_daily")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(daily.usage.as_ref(), Some(&daily_usage));
|
||||||
|
assert_eq!(daily.usage_period, Some(AccountUsagePeriod::Daily));
|
||||||
|
let queries = std::mem::take(&mut *store.usage_queries.lock().unwrap());
|
||||||
|
assert_eq!(queries.len(), 4);
|
||||||
|
assert_eq!(queries[0].0.end, queries[1].0.end);
|
||||||
|
for (range, ids) in queries {
|
||||||
|
if ids == ["acct_daily"] {
|
||||||
|
assert_eq!(range.end - range.start, TimeDelta::hours(24));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
assert_eq!(ids, ["acct_test"]);
|
||||||
|
let timezone = gateway_core::time::DeploymentTimeZone::default();
|
||||||
|
assert_eq!(range.start, timezone.days_before(range.end, 6).unwrap());
|
||||||
|
assert!(range.end - range.start >= TimeDelta::days(6));
|
||||||
|
assert!(range.end - range.start < TimeDelta::days(7));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3223,10 +3281,10 @@ async fn accounts_list_and_quota_refresh_should_select_the_same_weekly_or_monthl
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_windows() {
|
async fn account_windows_attach_only_the_usage_allowed_by_the_provider() {
|
||||||
let provider = FakeProviderAdmin::new("openai", events());
|
let provider = FakeProviderAdmin::new("openai", events());
|
||||||
let reset_at = Utc::now() + TimeDelta::days(7);
|
let reset_at = Utc::now() + TimeDelta::days(7);
|
||||||
provider.set_quota(ProviderQuota {
|
let mut quota = ProviderQuota {
|
||||||
paused_windows: Vec::new(),
|
paused_windows: Vec::new(),
|
||||||
upstream: None,
|
upstream: None,
|
||||||
credits: None,
|
credits: None,
|
||||||
@@ -3269,7 +3327,13 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
|
|||||||
],
|
],
|
||||||
limit_reached: false,
|
limit_reached: false,
|
||||||
provider_data: None,
|
provider_data: None,
|
||||||
});
|
};
|
||||||
|
let ids = std::collections::BTreeSet::from(["model-in-group".to_owned()]);
|
||||||
|
let mut grouped = quota.windows[1].clone();
|
||||||
|
grouped.key = "known-group".to_owned();
|
||||||
|
grouped.local_usage_attribution = QuotaLocalUsageAttribution::Models(ids.clone());
|
||||||
|
quota.windows.push(grouped);
|
||||||
|
provider.set_quota(quota);
|
||||||
let store = FakeAccountStore::new("openai", events());
|
let store = FakeAccountStore::new("openai", events());
|
||||||
store.set_quota_window_usage(vec![
|
store.set_quota_window_usage(vec![
|
||||||
AccountUsageWindowResult {
|
AccountUsageWindowResult {
|
||||||
@@ -3282,9 +3346,14 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
|
|||||||
key: "codex-bengalfox-primary".to_owned(),
|
key: "codex-bengalfox-primary".to_owned(),
|
||||||
usage: quota_local_usage("acct_test", 127_926),
|
usage: quota_local_usage("acct_test", 127_926),
|
||||||
},
|
},
|
||||||
|
AccountUsageWindowResult {
|
||||||
|
account_id: "acct_test".to_owned(),
|
||||||
|
key: "known-group".to_owned(),
|
||||||
|
usage: quota_local_usage("acct_test", 85),
|
||||||
|
},
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let page = accounts_service(provider, store)
|
let page = accounts_service(provider, store.clone())
|
||||||
.await
|
.await
|
||||||
.accounts()
|
.accounts()
|
||||||
.list(AccountListQuery {
|
.list(AccountListQuery {
|
||||||
@@ -3318,6 +3387,7 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
|
|||||||
[
|
[
|
||||||
("core-primary", Some(12_818_806)),
|
("core-primary", Some(12_818_806)),
|
||||||
("codex-bengalfox-primary", None),
|
("codex-bengalfox-primary", None),
|
||||||
|
("known-group", Some(85)),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -3327,6 +3397,10 @@ async fn accounts_list_should_not_attach_account_usage_to_model_specific_quota_w
|
|||||||
.and_then(|usage| usage.total_tokens),
|
.and_then(|usage| usage.total_tokens),
|
||||||
Some(12_818_806),
|
Some(12_818_806),
|
||||||
);
|
);
|
||||||
|
let queries = store.quota_window_queries();
|
||||||
|
assert_eq!(queries.len(), 2);
|
||||||
|
assert_eq!(queries[0].models, None);
|
||||||
|
assert_eq!(queries[1].models.as_ref(), Some(&ids));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -191,6 +191,7 @@ fn quota_forecast_view(
|
|||||||
AccountUsagePeriod::Weekly => "weekly",
|
AccountUsagePeriod::Weekly => "weekly",
|
||||||
AccountUsagePeriod::Monthly => "monthly",
|
AccountUsagePeriod::Monthly => "monthly",
|
||||||
AccountUsagePeriod::Daily => "daily",
|
AccountUsagePeriod::Daily => "daily",
|
||||||
|
AccountUsagePeriod::RecentWeek => "recent_week",
|
||||||
},
|
},
|
||||||
target_days: forecast.target_seconds as f64 / 86_400.0,
|
target_days: forecast.target_seconds as f64 / 86_400.0,
|
||||||
extrapolated: forecast.extrapolated,
|
extrapolated: forecast.extrapolated,
|
||||||
@@ -374,8 +375,18 @@ pub(super) fn account_usage_view(
|
|||||||
now: DateTime<Utc>,
|
now: DateTime<Utc>,
|
||||||
time: crate::time::TimePresenter,
|
time: crate::time::TimePresenter,
|
||||||
) -> AccountUsageView {
|
) -> AccountUsageView {
|
||||||
|
let window_kind = match period {
|
||||||
|
Some(AccountUsagePeriod::Daily) => AccountUsageWindowKind::Daily,
|
||||||
|
Some(AccountUsagePeriod::RecentWeek) => AccountUsageWindowKind::RecentWeek,
|
||||||
|
Some(AccountUsagePeriod::Weekly) => AccountUsageWindowKind::Weekly,
|
||||||
|
Some(AccountUsagePeriod::Monthly) => AccountUsageWindowKind::Monthly,
|
||||||
|
None => AccountUsageWindowKind::Quota,
|
||||||
|
};
|
||||||
let Some(usage) = usage else {
|
let Some(usage) = usage else {
|
||||||
return empty_account_usage();
|
return AccountUsageView {
|
||||||
|
window_kind,
|
||||||
|
..empty_account_usage()
|
||||||
|
};
|
||||||
};
|
};
|
||||||
let known_count = usage
|
let known_count = usage
|
||||||
.cost_coverage
|
.cost_coverage
|
||||||
@@ -389,12 +400,7 @@ pub(super) fn account_usage_view(
|
|||||||
"known"
|
"known"
|
||||||
};
|
};
|
||||||
AccountUsageView {
|
AccountUsageView {
|
||||||
window_kind: match period {
|
window_kind,
|
||||||
Some(AccountUsagePeriod::Daily) => AccountUsageWindowKind::Daily,
|
|
||||||
Some(AccountUsagePeriod::Weekly) => AccountUsageWindowKind::Weekly,
|
|
||||||
Some(AccountUsagePeriod::Monthly) => AccountUsageWindowKind::Monthly,
|
|
||||||
None => AccountUsageWindowKind::Quota,
|
|
||||||
},
|
|
||||||
request_count: Some(usage.request_count),
|
request_count: Some(usage.request_count),
|
||||||
request_count_display: format_number(usage.request_count),
|
request_count_display: format_number(usage.request_count),
|
||||||
input_tokens: usage.input_tokens,
|
input_tokens: usage.input_tokens,
|
||||||
|
|||||||
@@ -437,6 +437,7 @@ pub struct AccountQuotaWindowView {
|
|||||||
pub enum AccountUsageWindowKind {
|
pub enum AccountUsageWindowKind {
|
||||||
General,
|
General,
|
||||||
Daily,
|
Daily,
|
||||||
|
RecentWeek,
|
||||||
Weekly,
|
Weekly,
|
||||||
Monthly,
|
Monthly,
|
||||||
Quota,
|
Quota,
|
||||||
|
|||||||
@@ -159,7 +159,6 @@ async fn model_responses(
|
|||||||
middleware_body,
|
middleware_body,
|
||||||
},
|
},
|
||||||
Some(authorization),
|
Some(authorization),
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
Ok(plugin_response(response))
|
Ok(plugin_response(response))
|
||||||
|
|||||||
@@ -118,13 +118,16 @@ pub(crate) fn capacity_error_for_client(data: &Value) -> Option<Value> {
|
|||||||
/// Gateway 错误的 OpenAI HTTP 表达
|
/// Gateway 错误的 OpenAI HTTP 表达
|
||||||
pub fn gateway_error_response(error: &GatewayError) -> Response {
|
pub fn gateway_error_response(error: &GatewayError) -> Response {
|
||||||
let (status, default_type, default_code) = gateway_error_contract(error.kind());
|
let (status, default_type, default_code) = gateway_error_contract(error.kind());
|
||||||
let mut response = openai_error_response(
|
let (status, Json(mut body)) = openai_error_response(
|
||||||
status,
|
status,
|
||||||
error.client_message(),
|
error.client_message(),
|
||||||
error.client_error_type().unwrap_or(default_type),
|
error.client_error_type().unwrap_or(default_type),
|
||||||
error.client_error_code().unwrap_or(default_code),
|
error.client_error_code().unwrap_or(default_code),
|
||||||
)
|
);
|
||||||
.into_response();
|
if let Some(parameter) = error.client_error_parameter() {
|
||||||
|
body["error"]["param"] = parameter.into();
|
||||||
|
}
|
||||||
|
let mut response = (status, Json(body)).into_response();
|
||||||
response.extensions_mut().insert(error.clone());
|
response.extensions_mut().insert(error.clone());
|
||||||
if let Some(delay) = error.retry_after()
|
if let Some(delay) = error.retry_after()
|
||||||
&& let Ok(value) = HeaderValue::from_str(
|
&& let Ok(value) = HeaderValue::from_str(
|
||||||
|
|||||||
@@ -104,8 +104,9 @@ pub(crate) async fn authenticate_client(
|
|||||||
pub(crate) async fn verify_client(
|
pub(crate) async fn verify_client(
|
||||||
service: &DataPlaneService,
|
service: &DataPlaneService,
|
||||||
headers: &HeaderMap,
|
headers: &HeaderMap,
|
||||||
|
accepted: ClientKeyHeaders,
|
||||||
) -> Result<AuthenticatedClient, ClientApiKeyAuthError> {
|
) -> Result<AuthenticatedClient, ClientApiKeyAuthError> {
|
||||||
let request = client_authentication_request(headers, ClientKeyHeaders::Bearer)?;
|
let request = client_authentication_request(headers, accepted)?;
|
||||||
service.verify(request).await
|
service.verify(request).await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,6 +115,7 @@ pub(crate) async fn verify_client(
|
|||||||
pub(crate) enum ClientKeyHeaders {
|
pub(crate) enum ClientKeyHeaders {
|
||||||
Bearer,
|
Bearer,
|
||||||
Anthropic,
|
Anthropic,
|
||||||
|
GenAi,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn client_authentication_request(
|
fn client_authentication_request(
|
||||||
@@ -125,16 +127,20 @@ fn client_authentication_request(
|
|||||||
.to_str()
|
.to_str()
|
||||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?
|
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?
|
||||||
.to_owned()
|
.to_owned()
|
||||||
} else if matches!(accepted, ClientKeyHeaders::Anthropic)
|
} else {
|
||||||
&& let Some(key) = headers.get("x-api-key")
|
let header = match accepted {
|
||||||
{
|
ClientKeyHeaders::Bearer => None,
|
||||||
|
ClientKeyHeaders::Anthropic => Some("x-api-key"),
|
||||||
|
ClientKeyHeaders::GenAi => Some("x-goog-api-key"),
|
||||||
|
};
|
||||||
|
let key = header
|
||||||
|
.and_then(|name| headers.get(name))
|
||||||
|
.ok_or(ClientApiKeyAuthError::MissingAuthorization)?;
|
||||||
format!(
|
format!(
|
||||||
"Bearer {}",
|
"Bearer {}",
|
||||||
key.to_str()
|
key.to_str()
|
||||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?
|
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?
|
||||||
)
|
)
|
||||||
} else {
|
|
||||||
return Err(ClientApiKeyAuthError::MissingAuthorization);
|
|
||||||
};
|
};
|
||||||
let request = ClientAuthenticationRequest::new(raw)
|
let request = ClientAuthenticationRequest::new(raw)
|
||||||
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?;
|
.map_err(|_| ClientApiKeyAuthError::MalformedAuthorization)?;
|
||||||
|
|||||||
@@ -8,6 +8,9 @@ use thiserror::Error;
|
|||||||
/// 请求解码错误
|
/// 请求解码错误
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||||
pub enum RequestDecodeError {
|
pub enum RequestDecodeError {
|
||||||
|
/// Chat 的入口校验与目标转换复用同一错误合同
|
||||||
|
#[error(transparent)]
|
||||||
|
Chat(#[from] gateway_protocol::chat_completions::ChatError),
|
||||||
/// 请求不是合法 JSON
|
/// 请求不是合法 JSON
|
||||||
#[error("request body must be valid JSON")]
|
#[error("request body must be valid JSON")]
|
||||||
MalformedJson,
|
MalformedJson,
|
||||||
@@ -52,12 +55,6 @@ pub enum RequestDecodeError {
|
|||||||
/// 字段路径;不保存原始值
|
/// 字段路径;不保存原始值
|
||||||
field: String,
|
field: String,
|
||||||
},
|
},
|
||||||
/// 未知字段
|
|
||||||
#[error("unknown field `{field}`")]
|
|
||||||
UnknownField {
|
|
||||||
/// 字段路径;不保存字段值
|
|
||||||
field: String,
|
|
||||||
},
|
|
||||||
/// 已知但尚未实现的语义
|
/// 已知但尚未实现的语义
|
||||||
#[error("field `{field}` is not supported by this gateway")]
|
#[error("field `{field}` is not supported by this gateway")]
|
||||||
UnsupportedField {
|
UnsupportedField {
|
||||||
@@ -85,6 +82,11 @@ impl RequestDecodeError {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn protocol_body(&self) -> ProtocolErrorBody {
|
pub fn protocol_body(&self) -> ProtocolErrorBody {
|
||||||
let (code, message, param) = match self {
|
let (code, message, param) = match self {
|
||||||
|
Self::Chat(error) => (
|
||||||
|
error.code(),
|
||||||
|
error.to_string(),
|
||||||
|
error.parameter().map(str::to_owned),
|
||||||
|
),
|
||||||
Self::MalformedJson => (
|
Self::MalformedJson => (
|
||||||
"invalid_json",
|
"invalid_json",
|
||||||
"Request body must be valid JSON.".to_owned(),
|
"Request body must be valid JSON.".to_owned(),
|
||||||
@@ -127,11 +129,6 @@ impl RequestDecodeError {
|
|||||||
format!("Parameter `{field}` has an invalid value."),
|
format!("Parameter `{field}` has an invalid value."),
|
||||||
Some(field.clone()),
|
Some(field.clone()),
|
||||||
),
|
),
|
||||||
Self::UnknownField { field } => (
|
|
||||||
"unknown_parameter",
|
|
||||||
format!("Unknown parameter `{field}`."),
|
|
||||||
Some(field.clone()),
|
|
||||||
),
|
|
||||||
Self::UnsupportedField { field } => (
|
Self::UnsupportedField { field } => (
|
||||||
"unsupported_parameter",
|
"unsupported_parameter",
|
||||||
format!("Parameter `{field}` is not supported by this gateway."),
|
format!("Parameter `{field}` is not supported by this gateway."),
|
||||||
|
|||||||
@@ -1,320 +1,158 @@
|
|||||||
//! Chat 出口持有协议投影缓冲 提交与资源回收始终委托原受管正文
|
//! Chat 出口只编码已转换的错误,不另建正文或提交状态机
|
||||||
|
|
||||||
use std::collections::VecDeque;
|
|
||||||
|
|
||||||
use axum::body::to_bytes;
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures::future::BoxFuture;
|
use gateway_core::event::{GatewayEvent, ProviderEvent};
|
||||||
use gateway_core::{
|
use gateway_protocol::openai::sse::{parse_sse_events, sse_frame_is_done};
|
||||||
engine::middleware::{
|
|
||||||
MiddlewareBody, MiddlewareError, MiddlewareFrame, MiddlewareFraming, MiddlewareHeader,
|
|
||||||
MiddlewareResponse,
|
|
||||||
},
|
|
||||||
error::{GatewayError, GatewayErrorKind},
|
|
||||||
};
|
|
||||||
use gateway_protocol::openai::sse::{DONE_SSE_FRAME, SseEvent, SseEventDecoder, sse_frame_is_done};
|
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::client_error::ProtocolErrorBody;
|
pub(in crate::data_plane) fn chat_error_frame(data: &Value) -> Bytes {
|
||||||
use crate::data_plane::middleware::error_response;
|
|
||||||
|
|
||||||
use super::response::{ChatIdentity, ChatStreamEncoder, project_response};
|
|
||||||
|
|
||||||
pub(super) fn project_middleware_response(
|
|
||||||
response: MiddlewareResponse,
|
|
||||||
identity: ChatIdentity,
|
|
||||||
streaming: bool,
|
|
||||||
include_usage: bool,
|
|
||||||
) -> MiddlewareResponse {
|
|
||||||
if !(200..300).contains(&response.status_code()) {
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
let (protocol, status, mut headers, body, envelope) = response.into_parts();
|
|
||||||
// 投影改变正文长度和表示形式 不继承 Responses 的实体长度或编码
|
|
||||||
headers.retain(|header| {
|
|
||||||
!["content-length", "content-type", "content-encoding"]
|
|
||||||
.iter()
|
|
||||||
.any(|name| header.name().eq_ignore_ascii_case(name))
|
|
||||||
});
|
|
||||||
headers.push(MiddlewareHeader::new(
|
|
||||||
"content-type",
|
|
||||||
Bytes::from_static(if streaming {
|
|
||||||
b"text/event-stream"
|
|
||||||
} else {
|
|
||||||
b"application/json"
|
|
||||||
}),
|
|
||||||
));
|
|
||||||
let projection = if streaming {
|
|
||||||
Projection::Stream(Box::new(StreamProjection {
|
|
||||||
encoder: ChatStreamEncoder::new(identity, include_usage),
|
|
||||||
decoder: SseEventDecoder::default(),
|
|
||||||
done_received: false,
|
|
||||||
}))
|
|
||||||
} else {
|
|
||||||
Projection::Json(identity)
|
|
||||||
};
|
|
||||||
let mut response = MiddlewareResponse::new(
|
|
||||||
protocol,
|
|
||||||
status,
|
|
||||||
headers,
|
|
||||||
Box::new(ChatBody {
|
|
||||||
inner: Some(body),
|
|
||||||
projection,
|
|
||||||
pending: VecDeque::new(),
|
|
||||||
committed: false,
|
|
||||||
finished: false,
|
|
||||||
}),
|
|
||||||
);
|
|
||||||
if let Some(envelope) = envelope {
|
|
||||||
response = response.with_envelope(envelope);
|
|
||||||
}
|
|
||||||
response
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn chat_error_frame(data: &Value) -> Bytes {
|
|
||||||
let error = data
|
let error = data
|
||||||
.pointer("/response/error")
|
.pointer("/response/error")
|
||||||
.or_else(|| data.get("error"));
|
.or_else(|| data.get("error"))
|
||||||
|
.unwrap_or(data);
|
||||||
Bytes::from(format!("data: {}\n\n", serde_json::json!({"error": error})))
|
Bytes::from(format!("data: {}\n\n", serde_json::json!({"error": error})))
|
||||||
}
|
}
|
||||||
|
|
||||||
enum Projection {
|
pub(in crate::data_plane) fn validate_response(bytes: &[u8]) -> Result<(), ()> {
|
||||||
Json(ChatIdentity),
|
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||||
Stream(Box<StreamProjection>),
|
if value.get("object").and_then(Value::as_str) != Some("chat.completion")
|
||||||
}
|
|| value.get("id").and_then(Value::as_str).is_none()
|
||||||
|
|| !value
|
||||||
impl Projection {
|
.get("choices")
|
||||||
fn terminal_seen(&self) -> bool {
|
.and_then(Value::as_array)
|
||||||
matches!(self, Self::Stream(stream) if stream.terminal_seen())
|
.is_some_and(|choices| {
|
||||||
|
choices.len() == 1
|
||||||
|
&& choices[0].get("message").is_some_and(Value::is_object)
|
||||||
|
&& choices[0]
|
||||||
|
.get("finish_reason")
|
||||||
|
.is_some_and(Value::is_string)
|
||||||
|
})
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
struct StreamProjection {
|
/// finish 与 usage 必须随原生 Completed 交付,避免终结失败后已向客户端报成功
|
||||||
encoder: ChatStreamEncoder,
|
#[derive(Default)]
|
||||||
decoder: SseEventDecoder,
|
pub(in crate::data_plane) struct ChatEncoder {
|
||||||
done_received: bool,
|
terminal: Vec<Bytes>,
|
||||||
|
pub(in crate::data_plane) completed: bool,
|
||||||
|
pub(in crate::data_plane) failed: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StreamProjection {
|
impl ChatEncoder {
|
||||||
fn terminal_seen(&self) -> bool {
|
pub(in crate::data_plane) fn push(&mut self, event: &ProviderEvent) -> Vec<Bytes> {
|
||||||
self.encoder.is_completed() || self.encoder.has_wire_failure()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn project(&mut self, events: Vec<SseEvent>) -> Result<Vec<Bytes>, MiddlewareError> {
|
|
||||||
let mut output = Vec::new();
|
let mut output = Vec::new();
|
||||||
for event in events {
|
if let Some(wire) = event
|
||||||
if self.done_received {
|
.wire_event()
|
||||||
return Err(invalid_response());
|
.filter(|wire| wire.protocol() == gateway_protocol::chat_completions::CHAT_PROTOCOL)
|
||||||
}
|
|
||||||
let data = serde_json::from_str(&event.data).map_err(|_| invalid_response())?;
|
|
||||||
// codec 区分辅助事件与终态后的业务输出 交付层不再维护一份事件分类
|
|
||||||
output.extend(
|
|
||||||
self.encoder
|
|
||||||
.push_event(event.event.as_deref(), &data)
|
|
||||||
.map_err(projection_error)?,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok(output)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct ChatBody {
|
|
||||||
inner: Option<Box<dyn MiddlewareBody>>,
|
|
||||||
projection: Projection,
|
|
||||||
pending: VecDeque<MiddlewareFrame>,
|
|
||||||
committed: bool,
|
|
||||||
finished: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ChatBody {
|
|
||||||
async fn read_one(&mut self) -> Result<(), MiddlewareError> {
|
|
||||||
let inner = self.inner.as_mut().ok_or(MiddlewareError::InvalidState)?;
|
|
||||||
let Some(frame) = inner.next_frame().await? else {
|
|
||||||
if let Projection::Stream(stream) = &mut self.projection {
|
|
||||||
let events = stream.decoder.finish().map_err(|_| invalid_response())?;
|
|
||||||
let frames = stream.project(events)?;
|
|
||||||
if !frames.is_empty() || !stream.done_received || !inner.is_finalized() {
|
|
||||||
return Err(invalid_response());
|
|
||||||
}
|
|
||||||
self.pending.push_back(done_frame());
|
|
||||||
}
|
|
||||||
self.finished = true;
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
let transformed = frame.transformed();
|
|
||||||
let (bytes, framing, terminal, envelope) = frame.into_parts();
|
|
||||||
let output = match &mut self.projection {
|
|
||||||
Projection::Json(identity) => {
|
|
||||||
if framing != MiddlewareFraming::JsonDocument || !terminal {
|
|
||||||
return Err(invalid_response());
|
|
||||||
}
|
|
||||||
let value = serde_json::from_slice(&bytes).map_err(|_| invalid_response())?;
|
|
||||||
let value = project_response(&value, identity).map_err(projection_error)?;
|
|
||||||
vec![MiddlewareFrame::new(
|
|
||||||
Bytes::from(serde_json::to_vec(&value).map_err(|_| invalid_response())?),
|
|
||||||
MiddlewareFraming::JsonDocument,
|
|
||||||
true,
|
|
||||||
)]
|
|
||||||
}
|
|
||||||
Projection::Stream(stream) => {
|
|
||||||
if framing != MiddlewareFraming::SseEvent {
|
|
||||||
return Err(invalid_response());
|
|
||||||
}
|
|
||||||
let events = stream
|
|
||||||
.decoder
|
|
||||||
.push(&bytes)
|
|
||||||
.map_err(|_| invalid_response())?;
|
|
||||||
let output = stream.project(events)?;
|
|
||||||
// 共用 SSE 解码器只返回业务事件 DONE 由受管正文的控制帧单独确认
|
|
||||||
if std::str::from_utf8(&bytes).is_ok_and(sse_frame_is_done) {
|
|
||||||
if stream.done_received || !stream.terminal_seen() {
|
|
||||||
return Err(invalid_response());
|
|
||||||
}
|
|
||||||
stream.done_received = true;
|
|
||||||
}
|
|
||||||
if terminal && !stream.done_received {
|
|
||||||
return Err(invalid_response());
|
|
||||||
}
|
|
||||||
output
|
|
||||||
.into_iter()
|
|
||||||
.map(|bytes| MiddlewareFrame::new(bytes, MiddlewareFraming::SseEvent, false))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let mut output: VecDeque<_> = output
|
|
||||||
.into_iter()
|
|
||||||
.map(|frame| frame.with_transformed(transformed))
|
|
||||||
.collect();
|
|
||||||
if let Some(envelope) = envelope
|
|
||||||
&& let Some(last) = output.pop_back()
|
|
||||||
{
|
{
|
||||||
output.push_back(last.with_envelope(envelope));
|
self.failed |= wire.data().get("error").is_some_and(Value::is_object);
|
||||||
}
|
let bytes = wire.raw_sse_frame().cloned().or_else(|| {
|
||||||
self.pending.extend(output);
|
wire.has_json_data()
|
||||||
Ok(())
|
.then(|| Bytes::from(format!("data: {}\n\n", wire.data())))
|
||||||
}
|
});
|
||||||
|
if let Some(bytes) = bytes {
|
||||||
async fn verify_terminal(&mut self) -> Result<(), MiddlewareError> {
|
if wire
|
||||||
while !self.finished {
|
.data()
|
||||||
self.read_one().await?;
|
.pointer("/choices/0/finish_reason")
|
||||||
}
|
.is_some_and(Value::is_string)
|
||||||
Ok(())
|
|| wire
|
||||||
}
|
.data()
|
||||||
|
.get("choices")
|
||||||
async fn fail_stream(&mut self, error: MiddlewareError) {
|
.and_then(Value::as_array)
|
||||||
self.pending.clear();
|
.is_some_and(Vec::is_empty)
|
||||||
if let Some(inner) = self.inner.take() {
|
{
|
||||||
inner.close().await;
|
self.terminal.push(bytes);
|
||||||
}
|
} else {
|
||||||
let response = error_response(error);
|
output.push(bytes);
|
||||||
let bytes = to_bytes(response.into_body(), usize::MAX)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default();
|
|
||||||
let value = serde_json::from_slice(&bytes).unwrap_or_else(|_| {
|
|
||||||
serde_json::json!({"error": {
|
|
||||||
"type": "server_error", "code": "invalid_upstream_response",
|
|
||||||
"message": "The gateway could not deliver the Chat response."
|
|
||||||
}})
|
|
||||||
});
|
|
||||||
self.pending.push_back(MiddlewareFrame::new(
|
|
||||||
chat_error_frame(&value),
|
|
||||||
MiddlewareFraming::SseEvent,
|
|
||||||
false,
|
|
||||||
));
|
|
||||||
self.pending.push_back(done_frame());
|
|
||||||
self.finished = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MiddlewareBody for ChatBody {
|
|
||||||
fn next_frame(&mut self) -> BoxFuture<'_, Result<Option<MiddlewareFrame>, MiddlewareError>> {
|
|
||||||
Box::pin(async move {
|
|
||||||
while self.pending.is_empty() && !self.finished {
|
|
||||||
let result = match self.read_one().await {
|
|
||||||
Ok(()) if self.committed && self.projection.terminal_seen() => {
|
|
||||||
self.verify_terminal().await
|
|
||||||
}
|
|
||||||
result => result,
|
|
||||||
};
|
|
||||||
if let Err(error) = result {
|
|
||||||
if !self.committed {
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
self.fail_stream(error).await;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(self.pending.pop_front())
|
}
|
||||||
})
|
if event
|
||||||
|
.canonical_facts()
|
||||||
|
.iter()
|
||||||
|
.any(|fact| matches!(fact, GatewayEvent::Completed(_)))
|
||||||
|
{
|
||||||
|
self.completed = true;
|
||||||
|
output.append(&mut self.terminal);
|
||||||
|
}
|
||||||
|
output
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub(in crate::data_plane) struct ChatDeliveryValidator {
|
||||||
|
id: Option<String>,
|
||||||
|
finished: bool,
|
||||||
|
done: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ChatDeliveryValidator {
|
||||||
|
pub(in crate::data_plane) fn response_id(&self) -> Option<&str> {
|
||||||
|
self.id.as_deref()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn commit_downstream(
|
pub(in crate::data_plane) fn validate_frame(&mut self, bytes: &[u8]) -> Result<(), ()> {
|
||||||
&mut self,
|
if self.done {
|
||||||
client_status_code: Option<u16>,
|
return Err(());
|
||||||
) -> BoxFuture<'_, Result<(), MiddlewareError>> {
|
}
|
||||||
Box::pin(async move {
|
let text = std::str::from_utf8(bytes).map_err(|_| ())?;
|
||||||
self.inner
|
if sse_frame_is_done(text) {
|
||||||
.as_mut()
|
if !self.finished {
|
||||||
.ok_or(MiddlewareError::InvalidState)?
|
return Err(());
|
||||||
.commit_downstream(client_status_code)
|
|
||||||
.await?;
|
|
||||||
self.committed = true;
|
|
||||||
// HTTP 尚未发送首帧 即使首批已经包含 finish 或 usage 也先确认原会话完成结算
|
|
||||||
if self.projection.terminal_seen()
|
|
||||||
&& let Err(error) = self.verify_terminal().await
|
|
||||||
{
|
|
||||||
// 原会话已提交 不能把已记录的 200 改成另一 HTTP 状态
|
|
||||||
// 首个 Chat 帧为 role 或 error 成功终态仍在 pending 内可安全撤回
|
|
||||||
self.fail_stream(error).await;
|
|
||||||
}
|
}
|
||||||
Ok(())
|
self.done = true;
|
||||||
})
|
return Ok(());
|
||||||
|
}
|
||||||
|
for event in parse_sse_events(text).map_err(|_| ())? {
|
||||||
|
let value: Value = serde_json::from_str(&event.data).map_err(|_| ())?;
|
||||||
|
if value.get("error").is_some_and(Value::is_object) {
|
||||||
|
self.finished = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if value.get("object").and_then(Value::as_str) != Some("chat.completion.chunk") {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let id = value.get("id").and_then(Value::as_str).ok_or(())?;
|
||||||
|
// 首帧必须留有提交锚点,终态不能替代被中间件移除的首个业务帧
|
||||||
|
if self.id.is_none()
|
||||||
|
&& value
|
||||||
|
.pointer("/choices/0/finish_reason")
|
||||||
|
.is_some_and(Value::is_string)
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
if self.id.as_deref().is_some_and(|expected| expected != id) {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
self.id.get_or_insert_with(|| id.to_owned());
|
||||||
|
let choices = value.get("choices").and_then(Value::as_array).ok_or(())?;
|
||||||
|
if choices.is_empty() {
|
||||||
|
if !self.finished || !value.get("usage").is_some_and(Value::is_object) {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if self.finished
|
||||||
|
|| choices.len() != 1
|
||||||
|
|| choices[0].get("index").and_then(Value::as_u64) != Some(0)
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
self.finished = choices[0]
|
||||||
|
.get("finish_reason")
|
||||||
|
.is_some_and(Value::is_string);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn record_client_status(&mut self, status: u16) -> BoxFuture<'_, Result<(), MiddlewareError>> {
|
pub(in crate::data_plane) fn finish_delivery(&self) -> Result<(), ()> {
|
||||||
match self.inner.as_mut() {
|
if self.finished && self.done {
|
||||||
Some(inner) => inner.record_client_status(status),
|
Ok(())
|
||||||
None => Box::pin(async { Ok(()) }),
|
} else {
|
||||||
|
Err(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_finalized(&self) -> bool {
|
|
||||||
self.inner.as_ref().is_none_or(|inner| inner.is_finalized())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn close(mut self: Box<Self>) -> BoxFuture<'static, ()> {
|
|
||||||
let inner = self.inner.take();
|
|
||||||
Box::pin(async move {
|
|
||||||
if let Some(inner) = inner {
|
|
||||||
inner.close().await;
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn projection_error(error: ProtocolErrorBody) -> MiddlewareError {
|
|
||||||
MiddlewareError::Gateway(
|
|
||||||
GatewayError::new(
|
|
||||||
GatewayErrorKind::UpstreamUnavailable,
|
|
||||||
"The gateway could not project the upstream response to Chat Completions.",
|
|
||||||
)
|
|
||||||
.with_client_code(error.error.code),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn invalid_response() -> MiddlewareError {
|
|
||||||
MiddlewareError::Gateway(
|
|
||||||
GatewayError::new(
|
|
||||||
GatewayErrorKind::UpstreamUnavailable,
|
|
||||||
"The gateway could not deliver the Chat response.",
|
|
||||||
)
|
|
||||||
.with_client_code("invalid_upstream_response"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn done_frame() -> MiddlewareFrame {
|
|
||||||
MiddlewareFrame::new(
|
|
||||||
Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
|
||||||
MiddlewareFraming::SseEvent,
|
|
||||||
true,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
//! Chat HTTP 入口只规范化协议 共用 Responses 的执行与交付链路
|
//! Chat HTTP 入口保留原始协议,由目标 Provider 直接转换
|
||||||
|
|
||||||
use std::{net::SocketAddr, time::SystemTime};
|
use std::net::SocketAddr;
|
||||||
|
|
||||||
use axum::{
|
use axum::{
|
||||||
body::Bytes,
|
body::Bytes,
|
||||||
extract::{Extension, State, connect_info::ConnectInfo},
|
extract::{Extension, State, connect_info::ConnectInfo},
|
||||||
http::{HeaderMap, StatusCode, header::CONTENT_ENCODING},
|
http::{
|
||||||
|
HeaderMap, StatusCode,
|
||||||
|
header::{CONTENT_ENCODING, CONTENT_LENGTH},
|
||||||
|
},
|
||||||
response::Response,
|
response::Response,
|
||||||
};
|
};
|
||||||
|
use gateway_core::operation::{GenerateRequest, Operation, ProtocolPayload};
|
||||||
|
use gateway_protocol::chat_completions::{self, CHAT_PROTOCOL};
|
||||||
|
|
||||||
use crate::ApiState;
|
use crate::ApiState;
|
||||||
use crate::data_plane::{
|
use crate::data_plane::{
|
||||||
@@ -15,24 +20,17 @@ use crate::data_plane::{
|
|||||||
body::{RequestDecodeError, decompress_request_body},
|
body::{RequestDecodeError, decompress_request_body},
|
||||||
error::{gateway_error_response, protocol_error_response},
|
error::{gateway_error_response, protocol_error_response},
|
||||||
generation::{
|
generation::{
|
||||||
DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest, HttpResponseAdapter,
|
ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest,
|
||||||
execute_prepared_generation,
|
GenerationRequestMetadata, execute_prepared_generation,
|
||||||
},
|
},
|
||||||
responses::decode_request_with_headers,
|
headers::session_context,
|
||||||
router::CHAT_COMPLETIONS_PATH,
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::{
|
|
||||||
delivery::{chat_error_frame, project_middleware_response},
|
|
||||||
request::convert_request,
|
|
||||||
response::ChatIdentity,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub(in crate::data_plane) async fn chat_completions(
|
pub(in crate::data_plane) async fn chat_completions(
|
||||||
State(state): State<ApiState>,
|
State(state): State<ApiState>,
|
||||||
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
connect_info: Option<Extension<ConnectInfo<SocketAddr>>>,
|
||||||
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
ingress_id: Option<Extension<tower_http::request_id::RequestId>>,
|
||||||
headers: HeaderMap,
|
mut headers: HeaderMap,
|
||||||
body: Bytes,
|
body: Bytes,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let service = state.data_plane().clone();
|
let service = state.data_plane().clone();
|
||||||
@@ -40,12 +38,17 @@ pub(in crate::data_plane) async fn chat_completions(
|
|||||||
Ok(client) => client,
|
Ok(client) => client,
|
||||||
Err(error) => return client_access_error_response(error),
|
Err(error) => return client_access_error_response(error),
|
||||||
};
|
};
|
||||||
let (decoded, middleware_body, include_usage) = match decode_request(
|
let maximum = client.snapshot().responses_max_decompressed_body_bytes();
|
||||||
&body,
|
let body = match decompress_request_body(&body, &headers, maximum) {
|
||||||
&headers,
|
Ok(body) => Bytes::copy_from_slice(&body),
|
||||||
client.snapshot().responses_max_decompressed_body_bytes(),
|
Err(error) => {
|
||||||
) {
|
return protocol_error_response(StatusCode::BAD_REQUEST, error.protocol_body());
|
||||||
Ok(request) => request,
|
}
|
||||||
|
};
|
||||||
|
headers.remove(CONTENT_ENCODING);
|
||||||
|
headers.remove(CONTENT_LENGTH);
|
||||||
|
let decoded = match decode_request(&body, &headers, maximum) {
|
||||||
|
Ok(decoded) => decoded,
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
return protocol_error_response(StatusCode::BAD_REQUEST, error.protocol_body());
|
return protocol_error_response(StatusCode::BAD_REQUEST, error.protocol_body());
|
||||||
}
|
}
|
||||||
@@ -54,22 +57,6 @@ pub(in crate::data_plane) async fn chat_completions(
|
|||||||
Ok(prepared) => prepared,
|
Ok(prepared) => prepared,
|
||||||
Err(error) => return gateway_error_response(&error),
|
Err(error) => return gateway_error_response(&error),
|
||||||
};
|
};
|
||||||
let identity = ChatIdentity {
|
|
||||||
id: format!("chatcmpl-{}", prepared.request_id().as_str()),
|
|
||||||
created: SystemTime::now()
|
|
||||||
.duration_since(SystemTime::UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_secs(),
|
|
||||||
model: decoded.metadata().requested_model().to_owned(),
|
|
||||||
};
|
|
||||||
let streaming = decoded.metadata().stream();
|
|
||||||
let adapter = HttpResponseAdapter {
|
|
||||||
endpoint: CHAT_COMPLETIONS_PATH,
|
|
||||||
wrap: Box::new(move |response| {
|
|
||||||
project_middleware_response(response, identity, streaming, include_usage)
|
|
||||||
}),
|
|
||||||
stream_error: chat_error_frame,
|
|
||||||
};
|
|
||||||
execute_prepared_generation(
|
execute_prepared_generation(
|
||||||
service,
|
service,
|
||||||
prepared,
|
prepared,
|
||||||
@@ -77,26 +64,43 @@ pub(in crate::data_plane) async fn chat_completions(
|
|||||||
peer_address: connect_info.map(|Extension(ConnectInfo(address))| address),
|
peer_address: connect_info.map(|Extension(ConnectInfo(address))| address),
|
||||||
ingress_id,
|
ingress_id,
|
||||||
headers,
|
headers,
|
||||||
input: GenerationEndpoint::Responses.input(decoded),
|
input: GenerationEndpoint::Chat.input(decoded),
|
||||||
middleware_body,
|
middleware_body: body,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
Some(adapter),
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decode_request(
|
pub(in crate::data_plane) fn decode_request(
|
||||||
body: &[u8],
|
body: &[u8],
|
||||||
headers: &HeaderMap,
|
headers: &HeaderMap,
|
||||||
maximum_body_bytes: usize,
|
maximum: usize,
|
||||||
) -> Result<(DecodedGenerationRequest, Bytes, bool), RequestDecodeError> {
|
) -> Result<DecodedGenerationRequest, RequestDecodeError> {
|
||||||
let body = decompress_request_body(body, headers, maximum_body_bytes)?;
|
let body = decompress_request_body(body, headers, maximum)?;
|
||||||
let converted = convert_request(&body)?;
|
let parsed = chat_completions::parse_request(&body)?;
|
||||||
let body =
|
let model = parsed
|
||||||
serde_json::to_vec(&converted.body).map_err(|_| RequestDecodeError::MalformedJson)?;
|
.get("model")
|
||||||
let mut decoded_headers = headers.clone();
|
.and_then(serde_json::Value::as_str)
|
||||||
decoded_headers.remove(CONTENT_ENCODING);
|
.unwrap_or_default()
|
||||||
let decoded = decode_request_with_headers(&body, &decoded_headers, maximum_body_bytes)?;
|
.to_owned();
|
||||||
Ok((decoded, Bytes::from(body), converted.include_usage))
|
let stream = parsed
|
||||||
|
.get("stream")
|
||||||
|
.and_then(serde_json::Value::as_bool)
|
||||||
|
.unwrap_or(false);
|
||||||
|
let payload = ProtocolPayload::from_json_bytes(CHAT_PROTOCOL, Bytes::copy_from_slice(&body))
|
||||||
|
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||||
|
field: "chat request".to_owned(),
|
||||||
|
})?
|
||||||
|
.with_context(session_context(headers));
|
||||||
|
Ok(DecodedGenerationRequest {
|
||||||
|
operation: Operation::Generate(GenerateRequest::from_protocol_payload(payload)),
|
||||||
|
metadata: GenerationRequestMetadata {
|
||||||
|
requested_model: model,
|
||||||
|
stream,
|
||||||
|
continuation: ContinuationIntent::None,
|
||||||
|
client_ip: None,
|
||||||
|
user_agent: None,
|
||||||
|
},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
//! Chat Completions 与 Responses 之间的 API 协议适配
|
//! Chat 原始协议入口与交付,目标协议转换由选定的 Provider 装配
|
||||||
|
|
||||||
mod delivery;
|
pub(in crate::data_plane) mod delivery;
|
||||||
mod http;
|
mod http;
|
||||||
mod request;
|
|
||||||
mod response;
|
|
||||||
|
|
||||||
|
pub(in crate::data_plane) use delivery::chat_error_frame;
|
||||||
pub(super) use http::chat_completions;
|
pub(super) use http::chat_completions;
|
||||||
|
pub(in crate::data_plane) use http::decode_request;
|
||||||
|
|||||||
@@ -0,0 +1,182 @@
|
|||||||
|
//! Codex 模型目录的原生对象保留、通用画像投影与客户端权限裁剪
|
||||||
|
|
||||||
|
use crate::data_plane::{error::openai_error_response, service::DataPlaneService};
|
||||||
|
use axum::{
|
||||||
|
Json,
|
||||||
|
http::StatusCode,
|
||||||
|
response::{IntoResponse, Response},
|
||||||
|
};
|
||||||
|
use gateway_core::{
|
||||||
|
engine::execution::AuthenticatedClient,
|
||||||
|
routing::{PublicModelDescriptor, PublicModelProfile},
|
||||||
|
};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
const CODEX_BASE_INSTRUCTIONS: &str = "You are Codex, a coding agent. Follow the user's instructions and use the available tools to complete software engineering tasks. Inspect relevant files before editing, preserve unrelated changes, and verify the result.";
|
||||||
|
|
||||||
|
pub(crate) async fn model_catalog(
|
||||||
|
service: &DataPlaneService,
|
||||||
|
client: &AuthenticatedClient,
|
||||||
|
version: &str,
|
||||||
|
) -> Response {
|
||||||
|
let context = crate::middleware::current();
|
||||||
|
if version.len() > 64
|
||||||
|
|| !version
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_alphanumeric() || b".-+".contains(&byte))
|
||||||
|
{
|
||||||
|
return openai_error_response(
|
||||||
|
StatusCode::BAD_REQUEST,
|
||||||
|
"Invalid client_version.",
|
||||||
|
"invalid_request_error",
|
||||||
|
"invalid_client_version",
|
||||||
|
)
|
||||||
|
.into_response();
|
||||||
|
}
|
||||||
|
let catalog = match service
|
||||||
|
.execution()
|
||||||
|
.client_model_catalog(
|
||||||
|
client,
|
||||||
|
"codex",
|
||||||
|
version,
|
||||||
|
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(catalog) => catalog,
|
||||||
|
Err(_) => return catalog_unavailable_response(),
|
||||||
|
};
|
||||||
|
let models = catalog
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, entry)| match entry {
|
||||||
|
PublicModelDescriptor::Adapted(profile) => Ok(adapted_codex_model_json(profile, index)),
|
||||||
|
PublicModelDescriptor::Native { model, payload } => {
|
||||||
|
if payload.protocol() != "codex" {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
let mut value: Value = serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
||||||
|
let object = value.as_object_mut().ok_or(())?;
|
||||||
|
// 别名只改变请求标识,能力、提示词、顺序等仍由上游目录决定
|
||||||
|
object.insert("slug".to_owned(), Value::String(model.as_str().to_owned()));
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Result<Vec<_>, ()>>();
|
||||||
|
let Ok(mut models) = models else {
|
||||||
|
return catalog_unavailable_response();
|
||||||
|
};
|
||||||
|
if !client.policy().account_scope().allows_subagents() {
|
||||||
|
for model in &mut models {
|
||||||
|
model["multi_agent_version"] = json!("disabled");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(
|
||||||
|
StatusCode::OK,
|
||||||
|
// 目录经过账号选择/别名/多 Provider 聚合,不能借用上游 ETag 表示改写后的正文
|
||||||
|
[("cache-control", "private, no-store")],
|
||||||
|
Json(json!({
|
||||||
|
"models": models,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn catalog_unavailable_response() -> Response {
|
||||||
|
openai_error_response(
|
||||||
|
StatusCode::SERVICE_UNAVAILABLE,
|
||||||
|
"Model catalog is temporarily unavailable.",
|
||||||
|
"server_error",
|
||||||
|
"model_catalog_unavailable",
|
||||||
|
)
|
||||||
|
.into_response()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn adapted_codex_model_json(profile: &PublicModelProfile, index: usize) -> Value {
|
||||||
|
let id = profile.model().as_str();
|
||||||
|
let presentation = profile.presentation();
|
||||||
|
let reasoning_levels = presentation
|
||||||
|
.supported_reasoning_efforts()
|
||||||
|
.iter()
|
||||||
|
.map(|effort| {
|
||||||
|
json!({
|
||||||
|
"effort": effort,
|
||||||
|
"description": reasoning_effort_description(effort),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let reasoning_summary = presentation.reasoning_summary();
|
||||||
|
let context_window = presentation.context_window_tokens();
|
||||||
|
let max_context_window = presentation.max_context_window_tokens();
|
||||||
|
let input_modalities = if presentation.image_input() {
|
||||||
|
vec!["text", "image"]
|
||||||
|
} else {
|
||||||
|
vec!["text"]
|
||||||
|
};
|
||||||
|
let additional_speed_tiers = presentation
|
||||||
|
.service_tiers()
|
||||||
|
.iter()
|
||||||
|
.filter_map(|tier| tier.speed_tier())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let service_tiers = presentation
|
||||||
|
.service_tiers()
|
||||||
|
.iter()
|
||||||
|
.map(|tier| {
|
||||||
|
json!({
|
||||||
|
"id": tier.id(),
|
||||||
|
"name": tier.name(),
|
||||||
|
"description": tier.description(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
json!({
|
||||||
|
"slug": id,
|
||||||
|
"display_name": presentation.display_name().unwrap_or(id),
|
||||||
|
"description": presentation.description(),
|
||||||
|
"default_reasoning_level": presentation.default_reasoning_effort(),
|
||||||
|
"supported_reasoning_levels": reasoning_levels,
|
||||||
|
"shell_type": "shell_command",
|
||||||
|
"visibility": if presentation.hidden() { "hide" } else { "list" },
|
||||||
|
"supported_in_api": true,
|
||||||
|
"priority": index.saturating_add(1),
|
||||||
|
"additional_speed_tiers": additional_speed_tiers,
|
||||||
|
"service_tiers": service_tiers,
|
||||||
|
"availability_nux": Value::Null,
|
||||||
|
"upgrade": Value::Null,
|
||||||
|
"base_instructions": CODEX_BASE_INSTRUCTIONS,
|
||||||
|
"model_messages": Value::Null,
|
||||||
|
"include_skills_usage_instructions": false,
|
||||||
|
"supports_reasoning_summary_parameter": reasoning_summary,
|
||||||
|
"default_reasoning_summary": if reasoning_summary { "auto" } else { "none" },
|
||||||
|
"support_verbosity": presentation.verbosity(),
|
||||||
|
"default_verbosity": Value::Null,
|
||||||
|
"apply_patch_tool_type": presentation.agent_tools().then_some("freeform"),
|
||||||
|
"web_search_tool_type": "text",
|
||||||
|
"truncation_policy": { "mode": "tokens", "limit": 10_000 },
|
||||||
|
"supports_parallel_tool_calls": presentation.parallel_tool_calls(),
|
||||||
|
"supports_image_detail_original": presentation.image_detail_original(),
|
||||||
|
"context_window": context_window,
|
||||||
|
"max_context_window": max_context_window,
|
||||||
|
"effective_context_window_percent": 95,
|
||||||
|
"experimental_supported_tools": [],
|
||||||
|
"input_modalities": input_modalities,
|
||||||
|
"supports_search_tool": presentation.search_tool(),
|
||||||
|
// 通用画像没有 Responses Lite 支持依据,避免客户端启用未经声明的协议行为
|
||||||
|
// 原生目录由 Native 分支保留上游字段,不经过此处
|
||||||
|
"use_responses_lite": false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reasoning_effort_description(effort: &str) -> &'static str {
|
||||||
|
match effort {
|
||||||
|
"none" => "No reasoning",
|
||||||
|
"minimal" => "Minimal reasoning",
|
||||||
|
"low" => "Fast responses with lighter reasoning",
|
||||||
|
"medium" => "Balances speed and reasoning depth for everyday tasks",
|
||||||
|
"high" => "Greater reasoning depth for complex problems",
|
||||||
|
"xhigh" => "Extra high reasoning depth for complex problems",
|
||||||
|
"max" => "Maximum reasoning depth for the hardest problems",
|
||||||
|
_ => "Provider-supported reasoning level",
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
//! Codex 客户端的目录投影与请求身份扩展
|
||||||
|
|
||||||
|
mod catalog;
|
||||||
|
mod request;
|
||||||
|
|
||||||
|
pub(crate) use catalog::model_catalog;
|
||||||
|
pub(crate) use request::CodexRequestHeaders;
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
//! Codex 请求身份、Guardian 与子代理元数据的客户端边界
|
||||||
|
|
||||||
|
use crate::data_plane::headers::header_string;
|
||||||
|
use axum::http::HeaderMap;
|
||||||
|
use gateway_core::operation::ClientTurn;
|
||||||
|
use gateway_protocol::openai::{
|
||||||
|
X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER, X_OPENAI_MEMGEN_REQUEST_HEADER,
|
||||||
|
};
|
||||||
|
use serde_json::{Map, Value};
|
||||||
|
|
||||||
|
const OPENAI_SUBAGENT_KEY: &str = "x-openai-subagent";
|
||||||
|
const PASSTHROUGH_HEADERS_CONTEXT_KEY: &str = "opaque_request_headers";
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
pub(crate) struct CodexRequestHeaders {
|
||||||
|
guardian: Option<String>,
|
||||||
|
ambiguous_guardian_headers: bool,
|
||||||
|
turn_state: Option<String>,
|
||||||
|
turn_metadata: Option<String>,
|
||||||
|
version: Option<String>,
|
||||||
|
codex_window_id: Option<String>,
|
||||||
|
parent_thread_id: Option<String>,
|
||||||
|
turn_id: Option<String>,
|
||||||
|
responses_lite: Option<String>,
|
||||||
|
memgen_request: Option<String>,
|
||||||
|
subagent: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CodexRequestHeaders {
|
||||||
|
pub(crate) fn from_headers(headers: &HeaderMap) -> Self {
|
||||||
|
Self {
|
||||||
|
guardian: header_string(headers, "x-codex-guardian"),
|
||||||
|
ambiguous_guardian_headers: [
|
||||||
|
"x-codex-guardian",
|
||||||
|
OPENAI_SUBAGENT_KEY,
|
||||||
|
"x-codex-turn-metadata",
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.any(|name| {
|
||||||
|
let mut values = headers.get_all(name).iter();
|
||||||
|
values.next().is_some_and(|v| v.to_str().is_err()) || values.next().is_some()
|
||||||
|
}),
|
||||||
|
turn_state: header_string(headers, "x-codex-turn-state"),
|
||||||
|
turn_metadata: header_string(headers, "x-codex-turn-metadata"),
|
||||||
|
version: header_string(headers, "version"),
|
||||||
|
codex_window_id: header_string(headers, "x-codex-window-id"),
|
||||||
|
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
||||||
|
turn_id: header_string(headers, "x-codex-turn-id"),
|
||||||
|
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
||||||
|
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
||||||
|
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn append_context(&self, context: &mut Map<String, Value>) {
|
||||||
|
for (key, value) in [
|
||||||
|
("turn_state", self.turn_state.as_ref()),
|
||||||
|
("turn_metadata", self.turn_metadata.as_ref()),
|
||||||
|
("subagent", self.subagent.as_ref()),
|
||||||
|
("version", self.version.as_ref()),
|
||||||
|
("codex_window_id", self.codex_window_id.as_ref()),
|
||||||
|
("parent_thread_id", self.parent_thread_id.as_ref()),
|
||||||
|
("turn_id", self.turn_id.as_ref()),
|
||||||
|
("responses_lite", self.responses_lite.as_ref()),
|
||||||
|
("memgen_request", self.memgen_request.as_ref()),
|
||||||
|
] {
|
||||||
|
if let Some(value) = value {
|
||||||
|
context.insert(key.into(), Value::String(value.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn apply(
|
||||||
|
&self,
|
||||||
|
body: &mut Map<String, Value>,
|
||||||
|
context: &mut Map<String, Value>,
|
||||||
|
websocket_frame: bool,
|
||||||
|
) -> Option<ClientTurn> {
|
||||||
|
gateway_protocol::openai::capture_codex_guardian_identity(
|
||||||
|
body,
|
||||||
|
context,
|
||||||
|
self.guardian.as_deref(),
|
||||||
|
self.ambiguous_guardian_headers,
|
||||||
|
);
|
||||||
|
self.apply_subagent(body, context, websocket_frame);
|
||||||
|
|
||||||
|
let semantics = gateway_protocol::openai::codex_responses_request_semantics(body, context);
|
||||||
|
if body.get("generate").and_then(Value::as_bool) != Some(false)
|
||||||
|
&& semantics.request_kind.as_deref() == Some("turn")
|
||||||
|
&& !semantics.compact
|
||||||
|
{
|
||||||
|
gateway_protocol::openai::codex_account_thread_id(body, context)
|
||||||
|
.zip(gateway_protocol::openai::codex_turn_id(body, context))
|
||||||
|
.and_then(|(thread, turn)| ClientTurn::new(thread, turn))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply_subagent(
|
||||||
|
&self,
|
||||||
|
body: &mut Map<String, Value>,
|
||||||
|
context: &mut Map<String, Value>,
|
||||||
|
websocket_frame: bool,
|
||||||
|
) {
|
||||||
|
if websocket_frame
|
||||||
|
&& let Some(frame_agent) = body
|
||||||
|
.get("client_metadata")
|
||||||
|
.and_then(|m| m.get(OPENAI_SUBAGENT_KEY))
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
&& (frame_agent == "guardian"
|
||||||
|
|| self.subagent.as_deref() == Some("guardian")
|
||||||
|
|| self.guardian.is_some())
|
||||||
|
{
|
||||||
|
// 帧内声明优先;旧 opening 的不透明副本也不能在 Provider 再度覆盖
|
||||||
|
let stale_subagent = self
|
||||||
|
.subagent
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|opening| opening != frame_agent);
|
||||||
|
let stale_guardian = self.guardian.as_deref().is_some_and(|opening| {
|
||||||
|
frame_agent != "guardian"
|
||||||
|
|| gateway_protocol::openai::codex_guardian_role(body, context)
|
||||||
|
.is_some_and(|role| role.header() != Some(opening))
|
||||||
|
});
|
||||||
|
if stale_subagent {
|
||||||
|
context.insert("subagent".into(), Value::from(frame_agent));
|
||||||
|
}
|
||||||
|
if (stale_subagent || stale_guardian)
|
||||||
|
&& let Some(Value::Array(headers)) =
|
||||||
|
context.get_mut(PASSTHROUGH_HEADERS_CONTEXT_KEY)
|
||||||
|
{
|
||||||
|
headers.retain(|pair| match pair.get(0).and_then(Value::as_str) {
|
||||||
|
Some(OPENAI_SUBAGENT_KEY) => !stale_subagent,
|
||||||
|
Some("x-codex-guardian") => !stale_guardian,
|
||||||
|
_ => true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(subagent) = self.subagent.as_deref() {
|
||||||
|
inject_subagent_metadata(body, subagent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inject_subagent_metadata(body: &mut Map<String, Value>, subagent: &str) {
|
||||||
|
let metadata = body
|
||||||
|
.entry("client_metadata".to_owned())
|
||||||
|
.or_insert_with(|| Value::Object(Map::new()));
|
||||||
|
let Some(metadata) = metadata.as_object_mut() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
metadata.insert(
|
||||||
|
OPENAI_SUBAGENT_KEY.to_owned(),
|
||||||
|
Value::String(subagent.to_owned()),
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -113,7 +113,7 @@ pub(super) fn decode(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
context.insert("headers".into(), Value::Object(attribution));
|
context.insert("headers".into(), Value::Object(attribution));
|
||||||
let passthrough = crate::data_plane::responses::request::passthrough_headers(headers);
|
let passthrough = crate::data_plane::headers::passthrough_headers(headers);
|
||||||
if !passthrough.is_empty() {
|
if !passthrough.is_empty() {
|
||||||
context.insert("opaque_request_headers".into(), Value::Array(passthrough));
|
context.insert("opaque_request_headers".into(), Value::Array(passthrough));
|
||||||
}
|
}
|
||||||
@@ -149,7 +149,6 @@ pub(super) fn decode(
|
|||||||
metadata: GenerationRequestMetadata {
|
metadata: GenerationRequestMetadata {
|
||||||
requested_model: model.to_owned(),
|
requested_model: model.to_owned(),
|
||||||
stream,
|
stream,
|
||||||
store: false,
|
|
||||||
continuation: ContinuationIntent::None,
|
continuation: ContinuationIntent::None,
|
||||||
client_ip: None,
|
client_ip: None,
|
||||||
user_agent: None,
|
user_agent: None,
|
||||||
@@ -176,7 +175,7 @@ async fn generate(
|
|||||||
body: Bytes,
|
body: Bytes,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let service = state.data_plane().clone();
|
let service = state.data_plane().clone();
|
||||||
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::Bearer).await {
|
let client = match authenticate_client(&service, &headers, ClientKeyHeaders::GenAi).await {
|
||||||
Ok(client) => client,
|
Ok(client) => client,
|
||||||
Err(error) => return client_access_error_response(error),
|
Err(error) => return client_access_error_response(error),
|
||||||
};
|
};
|
||||||
@@ -217,13 +216,12 @@ async fn generate(
|
|||||||
middleware_body: body,
|
middleware_body: body,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn metric(State(state): State<ApiState>, headers: HeaderMap) -> Response {
|
async fn metric(State(state): State<ApiState>, headers: HeaderMap) -> Response {
|
||||||
match verify_client(state.data_plane(), &headers).await {
|
match verify_client(state.data_plane(), &headers, ClientKeyHeaders::GenAi).await {
|
||||||
Ok(_) => Json(json!({})).into_response(),
|
Ok(_) => Json(json!({})).into_response(),
|
||||||
Err(error) => client_access_error_response(error.into()),
|
Err(error) => client_access_error_response(error.into()),
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ async fn query_response(
|
|||||||
query: ModelsQuery,
|
query: ModelsQuery,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let service = state.data_plane();
|
let service = state.data_plane();
|
||||||
let client = match authenticate_client(service, &headers, ClientKeyHeaders::Bearer).await {
|
let client = match authenticate_client(service, &headers, ClientKeyHeaders::GenAi).await {
|
||||||
Ok(client) => client,
|
Ok(client) => client,
|
||||||
Err(err) => return client_access_error_response(err),
|
Err(err) => return client_access_error_response(err),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -32,9 +32,7 @@ use gateway_core::engine::{
|
|||||||
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
||||||
use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
||||||
use gateway_core::lifecycle::{CancellationToken, ConnectionGuard};
|
use gateway_core::lifecycle::{CancellationToken, ConnectionGuard};
|
||||||
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
|
||||||
use gateway_protocol::openai::sse::response_failed_sse_event_with_id;
|
use gateway_protocol::openai::sse::response_failed_sse_event_with_id;
|
||||||
use serde_json::Value;
|
|
||||||
use tokio::time::Instant;
|
use tokio::time::Instant;
|
||||||
|
|
||||||
use crate::data_plane::error::{
|
use crate::data_plane::error::{
|
||||||
@@ -69,11 +67,17 @@ pub(crate) struct GenerationHttpRequest {
|
|||||||
pub middleware_body: Bytes,
|
pub middleware_body: Bytes,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 下游协议只投影出口字节 执行会话和计量仍归原 owner
|
impl GenerationEndpoint {
|
||||||
pub(crate) struct HttpResponseAdapter {
|
fn expected_http_body(self, stream: bool) -> ExpectedBody {
|
||||||
pub endpoint: &'static str,
|
if stream {
|
||||||
pub wrap: Box<dyn FnOnce(MiddlewareResponse) -> MiddlewareResponse + Send>,
|
// 原生 GenAI 客户端会将网关插入的 SSE 注释解析为无效帧
|
||||||
pub stream_error: fn(&Value) -> Bytes,
|
ExpectedBody::Sse {
|
||||||
|
keep_alive: matches!(self, Self::Chat | Self::Responses | Self::Messages),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ExpectedBody::SingleJson
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn execute_prepared_generation(
|
pub(crate) async fn execute_prepared_generation(
|
||||||
@@ -81,7 +85,6 @@ pub(crate) async fn execute_prepared_generation(
|
|||||||
prepared: PreparedRootExecution,
|
prepared: PreparedRootExecution,
|
||||||
request: GenerationHttpRequest,
|
request: GenerationHttpRequest,
|
||||||
authorization: Option<Arc<dyn ResponseAuthorization>>,
|
authorization: Option<Arc<dyn ResponseAuthorization>>,
|
||||||
adapter: Option<HttpResponseAdapter>,
|
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let GenerationHttpRequest {
|
let GenerationHttpRequest {
|
||||||
peer_address,
|
peer_address,
|
||||||
@@ -106,18 +109,17 @@ pub(crate) async fn execute_prepared_generation(
|
|||||||
let terminal_entered = Arc::clone(&execution_entered);
|
let terminal_entered = Arc::clone(&execution_entered);
|
||||||
let started_request_id = Arc::new(OnceLock::new());
|
let started_request_id = Arc::new(OnceLock::new());
|
||||||
let terminal_request_id = Arc::clone(&started_request_id);
|
let terminal_request_id = Arc::clone(&started_request_id);
|
||||||
let (admitted, keepalive) = tokio::sync::oneshot::channel();
|
let expected = protocol.expected_http_body(stream);
|
||||||
|
let (admitted, keepalive) = expected
|
||||||
|
.sends_keepalive()
|
||||||
|
.then(tokio::sync::oneshot::channel)
|
||||||
|
.unzip();
|
||||||
let mut middleware_headers = headers.clone();
|
let mut middleware_headers = headers.clone();
|
||||||
// 中间件正文已经由入口按上限解压;传输编码和旧长度不能与改写后的正文混用
|
// 中间件正文已经由入口按上限解压;传输编码和旧长度不能与改写后的正文混用
|
||||||
middleware_headers.remove(CONTENT_ENCODING);
|
middleware_headers.remove(CONTENT_ENCODING);
|
||||||
middleware_headers.remove(CONTENT_LENGTH);
|
middleware_headers.remove(CONTENT_LENGTH);
|
||||||
let endpoint = adapter
|
let endpoint = protocol.path();
|
||||||
.as_ref()
|
let stream_error = protocol.stream_error_encoder();
|
||||||
.map_or(protocol.path(), |adapter| adapter.endpoint);
|
|
||||||
let stream_error = adapter
|
|
||||||
.as_ref()
|
|
||||||
.map(|adapter| adapter.stream_error)
|
|
||||||
.or_else(|| protocol.stream_error_encoder());
|
|
||||||
let input = RequestInput {
|
let input = RequestInput {
|
||||||
endpoint: endpoint.to_owned(),
|
endpoint: endpoint.to_owned(),
|
||||||
protocol: protocol.wire().to_owned(),
|
protocol: protocol.wire().to_owned(),
|
||||||
@@ -183,7 +185,9 @@ pub(crate) async fn execute_prepared_generation(
|
|||||||
.session
|
.session
|
||||||
.trace()
|
.trace()
|
||||||
.capture("client.request.body", &request_body);
|
.capture("client.request.body", &request_body);
|
||||||
let _ = admitted.send(started.session.response_commit());
|
if let Some(admitted) = admitted {
|
||||||
|
let _ = admitted.send(started.session.response_commit());
|
||||||
|
}
|
||||||
execution_middleware_response(
|
execution_middleware_response(
|
||||||
started,
|
started,
|
||||||
connection_guard,
|
connection_guard,
|
||||||
@@ -203,11 +207,6 @@ pub(crate) async fn execute_prepared_generation(
|
|||||||
} else {
|
} else {
|
||||||
middleware.await
|
middleware.await
|
||||||
};
|
};
|
||||||
let expected = if stream {
|
|
||||||
ExpectedBody::Sse
|
|
||||||
} else {
|
|
||||||
ExpectedBody::SingleJson
|
|
||||||
};
|
|
||||||
match middleware {
|
match middleware {
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
let response = if let Some(authorization) = authorization {
|
let response = if let Some(authorization) = authorization {
|
||||||
@@ -217,21 +216,20 @@ pub(crate) async fn execute_prepared_generation(
|
|||||||
};
|
};
|
||||||
let response =
|
let response =
|
||||||
validated_middleware_response(response, validation, stream, protocol);
|
validated_middleware_response(response, validation, stream, protocol);
|
||||||
let response = match adapter {
|
|
||||||
Some(adapter) => (adapter.wrap)(response),
|
|
||||||
None => response,
|
|
||||||
};
|
|
||||||
into_http_response(response, expected, protocol.wire()).await
|
into_http_response(response, expected, protocol.wire()).await
|
||||||
}
|
}
|
||||||
Err(error) => error_response(error),
|
Err(error) => error_response(error),
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let response = if stream {
|
let response = if let Some(keepalive) = keepalive {
|
||||||
super::keepalive::response_with_encoder(
|
super::keepalive::response(
|
||||||
response,
|
response,
|
||||||
keepalive,
|
keepalive,
|
||||||
stream_error,
|
stream_error,
|
||||||
protocol == GenerationEndpoint::Responses,
|
matches!(
|
||||||
|
protocol,
|
||||||
|
GenerationEndpoint::Responses | GenerationEndpoint::Chat
|
||||||
|
),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
} else {
|
} else {
|
||||||
@@ -473,50 +471,6 @@ async fn streaming_execution_middleware_response(
|
|||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 直接驱动测试 session 的非流式交付;生产入口通过同一 MiddlewareResponse 路径
|
|
||||||
pub async fn collect_execution_response(session: Box<dyn ExecutionSession>) -> Response {
|
|
||||||
match buffered_execution_middleware_response(
|
|
||||||
session,
|
|
||||||
GenerationValidationFacts::new(GenerationEndpoint::Responses),
|
|
||||||
GenerationEndpoint::Responses,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(response) => {
|
|
||||||
into_http_response(response, ExpectedBody::SingleJson, OPENAI_PROTOCOL).await
|
|
||||||
}
|
|
||||||
Err(error) => error_response(error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 直接驱动测试 session 的 SSE 交付;生产入口通过同一 MiddlewareResponse 路径
|
|
||||||
pub async fn stream_execution_response(
|
|
||||||
session: Box<dyn ExecutionSession>,
|
|
||||||
connection_guard: Option<Box<dyn ConnectionGuard>>,
|
|
||||||
) -> Response {
|
|
||||||
let (admitted, keepalive) = tokio::sync::oneshot::channel();
|
|
||||||
let _ = admitted.send(session.response_commit());
|
|
||||||
super::keepalive::response(
|
|
||||||
async move {
|
|
||||||
match streaming_execution_middleware_response(
|
|
||||||
session,
|
|
||||||
connection_guard,
|
|
||||||
GenerationValidationFacts::new(GenerationEndpoint::Responses),
|
|
||||||
GenerationEndpoint::Responses,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(response) => {
|
|
||||||
into_http_response(response, ExpectedBody::Sse, OPENAI_PROTOCOL).await
|
|
||||||
}
|
|
||||||
Err(error) => error_response(error),
|
|
||||||
}
|
|
||||||
},
|
|
||||||
keepalive,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
fn validated_middleware_response(
|
fn validated_middleware_response(
|
||||||
response: MiddlewareResponse,
|
response: MiddlewareResponse,
|
||||||
facts: GenerationValidationFacts,
|
facts: GenerationValidationFacts,
|
||||||
@@ -729,9 +683,9 @@ fn apply_provider_response_headers(
|
|||||||
response_headers: &[ProviderResponseHeader],
|
response_headers: &[ProviderResponseHeader],
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let connection_options =
|
let connection_options =
|
||||||
crate::data_plane::responses::response_connection_options(response_headers);
|
crate::data_plane::headers::response_connection_options(response_headers);
|
||||||
for header in response_headers {
|
for header in response_headers {
|
||||||
if !crate::data_plane::responses::response_header_is_forwardable(
|
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||||
header.name(),
|
header.name(),
|
||||||
&connection_options,
|
&connection_options,
|
||||||
) {
|
) {
|
||||||
@@ -753,7 +707,7 @@ fn response_headers(
|
|||||||
streaming: bool,
|
streaming: bool,
|
||||||
) -> Vec<MiddlewareHeader> {
|
) -> Vec<MiddlewareHeader> {
|
||||||
let connection_options =
|
let connection_options =
|
||||||
crate::data_plane::responses::response_connection_options(provider_headers);
|
crate::data_plane::headers::response_connection_options(provider_headers);
|
||||||
let mut headers = Vec::new();
|
let mut headers = Vec::new();
|
||||||
headers.push(MiddlewareHeader::new(
|
headers.push(MiddlewareHeader::new(
|
||||||
CONTENT_TYPE.as_str(),
|
CONTENT_TYPE.as_str(),
|
||||||
@@ -764,7 +718,7 @@ fn response_headers(
|
|||||||
}),
|
}),
|
||||||
));
|
));
|
||||||
for header in provider_headers {
|
for header in provider_headers {
|
||||||
if !crate::data_plane::responses::response_header_is_forwardable(
|
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||||
header.name(),
|
header.name(),
|
||||||
&connection_options,
|
&connection_options,
|
||||||
) || header.name().eq_ignore_ascii_case(CONTENT_TYPE.as_str())
|
) || header.name().eq_ignore_ascii_case(CONTENT_TYPE.as_str())
|
||||||
@@ -995,6 +949,25 @@ impl MiddlewareBody for StreamingExecutionBody {
|
|||||||
.map_err(MiddlewareError::Engine)?;
|
.map_err(MiddlewareError::Engine)?;
|
||||||
self.committed = true;
|
self.committed = true;
|
||||||
self.batch_pending = false;
|
self.batch_pending = false;
|
||||||
|
if self.protocol == GenerationEndpoint::Chat && self.awaiting_terminal_eof {
|
||||||
|
match self.verify_terminal_eof().await {
|
||||||
|
Ok(()) => {
|
||||||
|
self.pending.push_back(done_frame(self.protocol));
|
||||||
|
self.output_finished = true;
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
self.pending.clear();
|
||||||
|
let error = match error {
|
||||||
|
MiddlewareError::Engine(error) => gateway_error_from_engine(&error),
|
||||||
|
_ => GatewayError::new(
|
||||||
|
GatewayErrorKind::UpstreamUnavailable,
|
||||||
|
"The Chat response could not be finalized.",
|
||||||
|
),
|
||||||
|
};
|
||||||
|
self.push_stream_error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,13 +21,6 @@ use crate::data_plane::middleware::{SSE_KEEPALIVE_FRAME, SSE_KEEPALIVE_INTERVAL}
|
|||||||
pub(in crate::data_plane) async fn response(
|
pub(in crate::data_plane) async fn response(
|
||||||
response: impl Future<Output = Response> + Send + 'static,
|
response: impl Future<Output = Response> + Send + 'static,
|
||||||
admitted: oneshot::Receiver<ResponseCommit>,
|
admitted: oneshot::Receiver<ResponseCommit>,
|
||||||
) -> Response {
|
|
||||||
response_with_encoder(response, admitted, None, true).await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(in crate::data_plane) async fn response_with_encoder(
|
|
||||||
response: impl Future<Output = Response> + Send + 'static,
|
|
||||||
admitted: oneshot::Receiver<ResponseCommit>,
|
|
||||||
error_encoder: Option<fn(&Value) -> Bytes>,
|
error_encoder: Option<fn(&Value) -> Bytes>,
|
||||||
append_done: bool,
|
append_done: bool,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
|
|||||||
@@ -6,9 +6,7 @@ mod request;
|
|||||||
mod response;
|
mod response;
|
||||||
mod validation;
|
mod validation;
|
||||||
|
|
||||||
pub(crate) use http::{
|
pub(crate) use http::{GenerationHttpRequest, ResponseAuthorization, execute_prepared_generation};
|
||||||
GenerationHttpRequest, HttpResponseAdapter, ResponseAuthorization, execute_prepared_generation,
|
|
||||||
};
|
|
||||||
pub use request::{ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata};
|
pub use request::{ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata};
|
||||||
|
|
||||||
use axum::http::HeaderMap;
|
use axum::http::HeaderMap;
|
||||||
@@ -18,6 +16,7 @@ use gateway_protocol::openai::OPENAI_PROTOCOL;
|
|||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
pub(crate) enum GenerationEndpoint {
|
pub(crate) enum GenerationEndpoint {
|
||||||
|
Chat,
|
||||||
Responses,
|
Responses,
|
||||||
Messages,
|
Messages,
|
||||||
MessageTokenCount,
|
MessageTokenCount,
|
||||||
@@ -36,6 +35,7 @@ impl GenerationEndpoint {
|
|||||||
|
|
||||||
pub(crate) const fn wire(self) -> &'static str {
|
pub(crate) const fn wire(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chat => gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||||
Self::Responses => OPENAI_PROTOCOL,
|
Self::Responses => OPENAI_PROTOCOL,
|
||||||
Self::GenAi | Self::GenAiTokenCount => gateway_protocol::genai::GENAI_PROTOCOL,
|
Self::GenAi | Self::GenAiTokenCount => gateway_protocol::genai::GENAI_PROTOCOL,
|
||||||
Self::Messages | Self::MessageTokenCount => ANTHROPIC_PROTOCOL,
|
Self::Messages | Self::MessageTokenCount => ANTHROPIC_PROTOCOL,
|
||||||
@@ -44,6 +44,7 @@ impl GenerationEndpoint {
|
|||||||
|
|
||||||
pub(crate) const fn path(self) -> &'static str {
|
pub(crate) const fn path(self) -> &'static str {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chat => super::router::CHAT_COMPLETIONS_PATH,
|
||||||
Self::Responses => super::router::RESPONSES_PATH,
|
Self::Responses => super::router::RESPONSES_PATH,
|
||||||
Self::GenAi | Self::GenAiTokenCount => super::genai::MODEL_ACTION_PATH,
|
Self::GenAi | Self::GenAiTokenCount => super::genai::MODEL_ACTION_PATH,
|
||||||
Self::Messages => super::router::MESSAGES_PATH,
|
Self::Messages => super::router::MESSAGES_PATH,
|
||||||
@@ -53,7 +54,7 @@ impl GenerationEndpoint {
|
|||||||
|
|
||||||
pub(crate) const fn operation(self) -> OperationKind {
|
pub(crate) const fn operation(self) -> OperationKind {
|
||||||
match self {
|
match self {
|
||||||
Self::Responses | Self::Messages | Self::GenAi => OperationKind::Generate,
|
Self::Chat | Self::Responses | Self::Messages | Self::GenAi => OperationKind::Generate,
|
||||||
Self::MessageTokenCount | Self::GenAiTokenCount => OperationKind::CountTokens,
|
Self::MessageTokenCount | Self::GenAiTokenCount => OperationKind::CountTokens,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -74,6 +75,17 @@ impl GenerationInput {
|
|||||||
) -> Result<DecodedGenerationRequest, gateway_core::engine::middleware::MiddlewareError> {
|
) -> Result<DecodedGenerationRequest, gateway_core::engine::middleware::MiddlewareError> {
|
||||||
use gateway_core::engine::middleware::MiddlewareError;
|
use gateway_core::engine::middleware::MiddlewareError;
|
||||||
match self.endpoint {
|
match self.endpoint {
|
||||||
|
GenerationEndpoint::Chat => {
|
||||||
|
super::chat_completions::decode_request(body, headers, maximum).map_err(|error| {
|
||||||
|
MiddlewareError::Gateway(
|
||||||
|
gateway_core::error::GatewayError::new(
|
||||||
|
gateway_core::error::GatewayErrorKind::InvalidRequest,
|
||||||
|
"The Chat request is invalid.",
|
||||||
|
)
|
||||||
|
.with_source(error),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => {
|
GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => {
|
||||||
super::genai::decode(
|
super::genai::decode(
|
||||||
&self.model,
|
&self.model,
|
||||||
|
|||||||
@@ -32,12 +32,11 @@ impl fmt::Debug for ContinuationIntent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handler、Router 和 history owner 使用的请求元数据
|
/// 生成入口的路由、续接与客户端观测事实
|
||||||
#[derive(Clone, PartialEq, Eq)]
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
pub struct GenerationRequestMetadata {
|
pub struct GenerationRequestMetadata {
|
||||||
pub(in crate::data_plane) requested_model: String,
|
pub(in crate::data_plane) requested_model: String,
|
||||||
pub(in crate::data_plane) stream: bool,
|
pub(in crate::data_plane) stream: bool,
|
||||||
pub(in crate::data_plane) store: bool,
|
|
||||||
pub(in crate::data_plane) continuation: ContinuationIntent,
|
pub(in crate::data_plane) continuation: ContinuationIntent,
|
||||||
pub(in crate::data_plane) client_ip: Option<IpAddr>,
|
pub(in crate::data_plane) client_ip: Option<IpAddr>,
|
||||||
pub(in crate::data_plane) user_agent: Option<String>,
|
pub(in crate::data_plane) user_agent: Option<String>,
|
||||||
@@ -56,12 +55,6 @@ impl GenerationRequestMetadata {
|
|||||||
self.stream
|
self.stream
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 返回客户端 storage intent
|
|
||||||
#[must_use]
|
|
||||||
pub const fn store(&self) -> bool {
|
|
||||||
self.store
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 返回 continuation intent
|
/// 返回 continuation intent
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn continuation(&self) -> &ContinuationIntent {
|
pub const fn continuation(&self) -> &ContinuationIntent {
|
||||||
@@ -87,7 +80,6 @@ impl fmt::Debug for GenerationRequestMetadata {
|
|||||||
.debug_struct("GenerationRequestMetadata")
|
.debug_struct("GenerationRequestMetadata")
|
||||||
.field("requested_model", &self.requested_model)
|
.field("requested_model", &self.requested_model)
|
||||||
.field("stream", &self.stream)
|
.field("stream", &self.stream)
|
||||||
.field("store", &self.store)
|
|
||||||
.field("continuation", &self.continuation)
|
.field("continuation", &self.continuation)
|
||||||
.field("client_ip", &self.client_ip)
|
.field("client_ip", &self.client_ip)
|
||||||
.field("has_user_agent", &self.user_agent.is_some())
|
.field("has_user_agent", &self.user_agent.is_some())
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ use crate::data_plane::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
pub(super) enum GenerationEncoder {
|
pub(super) enum GenerationEncoder {
|
||||||
|
Chat(crate::data_plane::chat_completions::delivery::ChatEncoder),
|
||||||
Responses(OpenAiResponsesEncoder),
|
Responses(OpenAiResponsesEncoder),
|
||||||
GenAi {
|
GenAi {
|
||||||
failed: bool,
|
failed: bool,
|
||||||
@@ -33,6 +34,7 @@ pub(super) enum GenerationEncoder {
|
|||||||
impl GenerationEncoder {
|
impl GenerationEncoder {
|
||||||
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
||||||
match protocol {
|
match protocol {
|
||||||
|
GenerationEndpoint::Chat => Self::Chat(Default::default()),
|
||||||
GenerationEndpoint::Responses => Self::Responses(OpenAiResponsesEncoder::new()),
|
GenerationEndpoint::Responses => Self::Responses(OpenAiResponsesEncoder::new()),
|
||||||
GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => {
|
GenerationEndpoint::GenAi | GenerationEndpoint::GenAiTokenCount => {
|
||||||
Self::GenAi { failed: false }
|
Self::GenAi { failed: false }
|
||||||
@@ -49,6 +51,7 @@ impl GenerationEncoder {
|
|||||||
|
|
||||||
pub(super) fn push_sse(&mut self, event: &ProviderEvent) -> Vec<Bytes> {
|
pub(super) fn push_sse(&mut self, event: &ProviderEvent) -> Vec<Bytes> {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chat(encoder) => encoder.push(event),
|
||||||
Self::Responses(encoder) => encoder.push_sse(event),
|
Self::Responses(encoder) => encoder.push_sse(event),
|
||||||
Self::GenAi { failed } => {
|
Self::GenAi { failed } => {
|
||||||
let Some(wire) = event
|
let Some(wire) = event
|
||||||
@@ -142,6 +145,7 @@ impl GenerationEncoder {
|
|||||||
match self {
|
match self {
|
||||||
Self::Responses(encoder) => encoder.is_completed(),
|
Self::Responses(encoder) => encoder.is_completed(),
|
||||||
// 原生 GenAI 以 EOF 结束,finishReason 后仍可收到独立用量帧
|
// 原生 GenAI 以 EOF 结束,finishReason 后仍可收到独立用量帧
|
||||||
|
Self::Chat(encoder) => encoder.completed,
|
||||||
Self::GenAi { .. } => false,
|
Self::GenAi { .. } => false,
|
||||||
Self::Messages { completed, .. } => *completed,
|
Self::Messages { completed, .. } => *completed,
|
||||||
}
|
}
|
||||||
@@ -150,6 +154,7 @@ impl GenerationEncoder {
|
|||||||
pub(super) fn has_wire_failure(&self) -> bool {
|
pub(super) fn has_wire_failure(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Self::Responses(encoder) => encoder.has_wire_failure(),
|
Self::Responses(encoder) => encoder.has_wire_failure(),
|
||||||
|
Self::Chat(encoder) => encoder.failed,
|
||||||
Self::Messages { failed, .. } | Self::GenAi { failed } => *failed,
|
Self::Messages { failed, .. } | Self::GenAi { failed } => *failed,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -157,6 +162,13 @@ impl GenerationEncoder {
|
|||||||
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes {
|
pub(super) fn error_frame(&self, error: &GatewayError) -> Bytes {
|
||||||
let (status, error_type, code) = gateway_error_contract(error.kind());
|
let (status, error_type, code) = gateway_error_contract(error.kind());
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chat(_) => {
|
||||||
|
crate::data_plane::chat_completions::chat_error_frame(&json!({"error": {
|
||||||
|
"type": error.client_error_type().unwrap_or(error_type),
|
||||||
|
"code": error.client_error_code().unwrap_or(code),
|
||||||
|
"message": error.client_message(),
|
||||||
|
}}))
|
||||||
|
}
|
||||||
Self::Responses(encoder) => Bytes::from(response_failed_sse_event_with_id(
|
Self::Responses(encoder) => Bytes::from(response_failed_sse_event_with_id(
|
||||||
encoder.response_id(),
|
encoder.response_id(),
|
||||||
error.client_error_type().unwrap_or(error_type),
|
error.client_error_type().unwrap_or(error_type),
|
||||||
@@ -180,6 +192,7 @@ impl GenerationEncoder {
|
|||||||
impl GenerationEndpoint {
|
impl GenerationEndpoint {
|
||||||
pub(super) const fn stream_error_encoder(self) -> Option<fn(&Value) -> Bytes> {
|
pub(super) const fn stream_error_encoder(self) -> Option<fn(&Value) -> Bytes> {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chat => Some(crate::data_plane::chat_completions::chat_error_frame),
|
||||||
Self::Responses => None,
|
Self::Responses => None,
|
||||||
Self::GenAi | Self::GenAiTokenCount => Some(crate::data_plane::genai::stream_error),
|
Self::GenAi | Self::GenAiTokenCount => Some(crate::data_plane::genai::stream_error),
|
||||||
Self::Messages | Self::MessageTokenCount => Some(messages::stream_error),
|
Self::Messages | Self::MessageTokenCount => Some(messages::stream_error),
|
||||||
@@ -191,7 +204,7 @@ impl GenerationEndpoint {
|
|||||||
response: axum::response::Response,
|
response: axum::response::Response,
|
||||||
) -> axum::response::Response {
|
) -> axum::response::Response {
|
||||||
match self {
|
match self {
|
||||||
Self::Responses => response,
|
Self::Chat | Self::Responses => response,
|
||||||
Self::GenAi | Self::GenAiTokenCount => {
|
Self::GenAi | Self::GenAiTokenCount => {
|
||||||
crate::data_plane::genai::project_error_response(response).await
|
crate::data_plane::genai::project_error_response(response).await
|
||||||
}
|
}
|
||||||
@@ -203,7 +216,7 @@ impl GenerationEndpoint {
|
|||||||
|
|
||||||
pub(super) fn terminal_bytes(self) -> Bytes {
|
pub(super) fn terminal_bytes(self) -> Bytes {
|
||||||
match self {
|
match self {
|
||||||
Self::Responses => Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
Self::Chat | Self::Responses => Bytes::from_static(DONE_SSE_FRAME.as_bytes()),
|
||||||
// Messages 的 message_stop 已在 wire 中交付,空帧只确认宿主交付终结
|
// Messages 的 message_stop 已在 wire 中交付,空帧只确认宿主交付终结
|
||||||
Self::Messages | Self::MessageTokenCount | Self::GenAi | Self::GenAiTokenCount => {
|
Self::Messages | Self::MessageTokenCount | Self::GenAi | Self::GenAiTokenCount => {
|
||||||
Bytes::new()
|
Bytes::new()
|
||||||
@@ -212,6 +225,39 @@ impl GenerationEndpoint {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn collect(self, events: &[ProviderEvent]) -> Result<Vec<u8>, ResponseEncodeError> {
|
pub(super) fn collect(self, events: &[ProviderEvent]) -> Result<Vec<u8>, ResponseEncodeError> {
|
||||||
|
if self == Self::Chat {
|
||||||
|
let mut accumulator = gateway_protocol::chat_completions::ChatAccumulator::default();
|
||||||
|
let mut json_body = None;
|
||||||
|
let mut chunks = false;
|
||||||
|
for wire in events
|
||||||
|
.iter()
|
||||||
|
.filter_map(ProviderEvent::wire_event)
|
||||||
|
.filter(|wire| wire.protocol() == self.wire())
|
||||||
|
{
|
||||||
|
if let Some(raw) = wire.raw_json_body() {
|
||||||
|
if chunks || json_body.replace(raw).is_some() {
|
||||||
|
return Err(ResponseEncodeError::InvalidOutputItems);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if json_body.is_some() {
|
||||||
|
return Err(ResponseEncodeError::InvalidOutputItems);
|
||||||
|
}
|
||||||
|
chunks = true;
|
||||||
|
accumulator
|
||||||
|
.push(wire.data())
|
||||||
|
.map_err(|_| ResponseEncodeError::InvalidOutputItems)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(raw) = json_body {
|
||||||
|
return Ok(raw.to_vec());
|
||||||
|
}
|
||||||
|
return serde_json::to_vec(
|
||||||
|
&accumulator
|
||||||
|
.finish()
|
||||||
|
.map_err(|_| ResponseEncodeError::MissingWireTerminal)?,
|
||||||
|
)
|
||||||
|
.map_err(|_| ResponseEncodeError::Serialization);
|
||||||
|
}
|
||||||
if self == Self::Responses {
|
if self == Self::Responses {
|
||||||
return serde_json::to_vec(&crate::data_plane::responses::response::collect_response(
|
return serde_json::to_vec(&crate::data_plane::responses::response::collect_response(
|
||||||
events,
|
events,
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ use crate::data_plane::responses::validation::{
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub(super) enum GenerationValidationFacts {
|
pub(super) enum GenerationValidationFacts {
|
||||||
|
Chat(Arc<Mutex<Option<String>>>),
|
||||||
Responses(ResponseValidationFacts),
|
Responses(ResponseValidationFacts),
|
||||||
Messages(Arc<Mutex<Option<String>>>),
|
Messages(Arc<Mutex<Option<String>>>),
|
||||||
Count(&'static str),
|
Count(&'static str),
|
||||||
@@ -23,6 +24,7 @@ pub(super) enum GenerationValidationFacts {
|
|||||||
impl GenerationValidationFacts {
|
impl GenerationValidationFacts {
|
||||||
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
||||||
match protocol {
|
match protocol {
|
||||||
|
GenerationEndpoint::Chat => Self::Chat(Arc::default()),
|
||||||
GenerationEndpoint::Responses => Self::Responses(ResponseValidationFacts::default()),
|
GenerationEndpoint::Responses => Self::Responses(ResponseValidationFacts::default()),
|
||||||
GenerationEndpoint::Messages => Self::Messages(Arc::default()),
|
GenerationEndpoint::Messages => Self::Messages(Arc::default()),
|
||||||
GenerationEndpoint::MessageTokenCount => Self::Count("input_tokens"),
|
GenerationEndpoint::MessageTokenCount => Self::Count("input_tokens"),
|
||||||
@@ -33,6 +35,25 @@ impl GenerationValidationFacts {
|
|||||||
|
|
||||||
pub(super) fn observe_event(&self, event: &ProviderEvent) {
|
pub(super) fn observe_event(&self, event: &ProviderEvent) {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chat(id) => {
|
||||||
|
if let Some(wire) = event.wire_event().filter(|wire| {
|
||||||
|
wire.protocol() == gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||||
|
}) {
|
||||||
|
let parsed = wire
|
||||||
|
.raw_json_body()
|
||||||
|
.and_then(|bytes| serde_json::from_slice::<Value>(bytes).ok());
|
||||||
|
if let Some(value) = parsed
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_or_else(|| wire.data())
|
||||||
|
.get("id")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
{
|
||||||
|
id.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.get_or_insert_with(|| value.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Self::Responses(facts) => facts.observe_event(event),
|
Self::Responses(facts) => facts.observe_event(event),
|
||||||
Self::Messages(id) => {
|
Self::Messages(id) => {
|
||||||
if let Some(value) = event
|
if let Some(value) = event
|
||||||
@@ -73,12 +94,29 @@ impl GenerationValidationFacts {
|
|||||||
match self {
|
match self {
|
||||||
Self::Responses(facts) => facts.response_id(),
|
Self::Responses(facts) => facts.response_id(),
|
||||||
Self::Messages(id) => id.lock().ok().and_then(|id| id.clone()),
|
Self::Messages(id) => id.lock().ok().and_then(|id| id.clone()),
|
||||||
|
Self::Chat(id) => id
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.clone(),
|
||||||
Self::Count(_) | Self::GenAi => None,
|
Self::Count(_) | Self::GenAi => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn validate_buffered(&self, bytes: &[u8]) -> Result<(), ()> {
|
pub(super) fn validate_buffered(&self, bytes: &[u8]) -> Result<(), ()> {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chat(id) => {
|
||||||
|
crate::data_plane::chat_completions::delivery::validate_response(bytes)?;
|
||||||
|
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||||
|
if id
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|id| value.get("id").and_then(Value::as_str) != Some(id))
|
||||||
|
{
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Self::Responses(facts) => validate_buffered_response(facts, bytes).map_err(|_| ()),
|
Self::Responses(facts) => validate_buffered_response(facts, bytes).map_err(|_| ()),
|
||||||
Self::Messages(_) => {
|
Self::Messages(_) => {
|
||||||
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
let value: Value = serde_json::from_slice(bytes).map_err(|_| ())?;
|
||||||
@@ -113,6 +151,7 @@ impl GenerationValidationFacts {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(super) enum GenerationDeliveryValidator {
|
pub(super) enum GenerationDeliveryValidator {
|
||||||
|
Chat(crate::data_plane::chat_completions::delivery::ChatDeliveryValidator),
|
||||||
Responses(ResponsesDeliveryValidator),
|
Responses(ResponsesDeliveryValidator),
|
||||||
Messages {
|
Messages {
|
||||||
id: Option<String>,
|
id: Option<String>,
|
||||||
@@ -127,6 +166,7 @@ pub(super) enum GenerationDeliveryValidator {
|
|||||||
impl GenerationDeliveryValidator {
|
impl GenerationDeliveryValidator {
|
||||||
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
pub(super) fn new(protocol: GenerationEndpoint) -> Self {
|
||||||
match protocol {
|
match protocol {
|
||||||
|
GenerationEndpoint::Chat => Self::Chat(Default::default()),
|
||||||
GenerationEndpoint::Responses => Self::Responses(ResponsesDeliveryValidator::default()),
|
GenerationEndpoint::Responses => Self::Responses(ResponsesDeliveryValidator::default()),
|
||||||
GenerationEndpoint::GenAi => Self::GenAi {
|
GenerationEndpoint::GenAi => Self::GenAi {
|
||||||
observation: GenerateContentObservation::default(),
|
observation: GenerateContentObservation::default(),
|
||||||
@@ -141,6 +181,7 @@ impl GenerationDeliveryValidator {
|
|||||||
|
|
||||||
pub(super) fn response_id(&self) -> Option<&str> {
|
pub(super) fn response_id(&self) -> Option<&str> {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chat(validator) => validator.response_id(),
|
||||||
Self::Responses(validator) => validator.response_id(),
|
Self::Responses(validator) => validator.response_id(),
|
||||||
Self::Messages { id, .. } => id.as_deref(),
|
Self::Messages { id, .. } => id.as_deref(),
|
||||||
Self::GenAi { .. } => None,
|
Self::GenAi { .. } => None,
|
||||||
@@ -154,6 +195,18 @@ impl GenerationDeliveryValidator {
|
|||||||
facts: &GenerationValidationFacts,
|
facts: &GenerationValidationFacts,
|
||||||
) -> Result<(), ()> {
|
) -> Result<(), ()> {
|
||||||
match (self, facts) {
|
match (self, facts) {
|
||||||
|
(Self::Chat(validator), GenerationValidationFacts::Chat(id)) => {
|
||||||
|
validator.validate_frame(bytes)?;
|
||||||
|
if validator.response_id().is_some_and(|actual| {
|
||||||
|
id.lock()
|
||||||
|
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|expected| expected != actual)
|
||||||
|
}) {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
(Self::Responses(validator), GenerationValidationFacts::Responses(facts)) => validator
|
(Self::Responses(validator), GenerationValidationFacts::Responses(facts)) => validator
|
||||||
.validate_frame(bytes, transformed, facts)
|
.validate_frame(bytes, transformed, facts)
|
||||||
.map_err(|_| ()),
|
.map_err(|_| ()),
|
||||||
@@ -234,6 +287,7 @@ impl GenerationDeliveryValidator {
|
|||||||
|
|
||||||
pub(super) fn finish_delivery(&self) -> Result<(), ()> {
|
pub(super) fn finish_delivery(&self) -> Result<(), ()> {
|
||||||
match self {
|
match self {
|
||||||
|
Self::Chat(validator) => validator.finish_delivery(),
|
||||||
Self::Responses(validator) => validator.finish_delivery().map_err(|_| ()),
|
Self::Responses(validator) => validator.finish_delivery().map_err(|_| ()),
|
||||||
Self::Messages { finished: true, .. } => Ok(()),
|
Self::Messages { finished: true, .. } => Ok(()),
|
||||||
Self::GenAi {
|
Self::GenAi {
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
//! 数据面入站业务头与上游响应头的公共传输边界
|
||||||
|
|
||||||
|
use axum::http::{HeaderMap, HeaderName, HeaderValue};
|
||||||
|
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||||
|
use gateway_core::event::ProviderResponseHeader;
|
||||||
|
use gateway_protocol::http::is_transport_managed_request_header;
|
||||||
|
use serde_json::{Map, Value};
|
||||||
|
|
||||||
|
/// 出口统一剥离已知账号身份,过滤范围不随客户端选择的协议变化
|
||||||
|
pub(crate) fn response_header_is_forwardable(name: &str, connection_options: &[String]) -> bool {
|
||||||
|
gateway_protocol::http::response_header_is_forwardable(name, connection_options)
|
||||||
|
&& !gateway_protocol::openai::is_private_response_header(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn response_connection_options(headers: &[ProviderResponseHeader]) -> Vec<String> {
|
||||||
|
headers
|
||||||
|
.iter()
|
||||||
|
.filter(|header| header.name().trim().eq_ignore_ascii_case("connection"))
|
||||||
|
.filter_map(|header| std::str::from_utf8(header.value()).ok())
|
||||||
|
.flat_map(|value| value.split(','))
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|name| !name.is_empty())
|
||||||
|
.map(str::to_ascii_lowercase)
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn passthrough_headers(headers: &HeaderMap) -> Vec<Value> {
|
||||||
|
passthrough_request_headers(headers)
|
||||||
|
.map(|(name, value)| {
|
||||||
|
Value::Array(vec![
|
||||||
|
Value::String(name.as_str().to_owned()),
|
||||||
|
Value::String(STANDARD.encode(value.as_bytes())),
|
||||||
|
])
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// HTTP 与 Live 入站共用的身份、传输边界;保留业务头原始多值字节
|
||||||
|
pub(crate) fn passthrough_request_headers(
|
||||||
|
headers: &HeaderMap,
|
||||||
|
) -> impl Iterator<Item = (&HeaderName, &HeaderValue)> {
|
||||||
|
let connection_headers = headers
|
||||||
|
.get_all("connection")
|
||||||
|
.iter()
|
||||||
|
.filter_map(|value| value.to_str().ok())
|
||||||
|
.flat_map(|value| value.split(','))
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|name| !name.is_empty())
|
||||||
|
.map(str::to_ascii_lowercase)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
headers
|
||||||
|
.iter()
|
||||||
|
.filter(move |(name, _)| passthrough_header_name(name.as_str(), &connection_headers))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn passthrough_header_name(name: &str, connection_headers: &[String]) -> bool {
|
||||||
|
if connection_headers
|
||||||
|
.iter()
|
||||||
|
.any(|connection_header| connection_header.eq_ignore_ascii_case(name))
|
||||||
|
|| is_transport_managed_request_header(name)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
!matches!(
|
||||||
|
name,
|
||||||
|
// 下游鉴权和账号 cookie 绝不能成为上游账号身份
|
||||||
|
"authorization"
|
||||||
|
| "x-api-key"
|
||||||
|
| "x-goog-api-key"
|
||||||
|
// Codex 的服务端托管认证标记只用于客户端能力判断,不代表上游身份
|
||||||
|
| "x-openai-actor-authorization"
|
||||||
|
| "cookie"
|
||||||
|
| "cookie2"
|
||||||
|
| "chatgpt-account-id"
|
||||||
|
| "chatgpt-project-id"
|
||||||
|
| "openai-organization"
|
||||||
|
| "openai-project"
|
||||||
|
// 上游指纹必须由运行时画像统一生成,客户端 originator/User-Agent/version
|
||||||
|
// 不能作为不透明头透传覆盖,避免不同下游客户端暴露不一致的设备指纹
|
||||||
|
| "originator"
|
||||||
|
| "user-agent"
|
||||||
|
| "version"
|
||||||
|
// 设备 attestation/integrity 头只能由官方客户端或网关自身生成,
|
||||||
|
// 客户端注入的 x-oai-attestation / X-OAI-IS 不得透传上游
|
||||||
|
| "x-oai-attestation"
|
||||||
|
| "x-oai-is"
|
||||||
|
| "x-oai-is-update"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn header_string(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||||
|
headers
|
||||||
|
.get(name)
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 共享会话头与不透明业务头,不继承 Responses 的续接和连接状态
|
||||||
|
pub(crate) fn session_context(headers: &HeaderMap) -> Map<String, Value> {
|
||||||
|
let mut context = Map::new();
|
||||||
|
for (key, value) in [
|
||||||
|
(
|
||||||
|
"session_id",
|
||||||
|
header_string(headers, "session-id").or_else(|| header_string(headers, "session_id")),
|
||||||
|
),
|
||||||
|
("thread_id", header_string(headers, "thread-id")),
|
||||||
|
(
|
||||||
|
"turn_metadata",
|
||||||
|
header_string(headers, "x-codex-turn-metadata"),
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
if let Some(value) = value {
|
||||||
|
context.insert(key.into(), Value::String(value));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let passthrough = passthrough_headers(headers);
|
||||||
|
if !passthrough.is_empty() {
|
||||||
|
context.insert("opaque_request_headers".into(), Value::Array(passthrough));
|
||||||
|
}
|
||||||
|
context
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ use super::{
|
|||||||
ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest,
|
ContinuationIntent, DecodedGenerationRequest, GenerationEndpoint, GenerationHttpRequest,
|
||||||
GenerationRequestMetadata, execute_prepared_generation,
|
GenerationRequestMetadata, execute_prepared_generation,
|
||||||
},
|
},
|
||||||
responses::OpenAiRequestHeaders,
|
headers::session_context,
|
||||||
};
|
};
|
||||||
use crate::ApiState;
|
use crate::ApiState;
|
||||||
|
|
||||||
@@ -108,7 +108,6 @@ async fn execute(
|
|||||||
middleware_body: body,
|
middleware_body: body,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
@@ -134,7 +133,7 @@ pub(super) fn decode_request(
|
|||||||
};
|
};
|
||||||
validation.map_err(|error| {
|
validation.map_err(|error| {
|
||||||
invalid(match error {
|
invalid(match error {
|
||||||
anthropic::TranslationError::InvalidRequest(message) => message,
|
anthropic::MessageError::InvalidRequest(message) => message,
|
||||||
_ => "Messages request is invalid.",
|
_ => "Messages request is invalid.",
|
||||||
})
|
})
|
||||||
})?;
|
})?;
|
||||||
@@ -148,7 +147,7 @@ pub(super) fn decode_request(
|
|||||||
.get("stream")
|
.get("stream")
|
||||||
.and_then(Value::as_bool)
|
.and_then(Value::as_bool)
|
||||||
.unwrap_or(false);
|
.unwrap_or(false);
|
||||||
let context = OpenAiRequestHeaders::from_headers(headers).session_context();
|
let context = session_context(headers);
|
||||||
let operation = if counted {
|
let operation = if counted {
|
||||||
let payload = RawJsonPayload::new(protocol.wire(), Bytes::copy_from_slice(&body))
|
let payload = RawJsonPayload::new(protocol.wire(), Bytes::copy_from_slice(&body))
|
||||||
.map_err(|_| invalid("Request protocol is invalid."))?
|
.map_err(|_| invalid("Request protocol is invalid."))?
|
||||||
@@ -165,7 +164,6 @@ pub(super) fn decode_request(
|
|||||||
metadata: GenerationRequestMetadata {
|
metadata: GenerationRequestMetadata {
|
||||||
requested_model: model,
|
requested_model: model,
|
||||||
stream,
|
stream,
|
||||||
store: false,
|
|
||||||
continuation: ContinuationIntent::None,
|
continuation: ContinuationIntent::None,
|
||||||
client_ip: None,
|
client_ip: None,
|
||||||
user_agent: None,
|
user_agent: None,
|
||||||
|
|||||||
@@ -62,10 +62,14 @@ impl MiddlewareBody for BufferedBody {
|
|||||||
pub(crate) enum ExpectedBody {
|
pub(crate) enum ExpectedBody {
|
||||||
SingleJson,
|
SingleJson,
|
||||||
SinglePayload,
|
SinglePayload,
|
||||||
Sse,
|
Sse { keep_alive: bool },
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ExpectedBody {
|
impl ExpectedBody {
|
||||||
|
pub(crate) fn sends_keepalive(self) -> bool {
|
||||||
|
matches!(self, Self::Sse { keep_alive: true })
|
||||||
|
}
|
||||||
|
|
||||||
fn validate(self, frame: &MiddlewareFrame) -> Result<(), MiddlewareError> {
|
fn validate(self, frame: &MiddlewareFrame) -> Result<(), MiddlewareError> {
|
||||||
let valid = match self {
|
let valid = match self {
|
||||||
Self::SingleJson => {
|
Self::SingleJson => {
|
||||||
@@ -80,7 +84,7 @@ impl ExpectedBody {
|
|||||||
|| Self::SingleJson.validate(frame).is_ok())
|
|| Self::SingleJson.validate(frame).is_ok())
|
||||||
}
|
}
|
||||||
// 原生超大 SSE 帧允许按原字节片段交付;插件写入边界由 Runtime 校验
|
// 原生超大 SSE 帧允许按原字节片段交付;插件写入边界由 Runtime 校验
|
||||||
Self::Sse => frame.framing() == MiddlewareFraming::SseEvent,
|
Self::Sse { .. } => frame.framing() == MiddlewareFraming::SseEvent,
|
||||||
};
|
};
|
||||||
if valid {
|
if valid {
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -133,14 +137,15 @@ pub(crate) async fn into_http_response(
|
|||||||
})
|
})
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if matches!(expected, ExpectedBody::Sse) {
|
let streaming = matches!(expected, ExpectedBody::Sse { .. });
|
||||||
|
if streaming {
|
||||||
headers.insert(
|
headers.insert(
|
||||||
header::CACHE_CONTROL,
|
header::CACHE_CONTROL,
|
||||||
HeaderValue::from_static("no-cache, no-transform"),
|
HeaderValue::from_static("no-cache, no-transform"),
|
||||||
);
|
);
|
||||||
headers.insert("x-accel-buffering", HeaderValue::from_static("no"));
|
headers.insert("x-accel-buffering", HeaderValue::from_static("no"));
|
||||||
}
|
}
|
||||||
let exhausted = empty || !matches!(expected, ExpectedBody::Sse);
|
let exhausted = empty || !streaming;
|
||||||
if !empty && exhausted {
|
if !empty && exhausted {
|
||||||
match body.next_frame().await {
|
match body.next_frame().await {
|
||||||
Ok(None) => {}
|
Ok(None) => {}
|
||||||
@@ -158,20 +163,24 @@ pub(crate) async fn into_http_response(
|
|||||||
exhausted,
|
exhausted,
|
||||||
terminal_seen: empty,
|
terminal_seen: empty,
|
||||||
};
|
};
|
||||||
let keep_alive = matches!(expected, ExpectedBody::Sse);
|
let stream = futures::stream::try_unfold(delivery, HttpDelivery::next);
|
||||||
let stream = Box::pin(futures::stream::try_unfold(delivery, HttpDelivery::next));
|
let body = if expected.sends_keepalive() {
|
||||||
// 固定同一条输出流;心跳不能取消并重建正在等待的 next_frame 或结算 future
|
// 固定同一条输出流,发送心跳时继续等待原有的读帧或结算操作
|
||||||
let stream = futures::stream::unfold(stream, move |mut stream| async move {
|
Body::from_stream(futures::stream::unfold(
|
||||||
let chunk = tokio::select! {
|
Box::pin(stream),
|
||||||
biased;
|
|mut stream| async move {
|
||||||
chunk = stream.next() => chunk?,
|
let chunk = tokio::select! {
|
||||||
() = tokio::time::sleep(SSE_KEEPALIVE_INTERVAL), if keep_alive => {
|
biased;
|
||||||
Ok(SSE_KEEPALIVE_FRAME)
|
chunk = stream.next() => chunk?,
|
||||||
}
|
() = tokio::time::sleep(SSE_KEEPALIVE_INTERVAL) => Ok(SSE_KEEPALIVE_FRAME),
|
||||||
};
|
};
|
||||||
Some((chunk, stream))
|
Some((chunk, stream))
|
||||||
});
|
},
|
||||||
let mut response = Response::new(Body::from_stream(stream));
|
))
|
||||||
|
} else {
|
||||||
|
Body::from_stream(stream)
|
||||||
|
};
|
||||||
|
let mut response = Response::new(body);
|
||||||
*response.status_mut() = status;
|
*response.status_mut() = status;
|
||||||
*response.headers_mut() = headers;
|
*response.headers_mut() = headers;
|
||||||
response
|
response
|
||||||
|
|||||||
@@ -3,20 +3,19 @@
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod body;
|
pub mod body;
|
||||||
mod chat_completions;
|
mod chat_completions;
|
||||||
|
mod codex;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub(crate) mod genai;
|
pub(crate) mod genai;
|
||||||
pub mod generation;
|
pub mod generation;
|
||||||
pub mod images;
|
mod headers;
|
||||||
pub(crate) mod live;
|
|
||||||
mod messages;
|
mod messages;
|
||||||
pub(crate) mod middleware;
|
pub(crate) mod middleware;
|
||||||
pub mod models;
|
mod models;
|
||||||
mod openai_endpoints;
|
mod openai;
|
||||||
mod peer_link;
|
mod peer_link;
|
||||||
mod provider_endpoints;
|
mod provider_endpoints;
|
||||||
pub mod responses;
|
pub mod responses;
|
||||||
pub mod router;
|
pub(crate) mod router;
|
||||||
pub mod search;
|
|
||||||
pub(crate) mod service;
|
pub(crate) mod service;
|
||||||
mod usage;
|
mod usage;
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,7 @@ use axum::{
|
|||||||
http::{HeaderMap, StatusCode},
|
http::{HeaderMap, StatusCode},
|
||||||
response::{IntoResponse, Response},
|
response::{IntoResponse, Response},
|
||||||
};
|
};
|
||||||
use gateway_core::{
|
use gateway_core::{engine::execution::AuthenticatedClient, routing::PublicModelId};
|
||||||
engine::execution::AuthenticatedClient,
|
|
||||||
routing::{PublicModelDescriptor, PublicModelId, PublicModelProfile},
|
|
||||||
};
|
|
||||||
use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
|
use gateway_protocol::anthropic::ANTHROPIC_PROTOCOL;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
@@ -25,7 +22,6 @@ use super::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
const MODEL_CREATED_TIMESTAMP: i64 = 1_700_000_000;
|
const MODEL_CREATED_TIMESTAMP: i64 = 1_700_000_000;
|
||||||
const CODEX_BASE_INSTRUCTIONS: &str = "You are Codex, a coding agent. Follow the user's instructions and use the available tools to complete software engineering tasks. Inspect relevant files before editing, preserve unrelated changes, and verify the result.";
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
pub(crate) struct ModelsQuery {
|
pub(crate) struct ModelsQuery {
|
||||||
@@ -78,60 +74,7 @@ async fn models_response(
|
|||||||
.as_deref()
|
.as_deref()
|
||||||
.filter(|version| !version.trim().is_empty())
|
.filter(|version| !version.trim().is_empty())
|
||||||
{
|
{
|
||||||
if version.len() > 64
|
return super::codex::model_catalog(service, &client, version).await;
|
||||||
|| !version
|
|
||||||
.bytes()
|
|
||||||
.all(|byte| byte.is_ascii_alphanumeric() || b".-+".contains(&byte))
|
|
||||||
{
|
|
||||||
return openai_error_response(
|
|
||||||
StatusCode::BAD_REQUEST,
|
|
||||||
"Invalid client_version.",
|
|
||||||
"invalid_request_error",
|
|
||||||
"invalid_client_version",
|
|
||||||
)
|
|
||||||
.into_response();
|
|
||||||
}
|
|
||||||
let catalog = match service.client_model_catalog(&client, version).await {
|
|
||||||
Ok(catalog) => catalog,
|
|
||||||
Err(_) => return catalog_unavailable_response(),
|
|
||||||
};
|
|
||||||
let models = catalog
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(index, entry)| match entry {
|
|
||||||
PublicModelDescriptor::Adapted(profile) => {
|
|
||||||
Ok(adapted_codex_model_json(profile, index))
|
|
||||||
}
|
|
||||||
PublicModelDescriptor::Native { model, payload } => {
|
|
||||||
if payload.protocol() != "codex" {
|
|
||||||
return Err(());
|
|
||||||
}
|
|
||||||
let mut value: Value =
|
|
||||||
serde_json::from_slice(payload.body()).map_err(|_| ())?;
|
|
||||||
let object = value.as_object_mut().ok_or(())?;
|
|
||||||
// 别名只改变请求标识,能力、提示词、顺序等仍由上游目录决定
|
|
||||||
object.insert("slug".to_owned(), Value::String(model.as_str().to_owned()));
|
|
||||||
Ok(value)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect::<Result<Vec<_>, ()>>();
|
|
||||||
let Ok(mut models) = models else {
|
|
||||||
return catalog_unavailable_response();
|
|
||||||
};
|
|
||||||
if !client.policy().account_scope().allows_subagents() {
|
|
||||||
for model in &mut models {
|
|
||||||
model["multi_agent_version"] = json!("disabled");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return (
|
|
||||||
StatusCode::OK,
|
|
||||||
// 目录经过账号选择/别名/多 Provider 聚合,不能借用上游 ETag 表示改写后的正文
|
|
||||||
[("cache-control", "private, no-store")],
|
|
||||||
Json(json!({
|
|
||||||
"models": models,
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.into_response();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let data = service
|
let data = service
|
||||||
@@ -149,16 +92,6 @@ async fn models_response(
|
|||||||
.into_response()
|
.into_response()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn catalog_unavailable_response() -> Response {
|
|
||||||
openai_error_response(
|
|
||||||
StatusCode::SERVICE_UNAVAILABLE,
|
|
||||||
"Model catalog is temporarily unavailable.",
|
|
||||||
"server_error",
|
|
||||||
"model_catalog_unavailable",
|
|
||||||
)
|
|
||||||
.into_response()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `GET /v1/models/{model_id}`
|
/// `GET /v1/models/{model_id}`
|
||||||
pub(crate) async fn model_detail(
|
pub(crate) async fn model_detail(
|
||||||
State(state): State<ApiState>,
|
State(state): State<ApiState>,
|
||||||
@@ -285,92 +218,3 @@ fn openai_model_json(id: &str) -> Value {
|
|||||||
"owned_by": "gateway",
|
"owned_by": "gateway",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn adapted_codex_model_json(profile: &PublicModelProfile, index: usize) -> Value {
|
|
||||||
let id = profile.model().as_str();
|
|
||||||
let presentation = profile.presentation();
|
|
||||||
let reasoning_levels = presentation
|
|
||||||
.supported_reasoning_efforts()
|
|
||||||
.iter()
|
|
||||||
.map(|effort| {
|
|
||||||
json!({
|
|
||||||
"effort": effort,
|
|
||||||
"description": reasoning_effort_description(effort),
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let reasoning_summary = presentation.reasoning_summary();
|
|
||||||
let context_window = presentation.context_window_tokens();
|
|
||||||
let max_context_window = presentation.max_context_window_tokens();
|
|
||||||
let input_modalities = if presentation.image_input() {
|
|
||||||
vec!["text", "image"]
|
|
||||||
} else {
|
|
||||||
vec!["text"]
|
|
||||||
};
|
|
||||||
let additional_speed_tiers = presentation
|
|
||||||
.service_tiers()
|
|
||||||
.iter()
|
|
||||||
.filter_map(|tier| tier.speed_tier())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let service_tiers = presentation
|
|
||||||
.service_tiers()
|
|
||||||
.iter()
|
|
||||||
.map(|tier| {
|
|
||||||
json!({
|
|
||||||
"id": tier.id(),
|
|
||||||
"name": tier.name(),
|
|
||||||
"description": tier.description(),
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
json!({
|
|
||||||
"slug": id,
|
|
||||||
"display_name": presentation.display_name().unwrap_or(id),
|
|
||||||
"description": presentation.description(),
|
|
||||||
"default_reasoning_level": presentation.default_reasoning_effort(),
|
|
||||||
"supported_reasoning_levels": reasoning_levels,
|
|
||||||
"shell_type": "shell_command",
|
|
||||||
"visibility": if presentation.hidden() { "hide" } else { "list" },
|
|
||||||
"supported_in_api": true,
|
|
||||||
"priority": index.saturating_add(1),
|
|
||||||
"additional_speed_tiers": additional_speed_tiers,
|
|
||||||
"service_tiers": service_tiers,
|
|
||||||
"availability_nux": Value::Null,
|
|
||||||
"upgrade": Value::Null,
|
|
||||||
"base_instructions": CODEX_BASE_INSTRUCTIONS,
|
|
||||||
"model_messages": Value::Null,
|
|
||||||
"include_skills_usage_instructions": false,
|
|
||||||
"supports_reasoning_summary_parameter": reasoning_summary,
|
|
||||||
"default_reasoning_summary": if reasoning_summary { "auto" } else { "none" },
|
|
||||||
"support_verbosity": presentation.verbosity(),
|
|
||||||
"default_verbosity": Value::Null,
|
|
||||||
"apply_patch_tool_type": presentation.agent_tools().then_some("freeform"),
|
|
||||||
"web_search_tool_type": "text",
|
|
||||||
"truncation_policy": { "mode": "tokens", "limit": 10_000 },
|
|
||||||
"supports_parallel_tool_calls": presentation.parallel_tool_calls(),
|
|
||||||
"supports_image_detail_original": presentation.image_detail_original(),
|
|
||||||
"context_window": context_window,
|
|
||||||
"max_context_window": max_context_window,
|
|
||||||
"effective_context_window_percent": 95,
|
|
||||||
"experimental_supported_tools": [],
|
|
||||||
"input_modalities": input_modalities,
|
|
||||||
"supports_search_tool": presentation.search_tool(),
|
|
||||||
// 通用画像没有 Responses Lite 支持依据,避免客户端启用未经声明的协议行为
|
|
||||||
// 原生目录由 Native 分支保留上游字段,不经过此处
|
|
||||||
"use_responses_lite": false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn reasoning_effort_description(effort: &str) -> &'static str {
|
|
||||||
match effort {
|
|
||||||
"none" => "No reasoning",
|
|
||||||
"minimal" => "Minimal reasoning",
|
|
||||||
"low" => "Fast responses with lighter reasoning",
|
|
||||||
"medium" => "Balances speed and reasoning depth for everyday tasks",
|
|
||||||
"high" => "Greater reasoning depth for complex problems",
|
|
||||||
"xhigh" => "Extra high reasoning depth for complex problems",
|
|
||||||
"max" => "Maximum reasoning depth for the hardest problems",
|
|
||||||
_ => "Provider-supported reasoning level",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
+9
-5
@@ -36,7 +36,7 @@ use crate::data_plane::middleware::{
|
|||||||
use crate::middleware::headers::encode_headers;
|
use crate::middleware::headers::encode_headers;
|
||||||
use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
use gateway_core::event::{ProviderEvent, ProviderResponseHeader};
|
||||||
|
|
||||||
use super::{
|
use crate::data_plane::{
|
||||||
error::{engine_error_response, gateway_error_response, protocol_error_response},
|
error::{engine_error_response, gateway_error_response, protocol_error_response},
|
||||||
service::DataPlaneService,
|
service::DataPlaneService,
|
||||||
};
|
};
|
||||||
@@ -142,7 +142,7 @@ where
|
|||||||
let mut response = if response.headers().contains_key("x-gateway-request-id") {
|
let mut response = if response.headers().contains_key("x-gateway-request-id") {
|
||||||
response
|
response
|
||||||
} else {
|
} else {
|
||||||
super::with_model_request_id(response, &request_id)
|
crate::data_plane::with_model_request_id(response, &request_id)
|
||||||
};
|
};
|
||||||
response
|
response
|
||||||
.extensions_mut()
|
.extensions_mut()
|
||||||
@@ -176,7 +176,7 @@ async fn collect_raw_json_response(
|
|||||||
},
|
},
|
||||||
Err(error) => engine_error_response(&error),
|
Err(error) => engine_error_response(&error),
|
||||||
};
|
};
|
||||||
let response = super::with_model_request_id(response, &started.request_id);
|
let response = crate::data_plane::with_model_request_id(response, &started.request_id);
|
||||||
let (parts, body) = response.into_parts();
|
let (parts, body) = response.into_parts();
|
||||||
let framing = if parts.status.is_success() {
|
let framing = if parts.status.is_success() {
|
||||||
MiddlewareFraming::JsonDocument
|
MiddlewareFraming::JsonDocument
|
||||||
@@ -229,9 +229,13 @@ fn apply_response_headers(
|
|||||||
mut response: Response,
|
mut response: Response,
|
||||||
response_headers: &[ProviderResponseHeader],
|
response_headers: &[ProviderResponseHeader],
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let connection_options = super::responses::response_connection_options(response_headers);
|
let connection_options =
|
||||||
|
crate::data_plane::headers::response_connection_options(response_headers);
|
||||||
for header in response_headers {
|
for header in response_headers {
|
||||||
if !super::responses::response_header_is_forwardable(header.name(), &connection_options) {
|
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||||
|
header.name(),
|
||||||
|
&connection_options,
|
||||||
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
||||||
+4
-4
@@ -21,9 +21,9 @@ use crate::ApiState;
|
|||||||
use crate::data_plane::middleware::RequestInput;
|
use crate::data_plane::middleware::RequestInput;
|
||||||
use crate::data_plane::{
|
use crate::data_plane::{
|
||||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||||
openai_endpoints::provider_endpoint_response,
|
headers::session_context,
|
||||||
responses::OpenAiRequestHeaders,
|
openai::endpoints::provider_endpoint_response,
|
||||||
router::{IMAGE_EDITS_PATH, IMAGE_GENERATIONS_PATH},
|
openai::{IMAGE_EDITS_PATH, IMAGE_GENERATIONS_PATH},
|
||||||
};
|
};
|
||||||
use crate::middleware::headers::encode_headers;
|
use crate::middleware::headers::encode_headers;
|
||||||
|
|
||||||
@@ -111,7 +111,7 @@ async fn image_operation(
|
|||||||
} else {
|
} else {
|
||||||
body
|
body
|
||||||
};
|
};
|
||||||
let mut context = OpenAiRequestHeaders::from_headers(&headers).session_context();
|
let mut context = session_context(&headers);
|
||||||
if let Some(turn_id) = headers
|
if let Some(turn_id) = headers
|
||||||
.get("x-codex-image-turn-id")
|
.get("x-codex-image-turn-id")
|
||||||
.and_then(|value| value.to_str().ok())
|
.and_then(|value| value.to_str().ok())
|
||||||
+3
-3
@@ -131,7 +131,7 @@ pub(crate) fn realtime_unsupported_response(capability: &str) -> Response {
|
|||||||
|
|
||||||
/// 共用 OpenAI 入站头边界;Content-Type 由正文适配结果单独提供
|
/// 共用 OpenAI 入站头边界;Content-Type 由正文适配结果单独提供
|
||||||
pub(crate) fn filter_protocol_headers(headers: &HeaderMap) -> Vec<ProviderHttpHeader> {
|
pub(crate) fn filter_protocol_headers(headers: &HeaderMap) -> Vec<ProviderHttpHeader> {
|
||||||
super::responses::passthrough_request_headers(headers)
|
crate::data_plane::headers::passthrough_request_headers(headers)
|
||||||
.filter(|(name, _)| *name != header::CONTENT_TYPE)
|
.filter(|(name, _)| *name != header::CONTENT_TYPE)
|
||||||
.map(|(name, value)| {
|
.map(|(name, value)| {
|
||||||
ProviderHttpHeader::new(name.as_str(), Bytes::copy_from_slice(value.as_bytes()))
|
ProviderHttpHeader::new(name.as_str(), Bytes::copy_from_slice(value.as_bytes()))
|
||||||
@@ -268,12 +268,12 @@ pub(crate) fn encode_call_request(
|
|||||||
pub(crate) fn live_forwarded_response_headers(
|
pub(crate) fn live_forwarded_response_headers(
|
||||||
headers: &[ProviderResponseHeader],
|
headers: &[ProviderResponseHeader],
|
||||||
) -> Vec<(HeaderName, HeaderValue)> {
|
) -> Vec<(HeaderName, HeaderValue)> {
|
||||||
let connection_options = super::responses::response_connection_options(headers);
|
let connection_options = crate::data_plane::headers::response_connection_options(headers);
|
||||||
headers
|
headers
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|header| {
|
.filter(|header| {
|
||||||
header.name().eq_ignore_ascii_case("content-type")
|
header.name().eq_ignore_ascii_case("content-type")
|
||||||
|| super::responses::response_header_is_forwardable(
|
|| crate::data_plane::headers::response_header_is_forwardable(
|
||||||
header.name(),
|
header.name(),
|
||||||
&connection_options,
|
&connection_options,
|
||||||
)
|
)
|
||||||
+1
-1
@@ -24,7 +24,7 @@ use crate::{
|
|||||||
data_plane::{
|
data_plane::{
|
||||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||||
error::runtime_unavailable_response,
|
error::runtime_unavailable_response,
|
||||||
live::{
|
openai::live::{
|
||||||
filter_protocol_headers, live_error_response, offered_subprotocols,
|
filter_protocol_headers, live_error_response, offered_subprotocols,
|
||||||
realtime_unsupported_response,
|
realtime_unsupported_response,
|
||||||
},
|
},
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
//! 绑定 OpenAI Provider 的 Images、独立搜索与 Live 客户端入口
|
||||||
|
|
||||||
|
mod endpoints;
|
||||||
|
mod images;
|
||||||
|
mod live;
|
||||||
|
mod search;
|
||||||
|
|
||||||
|
use axum::{Router, routing::post};
|
||||||
|
|
||||||
|
pub(crate) const IMAGE_GENERATIONS_PATH: &str = "/v1/images/generations";
|
||||||
|
pub(crate) const IMAGE_EDITS_PATH: &str = "/v1/images/edits";
|
||||||
|
pub(crate) const SEARCH_PATH: &str = "/v1/alpha/search";
|
||||||
|
|
||||||
|
pub(crate) fn router() -> Router<crate::ApiState> {
|
||||||
|
Router::new()
|
||||||
|
.route(IMAGE_GENERATIONS_PATH, post(images::image_generations))
|
||||||
|
.route(IMAGE_EDITS_PATH, post(images::image_edits))
|
||||||
|
.route(SEARCH_PATH, post(search::standalone_search))
|
||||||
|
.merge(live::router())
|
||||||
|
}
|
||||||
+4
-4
@@ -18,9 +18,9 @@ use crate::ApiState;
|
|||||||
use crate::data_plane::middleware::RequestInput;
|
use crate::data_plane::middleware::RequestInput;
|
||||||
use crate::data_plane::{
|
use crate::data_plane::{
|
||||||
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
auth::{ClientKeyHeaders, authenticate_client, client_access_error_response},
|
||||||
openai_endpoints::provider_endpoint_response,
|
headers::session_context,
|
||||||
responses::OpenAiRequestHeaders,
|
openai::SEARCH_PATH,
|
||||||
router::SEARCH_PATH,
|
openai::endpoints::provider_endpoint_response,
|
||||||
};
|
};
|
||||||
use crate::middleware::headers::encode_headers;
|
use crate::middleware::headers::encode_headers;
|
||||||
|
|
||||||
@@ -60,7 +60,7 @@ pub(crate) async fn standalone_search(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn search_operation(body: Bytes, headers: &HeaderMap) -> Result<Operation, GatewayError> {
|
fn search_operation(body: Bytes, headers: &HeaderMap) -> Result<Operation, GatewayError> {
|
||||||
let context = OpenAiRequestHeaders::from_headers(headers).session_context();
|
let context = session_context(headers);
|
||||||
let payload = RawJsonPayload::new(OPENAI_PROTOCOL, body)
|
let payload = RawJsonPayload::new(OPENAI_PROTOCOL, body)
|
||||||
.map_err(|_| {
|
.map_err(|_| {
|
||||||
GatewayError::new(
|
GatewayError::new(
|
||||||
@@ -17,7 +17,7 @@ use gateway_protocol::peer::{MAX_ACCOUNTS, MAX_MODELS, MAX_QUOTA_WINDOWS, MAX_RE
|
|||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
auth::{client_access_error_response, verify_client},
|
auth::{ClientKeyHeaders, client_access_error_response, verify_client},
|
||||||
error::{missing_client_api_key_response, openai_error_response},
|
error::{missing_client_api_key_response, openai_error_response},
|
||||||
};
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -36,7 +36,7 @@ pub(super) fn router() -> Router<ApiState> {
|
|||||||
struct PeerQuery {}
|
struct PeerQuery {}
|
||||||
|
|
||||||
async fn peer_link(State(state): State<ApiState>, headers: HeaderMap, uri: Uri) -> Response {
|
async fn peer_link(State(state): State<ApiState>, headers: HeaderMap, uri: Uri) -> Response {
|
||||||
let client = match verify_client(state.data_plane(), &headers).await {
|
let client = match verify_client(state.data_plane(), &headers, ClientKeyHeaders::Bearer).await {
|
||||||
Ok(client) => client,
|
Ok(client) => client,
|
||||||
Err(error) => return client_access_error_response(error.into()),
|
Err(error) => return client_access_error_response(error.into()),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -57,7 +57,6 @@ pub(crate) async fn responses(
|
|||||||
middleware_body,
|
middleware_body,
|
||||||
},
|
},
|
||||||
None,
|
None,
|
||||||
None,
|
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,28 +8,10 @@ pub(in crate::data_plane) mod validation;
|
|||||||
pub mod websocket;
|
pub mod websocket;
|
||||||
|
|
||||||
pub use crate::client_error::{ProtocolError, ProtocolErrorBody};
|
pub use crate::client_error::{ProtocolError, ProtocolErrorBody};
|
||||||
pub use crate::data_plane::generation::http::{
|
|
||||||
collect_execution_response, stream_execution_response,
|
|
||||||
};
|
|
||||||
pub use error::ResponseEncodeError;
|
pub use error::ResponseEncodeError;
|
||||||
pub(crate) use http::responses;
|
pub(crate) use http::responses;
|
||||||
|
pub(crate) use request::decode_request_with_body;
|
||||||
pub use request::{OpenAiRequestHeaders, decode_request_with_headers};
|
pub use request::{OpenAiRequestHeaders, decode_request_with_headers};
|
||||||
pub(crate) use request::{decode_request_with_body, passthrough_request_headers};
|
|
||||||
pub use response::OpenAiResponsesEncoder;
|
pub use response::OpenAiResponsesEncoder;
|
||||||
pub(crate) use websocket::responses_websocket;
|
pub(crate) use websocket::responses_websocket;
|
||||||
pub use websocket::{ResponseCreateFrameError, decode_response_create_with_context};
|
pub use websocket::{ResponseCreateFrameError, decode_response_create_with_context};
|
||||||
|
|
||||||
use gateway_core::event::ProviderResponseHeader;
|
|
||||||
pub(super) use gateway_protocol::openai::response_header_is_forwardable;
|
|
||||||
|
|
||||||
pub(super) fn response_connection_options(headers: &[ProviderResponseHeader]) -> Vec<String> {
|
|
||||||
headers
|
|
||||||
.iter()
|
|
||||||
.filter(|header| header.name().trim().eq_ignore_ascii_case("connection"))
|
|
||||||
.filter_map(|header| std::str::from_utf8(header.value()).ok())
|
|
||||||
.flat_map(|value| value.split(','))
|
|
||||||
.map(str::trim)
|
|
||||||
.filter(|name| !name.is_empty())
|
|
||||||
.map(str::to_ascii_lowercase)
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,16 +1,13 @@
|
|||||||
//! OpenAI Responses JSON 到 Core 路由事实与不透明 wire payload 的单一解码边界
|
//! OpenAI Responses JSON 到 Core 路由事实与不透明 wire payload 的单一解码边界
|
||||||
|
|
||||||
use crate::data_plane::body::decompress_request_body;
|
use crate::data_plane::body::decompress_request_body;
|
||||||
|
use crate::data_plane::codex::CodexRequestHeaders;
|
||||||
|
use crate::data_plane::headers::{header_string, passthrough_headers};
|
||||||
|
|
||||||
use axum::http::{HeaderMap, HeaderName, HeaderValue};
|
use axum::http::HeaderMap;
|
||||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use gateway_core::operation::{ClientTurn, GenerateRequest, Operation, ProtocolPayload};
|
use gateway_core::operation::{GenerateRequest, Operation, ProtocolPayload};
|
||||||
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
use gateway_protocol::openai::OPENAI_PROTOCOL;
|
||||||
use gateway_protocol::openai::{
|
|
||||||
X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER, X_OPENAI_MEMGEN_REQUEST_HEADER,
|
|
||||||
is_transport_managed_request_header,
|
|
||||||
};
|
|
||||||
use serde_json::{Map, Value};
|
use serde_json::{Map, Value};
|
||||||
|
|
||||||
use crate::data_plane::body::RequestDecodeError;
|
use crate::data_plane::body::RequestDecodeError;
|
||||||
@@ -18,7 +15,6 @@ use crate::data_plane::generation::{
|
|||||||
ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata,
|
ContinuationIntent, DecodedGenerationRequest, GenerationRequestMetadata,
|
||||||
};
|
};
|
||||||
|
|
||||||
const OPENAI_SUBAGENT_KEY: &str = "x-openai-subagent";
|
|
||||||
const PASSTHROUGH_HEADERS_CONTEXT_KEY: &str = "opaque_request_headers";
|
const PASSTHROUGH_HEADERS_CONTEXT_KEY: &str = "opaque_request_headers";
|
||||||
const DOWNSTREAM_WEBSOCKET_CONNECTION_ID_CONTEXT_KEY: &str = "downstream_websocket_connection_id";
|
const DOWNSTREAM_WEBSOCKET_CONNECTION_ID_CONTEXT_KEY: &str = "downstream_websocket_connection_id";
|
||||||
|
|
||||||
@@ -33,24 +29,14 @@ pub(super) enum RequestDecodeSource {
|
|||||||
|
|
||||||
#[derive(Clone, Default)]
|
#[derive(Clone, Default)]
|
||||||
pub struct OpenAiRequestHeaders {
|
pub struct OpenAiRequestHeaders {
|
||||||
guardian: Option<String>,
|
codex: CodexRequestHeaders,
|
||||||
ambiguous_guardian_headers: bool,
|
|
||||||
turn_state: Option<String>,
|
|
||||||
turn_metadata: Option<String>,
|
|
||||||
version: Option<String>,
|
|
||||||
codex_window_id: Option<String>,
|
|
||||||
parent_thread_id: Option<String>,
|
|
||||||
downstream_websocket_connection_id: Option<String>,
|
downstream_websocket_connection_id: Option<String>,
|
||||||
|
|
||||||
conversation_id: Option<String>,
|
conversation_id: Option<String>,
|
||||||
session_id: Option<String>,
|
session_id: Option<String>,
|
||||||
thread_id: Option<String>,
|
thread_id: Option<String>,
|
||||||
client_request_id: Option<String>,
|
client_request_id: Option<String>,
|
||||||
turn_id: Option<String>,
|
|
||||||
|
|
||||||
responses_lite: Option<String>,
|
|
||||||
memgen_request: Option<String>,
|
|
||||||
subagent: Option<String>,
|
|
||||||
passthrough_headers: Vec<Value>,
|
passthrough_headers: Vec<Value>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,22 +45,7 @@ impl OpenAiRequestHeaders {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn from_headers(headers: &HeaderMap) -> Self {
|
pub fn from_headers(headers: &HeaderMap) -> Self {
|
||||||
Self {
|
Self {
|
||||||
guardian: header_string(headers, "x-codex-guardian"),
|
codex: CodexRequestHeaders::from_headers(headers),
|
||||||
ambiguous_guardian_headers: [
|
|
||||||
"x-codex-guardian",
|
|
||||||
OPENAI_SUBAGENT_KEY,
|
|
||||||
"x-codex-turn-metadata",
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.any(|name| {
|
|
||||||
let mut values = headers.get_all(name).iter();
|
|
||||||
values.next().is_some_and(|v| v.to_str().is_err()) || values.next().is_some()
|
|
||||||
}),
|
|
||||||
turn_state: header_string(headers, "x-codex-turn-state"),
|
|
||||||
turn_metadata: header_string(headers, "x-codex-turn-metadata"),
|
|
||||||
version: header_string(headers, "version"),
|
|
||||||
codex_window_id: header_string(headers, "x-codex-window-id"),
|
|
||||||
parent_thread_id: header_string(headers, "x-codex-parent-thread-id"),
|
|
||||||
downstream_websocket_connection_id: None,
|
downstream_websocket_connection_id: None,
|
||||||
conversation_id: header_string(headers, "conversation-id")
|
conversation_id: header_string(headers, "conversation-id")
|
||||||
.or_else(|| header_string(headers, "conversation_id")),
|
.or_else(|| header_string(headers, "conversation_id")),
|
||||||
@@ -82,10 +53,6 @@ impl OpenAiRequestHeaders {
|
|||||||
.or_else(|| header_string(headers, "session_id")),
|
.or_else(|| header_string(headers, "session_id")),
|
||||||
thread_id: header_string(headers, "thread-id"),
|
thread_id: header_string(headers, "thread-id"),
|
||||||
client_request_id: header_string(headers, "x-client-request-id"),
|
client_request_id: header_string(headers, "x-client-request-id"),
|
||||||
turn_id: header_string(headers, "x-codex-turn-id"),
|
|
||||||
responses_lite: header_string(headers, X_OPENAI_INTERNAL_CODEX_RESPONSES_LITE_HEADER),
|
|
||||||
memgen_request: header_string(headers, X_OPENAI_MEMGEN_REQUEST_HEADER),
|
|
||||||
subagent: header_string(headers, OPENAI_SUBAGENT_KEY),
|
|
||||||
passthrough_headers: passthrough_headers(headers),
|
passthrough_headers: passthrough_headers(headers),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,61 +67,6 @@ impl OpenAiRequestHeaders {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_subagent(
|
|
||||||
&self,
|
|
||||||
body: &mut Map<String, Value>,
|
|
||||||
context: &mut Map<String, Value>,
|
|
||||||
source: RequestDecodeSource,
|
|
||||||
) {
|
|
||||||
if matches!(source, RequestDecodeSource::WebSocketFrame)
|
|
||||||
&& let Some(frame_agent) = body
|
|
||||||
.get("client_metadata")
|
|
||||||
.and_then(|m| m.get(OPENAI_SUBAGENT_KEY))
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
&& (frame_agent == "guardian"
|
|
||||||
|| self.subagent.as_deref() == Some("guardian")
|
|
||||||
|| self.guardian.is_some())
|
|
||||||
{
|
|
||||||
// 帧内声明优先;旧 opening 的不透明副本也不能在 Provider 再度覆盖
|
|
||||||
let stale_subagent = self
|
|
||||||
.subagent
|
|
||||||
.as_deref()
|
|
||||||
.is_some_and(|opening| opening != frame_agent);
|
|
||||||
let stale_guardian = self.guardian.as_deref().is_some_and(|opening| {
|
|
||||||
frame_agent != "guardian"
|
|
||||||
|| gateway_protocol::openai::codex_guardian_role(body, context)
|
|
||||||
.is_some_and(|role| role.header() != Some(opening))
|
|
||||||
});
|
|
||||||
if stale_subagent {
|
|
||||||
context.insert("subagent".into(), Value::from(frame_agent));
|
|
||||||
}
|
|
||||||
if (stale_subagent || stale_guardian)
|
|
||||||
&& let Some(Value::Array(headers)) =
|
|
||||||
context.get_mut(PASSTHROUGH_HEADERS_CONTEXT_KEY)
|
|
||||||
{
|
|
||||||
headers.retain(|pair| match pair.get(0).and_then(Value::as_str) {
|
|
||||||
Some(OPENAI_SUBAGENT_KEY) => !stale_subagent,
|
|
||||||
Some("x-codex-guardian") => !stale_guardian,
|
|
||||||
_ => true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if let Some(subagent) = self.subagent.as_deref() {
|
|
||||||
inject_subagent_metadata(body, subagent);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 独立端点保留业务扩展头与会话身份,不携带 Responses 的连接状态
|
|
||||||
pub(crate) fn session_context(&self) -> Map<String, Value> {
|
|
||||||
let mut context = Map::new();
|
|
||||||
insert_protocol_context(&mut context, "session_id", self.session_id.as_ref());
|
|
||||||
insert_protocol_context(&mut context, "thread_id", self.thread_id.as_ref());
|
|
||||||
insert_protocol_context(&mut context, "turn_metadata", self.turn_metadata.as_ref());
|
|
||||||
self.insert_passthrough_headers(&mut context);
|
|
||||||
context
|
|
||||||
}
|
|
||||||
|
|
||||||
fn insert_passthrough_headers(&self, context: &mut Map<String, Value>) {
|
fn insert_passthrough_headers(&self, context: &mut Map<String, Value>) {
|
||||||
if !self.passthrough_headers.is_empty() {
|
if !self.passthrough_headers.is_empty() {
|
||||||
context.insert(
|
context.insert(
|
||||||
@@ -170,26 +82,13 @@ impl OpenAiRequestHeaders {
|
|||||||
source: RequestDecodeSource,
|
source: RequestDecodeSource,
|
||||||
) -> Map<String, Value> {
|
) -> Map<String, Value> {
|
||||||
let mut context = Map::new();
|
let mut context = Map::new();
|
||||||
insert_protocol_context(&mut context, "turn_state", self.turn_state.as_ref());
|
self.codex.append_context(&mut context);
|
||||||
insert_protocol_context(&mut context, "turn_metadata", self.turn_metadata.as_ref());
|
|
||||||
insert_protocol_context(&mut context, "subagent", self.subagent.as_ref());
|
|
||||||
if matches!(source, RequestDecodeSource::WebSocketFrame) {
|
if matches!(source, RequestDecodeSource::WebSocketFrame) {
|
||||||
context.insert(
|
context.insert(
|
||||||
gateway_protocol::openai::WEBSOCKET_FRAME_CONTEXT_KEY.to_owned(),
|
gateway_protocol::openai::WEBSOCKET_FRAME_CONTEXT_KEY.to_owned(),
|
||||||
Value::Bool(true),
|
Value::Bool(true),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
insert_protocol_context(&mut context, "version", self.version.as_ref());
|
|
||||||
insert_protocol_context(
|
|
||||||
&mut context,
|
|
||||||
"codex_window_id",
|
|
||||||
self.codex_window_id.as_ref(),
|
|
||||||
);
|
|
||||||
insert_protocol_context(
|
|
||||||
&mut context,
|
|
||||||
"parent_thread_id",
|
|
||||||
self.parent_thread_id.as_ref(),
|
|
||||||
);
|
|
||||||
insert_protocol_context(
|
insert_protocol_context(
|
||||||
&mut context,
|
&mut context,
|
||||||
DOWNSTREAM_WEBSOCKET_CONNECTION_ID_CONTEXT_KEY,
|
DOWNSTREAM_WEBSOCKET_CONNECTION_ID_CONTEXT_KEY,
|
||||||
@@ -207,9 +106,6 @@ impl OpenAiRequestHeaders {
|
|||||||
"client_request_id",
|
"client_request_id",
|
||||||
self.client_request_id.as_ref(),
|
self.client_request_id.as_ref(),
|
||||||
);
|
);
|
||||||
insert_protocol_context(&mut context, "turn_id", self.turn_id.as_ref());
|
|
||||||
insert_protocol_context(&mut context, "responses_lite", self.responses_lite.as_ref());
|
|
||||||
insert_protocol_context(&mut context, "memgen_request", self.memgen_request.as_ref());
|
|
||||||
self.insert_passthrough_headers(&mut context);
|
self.insert_passthrough_headers(&mut context);
|
||||||
if let Some(use_websocket) = use_websocket {
|
if let Some(use_websocket) = use_websocket {
|
||||||
context.insert("use_websocket".to_owned(), Value::Bool(use_websocket));
|
context.insert("use_websocket".to_owned(), Value::Bool(use_websocket));
|
||||||
@@ -288,10 +184,6 @@ pub(super) fn decode_request_object(
|
|||||||
Some(value) => value.as_bool().unwrap_or(true),
|
Some(value) => value.as_bool().unwrap_or(true),
|
||||||
None => matches!(source, RequestDecodeSource::WebSocketFrame),
|
None => matches!(source, RequestDecodeSource::WebSocketFrame),
|
||||||
};
|
};
|
||||||
let store = object
|
|
||||||
.get("store")
|
|
||||||
.and_then(Value::as_bool)
|
|
||||||
.unwrap_or(false);
|
|
||||||
let continuation = object
|
let continuation = object
|
||||||
.get("previous_response_id")
|
.get("previous_response_id")
|
||||||
.and_then(Value::as_str)
|
.and_then(Value::as_str)
|
||||||
@@ -299,29 +191,11 @@ pub(super) fn decode_request_object(
|
|||||||
.unwrap_or(ContinuationIntent::None);
|
.unwrap_or(ContinuationIntent::None);
|
||||||
|
|
||||||
let mut protocol_context = request_headers.protocol_context(use_websocket, source);
|
let mut protocol_context = request_headers.protocol_context(use_websocket, source);
|
||||||
gateway_protocol::openai::capture_codex_guardian_identity(
|
let client_turn = request_headers.codex.apply(
|
||||||
&object,
|
&mut object,
|
||||||
&mut protocol_context,
|
&mut protocol_context,
|
||||||
request_headers.guardian.as_deref(),
|
matches!(source, RequestDecodeSource::WebSocketFrame),
|
||||||
request_headers.ambiguous_guardian_headers,
|
|
||||||
);
|
);
|
||||||
request_headers.apply_subagent(&mut object, &mut protocol_context, source);
|
|
||||||
|
|
||||||
let semantics =
|
|
||||||
gateway_protocol::openai::codex_responses_request_semantics(&object, &protocol_context);
|
|
||||||
let client_turn = if object.get("generate").and_then(Value::as_bool) != Some(false)
|
|
||||||
&& semantics.request_kind.as_deref() == Some("turn")
|
|
||||||
&& !semantics.compact
|
|
||||||
{
|
|
||||||
gateway_protocol::openai::codex_account_thread_id(&object, &protocol_context)
|
|
||||||
.zip(gateway_protocol::openai::codex_turn_id(
|
|
||||||
&object,
|
|
||||||
&protocol_context,
|
|
||||||
))
|
|
||||||
.and_then(|(thread, turn)| ClientTurn::new(thread, turn))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
let payload = ProtocolPayload::json_object(OPENAI_PROTOCOL, object)
|
let payload = ProtocolPayload::json_object(OPENAI_PROTOCOL, object)
|
||||||
.map_err(|_| RequestDecodeError::CanonicalContract {
|
.map_err(|_| RequestDecodeError::CanonicalContract {
|
||||||
@@ -336,7 +210,6 @@ pub(super) fn decode_request_object(
|
|||||||
metadata: GenerationRequestMetadata {
|
metadata: GenerationRequestMetadata {
|
||||||
requested_model: model,
|
requested_model: model,
|
||||||
stream,
|
stream,
|
||||||
store,
|
|
||||||
continuation,
|
continuation,
|
||||||
client_ip: None,
|
client_ip: None,
|
||||||
user_agent: None,
|
user_agent: None,
|
||||||
@@ -344,92 +217,6 @@ pub(super) fn decode_request_object(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn inject_subagent_metadata(body: &mut Map<String, Value>, subagent: &str) {
|
|
||||||
let metadata = body
|
|
||||||
.entry("client_metadata".to_owned())
|
|
||||||
.or_insert_with(|| Value::Object(Map::new()));
|
|
||||||
let Some(metadata) = metadata.as_object_mut() else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
metadata.insert(
|
|
||||||
OPENAI_SUBAGENT_KEY.to_owned(),
|
|
||||||
Value::String(subagent.to_owned()),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn header_string(headers: &HeaderMap, name: &str) -> Option<String> {
|
|
||||||
headers
|
|
||||||
.get(name)
|
|
||||||
.and_then(|value| value.to_str().ok())
|
|
||||||
.map(ToOwned::to_owned)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn passthrough_headers(headers: &HeaderMap) -> Vec<Value> {
|
|
||||||
passthrough_request_headers(headers)
|
|
||||||
.map(|(name, value)| {
|
|
||||||
Value::Array(vec![
|
|
||||||
Value::String(name.as_str().to_owned()),
|
|
||||||
Value::String(STANDARD.encode(value.as_bytes())),
|
|
||||||
])
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// HTTP 与 Live 入站共用的身份、传输边界;保留业务头原始多值字节
|
|
||||||
pub(crate) fn passthrough_request_headers(
|
|
||||||
headers: &HeaderMap,
|
|
||||||
) -> impl Iterator<Item = (&HeaderName, &HeaderValue)> {
|
|
||||||
let connection_headers = headers
|
|
||||||
.get_all("connection")
|
|
||||||
.iter()
|
|
||||||
.filter_map(|value| value.to_str().ok())
|
|
||||||
.flat_map(|value| value.split(','))
|
|
||||||
.map(str::trim)
|
|
||||||
.filter(|name| !name.is_empty())
|
|
||||||
.map(str::to_ascii_lowercase)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
|
|
||||||
headers
|
|
||||||
.iter()
|
|
||||||
.filter(move |(name, _)| passthrough_header_name(name.as_str(), &connection_headers))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn passthrough_header_name(name: &str, connection_headers: &[String]) -> bool {
|
|
||||||
if connection_headers
|
|
||||||
.iter()
|
|
||||||
.any(|connection_header| connection_header.eq_ignore_ascii_case(name))
|
|
||||||
|| is_transport_managed_request_header(name)
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
!matches!(
|
|
||||||
name,
|
|
||||||
// 下游鉴权和账号 cookie 绝不能成为上游账号身份
|
|
||||||
"authorization"
|
|
||||||
| "x-api-key"
|
|
||||||
| "x-goog-api-key"
|
|
||||||
// Codex 的服务端托管认证标记只用于客户端能力判断,不代表上游身份
|
|
||||||
| "x-openai-actor-authorization"
|
|
||||||
| "cookie"
|
|
||||||
| "cookie2"
|
|
||||||
| "chatgpt-account-id"
|
|
||||||
| "chatgpt-project-id"
|
|
||||||
| "openai-organization"
|
|
||||||
| "openai-project"
|
|
||||||
// 上游指纹必须由运行时画像统一生成,客户端 originator/User-Agent/version
|
|
||||||
// 不能作为不透明头透传覆盖,避免不同下游客户端暴露不一致的设备指纹
|
|
||||||
| "originator"
|
|
||||||
| "user-agent"
|
|
||||||
| "version"
|
|
||||||
// 设备 attestation/integrity 头只能由官方客户端或网关自身生成,
|
|
||||||
// 客户端注入的 x-oai-attestation / X-OAI-IS 不得透传上游
|
|
||||||
| "x-oai-attestation"
|
|
||||||
| "x-oai-is"
|
|
||||||
| "x-oai-is-update"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn required_non_empty_string<'a>(
|
fn required_non_empty_string<'a>(
|
||||||
object: &'a Map<String, Value>,
|
object: &'a Map<String, Value>,
|
||||||
key: &str,
|
key: &str,
|
||||||
|
|||||||
@@ -288,10 +288,9 @@ fn client_payload(wire: &ProtocolWireEvent) -> Option<Value> {
|
|||||||
.flat_map(|value| value.split(','))
|
.flat_map(|value| value.split(','))
|
||||||
.map(|name| name.trim().to_ascii_lowercase())
|
.map(|name| name.trim().to_ascii_lowercase())
|
||||||
.collect();
|
.collect();
|
||||||
if headers
|
if headers.keys().all(|name| {
|
||||||
.keys()
|
crate::data_plane::headers::response_header_is_forwardable(name, &connection_options)
|
||||||
.all(|name| super::response_header_is_forwardable(name, &connection_options))
|
}) {
|
||||||
{
|
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
// 只剥离既有响应头隔离策略禁止的字段,metadata 业务扩展保持不透明
|
// 只剥离既有响应头隔离策略禁止的字段,metadata 业务扩展保持不透明
|
||||||
@@ -299,7 +298,9 @@ fn client_payload(wire: &ProtocolWireEvent) -> Option<Value> {
|
|||||||
projected
|
projected
|
||||||
.get_mut("headers")?
|
.get_mut("headers")?
|
||||||
.as_object_mut()?
|
.as_object_mut()?
|
||||||
.retain(|name, _| super::response_header_is_forwardable(name, &connection_options));
|
.retain(|name, _| {
|
||||||
|
crate::data_plane::headers::response_header_is_forwardable(name, &connection_options)
|
||||||
|
});
|
||||||
Some(projected)
|
Some(projected)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -70,11 +70,7 @@ impl ConnectionReplaySnapshot {
|
|||||||
return ForwardOutcome::Continue;
|
return ForwardOutcome::Continue;
|
||||||
};
|
};
|
||||||
self.provider_state = capture.provider_state.take();
|
self.provider_state = capture.provider_state.take();
|
||||||
let reconnect = delivered == Some(&id)
|
let reconnect = delivered == Some(&id) && capture.reconnect_websocket;
|
||||||
&& self
|
|
||||||
.provider_state
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(ProviderSessionState::prefers_websocket_reconnect);
|
|
||||||
self.last_response_id = Some(id);
|
self.last_response_id = Some(id);
|
||||||
if reconnect {
|
if reconnect {
|
||||||
ForwardOutcome::ReconnectIfIdle
|
ForwardOutcome::ReconnectIfIdle
|
||||||
@@ -88,6 +84,7 @@ impl ConnectionReplaySnapshot {
|
|||||||
pub(super) struct ReplayCapture {
|
pub(super) struct ReplayCapture {
|
||||||
response_id: Option<String>,
|
response_id: Option<String>,
|
||||||
provider_state: Option<ProviderSessionState>,
|
provider_state: Option<ProviderSessionState>,
|
||||||
|
reconnect_websocket: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) type ReplayCaptureHandle = Arc<Mutex<ReplayCapture>>;
|
pub(super) type ReplayCaptureHandle = Arc<Mutex<ReplayCapture>>;
|
||||||
@@ -476,7 +473,7 @@ struct WebSocketExecutionBody {
|
|||||||
encoder: OpenAiResponsesEncoder,
|
encoder: OpenAiResponsesEncoder,
|
||||||
validation: ResponseValidationFacts,
|
validation: ResponseValidationFacts,
|
||||||
pending: VecDeque<MiddlewareFrame>,
|
pending: VecDeque<MiddlewareFrame>,
|
||||||
provider_state: Option<ProviderSessionState>,
|
pending_replay: ReplayCapture,
|
||||||
request_id: Arc<str>,
|
request_id: Arc<str>,
|
||||||
capture: ReplayCaptureHandle,
|
capture: ReplayCaptureHandle,
|
||||||
batch_pending: bool,
|
batch_pending: bool,
|
||||||
@@ -498,7 +495,7 @@ impl WebSocketExecutionBody {
|
|||||||
encoder: OpenAiResponsesEncoder::new(),
|
encoder: OpenAiResponsesEncoder::new(),
|
||||||
validation,
|
validation,
|
||||||
pending: VecDeque::new(),
|
pending: VecDeque::new(),
|
||||||
provider_state: None,
|
pending_replay: ReplayCapture::default(),
|
||||||
request_id,
|
request_id,
|
||||||
capture,
|
capture,
|
||||||
batch_pending: false,
|
batch_pending: false,
|
||||||
@@ -541,8 +538,9 @@ impl WebSocketExecutionBody {
|
|||||||
.capture
|
.capture
|
||||||
.lock()
|
.lock()
|
||||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||||
capture.response_id = self.encoder.response_id().map(str::to_owned);
|
self.pending_replay.response_id =
|
||||||
capture.provider_state = self.provider_state.take();
|
self.encoder.response_id().map(str::to_owned);
|
||||||
|
*capture = std::mem::take(&mut self.pending_replay);
|
||||||
drop(capture);
|
drop(capture);
|
||||||
self.execution.disarm();
|
self.execution.disarm();
|
||||||
self.finished = true;
|
self.finished = true;
|
||||||
@@ -595,8 +593,9 @@ impl WebSocketExecutionBody {
|
|||||||
self.validation.observe_event(&event);
|
self.validation.observe_event(&event);
|
||||||
let transformed = self.transformed_pending || event.middleware_transformed();
|
let transformed = self.transformed_pending || event.middleware_transformed();
|
||||||
if let Some(update) = event.take_session_update() {
|
if let Some(update) = event.take_session_update() {
|
||||||
self.provider_state = Some(update);
|
self.pending_replay.provider_state = Some(update);
|
||||||
}
|
}
|
||||||
|
self.pending_replay.reconnect_websocket |= event.prefers_websocket_reconnect();
|
||||||
let encoded = self.encoder.push_websocket(&event);
|
let encoded = self.encoder.push_websocket(&event);
|
||||||
if encoded.is_empty() {
|
if encoded.is_empty() {
|
||||||
self.transformed_pending = transformed;
|
self.transformed_pending = transformed;
|
||||||
|
|||||||
@@ -130,10 +130,14 @@ pub(super) fn response_metadata_event(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<String, Value> {
|
fn response_event_headers(response_headers: &[ProviderResponseHeader]) -> Map<String, Value> {
|
||||||
let connection_options = super::super::response_connection_options(response_headers);
|
let connection_options =
|
||||||
|
crate::data_plane::headers::response_connection_options(response_headers);
|
||||||
let mut headers = Map::new();
|
let mut headers = Map::new();
|
||||||
for header in response_headers {
|
for header in response_headers {
|
||||||
if !super::super::response_header_is_forwardable(header.name(), &connection_options) {
|
if !crate::data_plane::headers::response_header_is_forwardable(
|
||||||
|
header.name(),
|
||||||
|
&connection_options,
|
||||||
|
) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
let Ok(name) = HeaderName::from_bytes(header.name().as_bytes()) else {
|
||||||
|
|||||||
@@ -8,12 +8,9 @@ use axum::{
|
|||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
chat_completions::chat_completions,
|
chat_completions::chat_completions,
|
||||||
images::{image_edits, image_generations},
|
|
||||||
live,
|
|
||||||
messages::{count_tokens, messages},
|
messages::{count_tokens, messages},
|
||||||
models::{model_detail, models},
|
models::{model_detail, models},
|
||||||
responses::{responses, responses_websocket},
|
responses::{responses, responses_websocket},
|
||||||
search::standalone_search,
|
|
||||||
usage,
|
usage,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -24,9 +21,6 @@ pub(super) use gateway_protocol::openai::RESPONSES_PATH;
|
|||||||
pub(super) const MESSAGES_PATH: &str = "/v1/messages";
|
pub(super) const MESSAGES_PATH: &str = "/v1/messages";
|
||||||
pub(super) const MESSAGE_TOKENS_PATH: &str = "/v1/messages/count_tokens";
|
pub(super) const MESSAGE_TOKENS_PATH: &str = "/v1/messages/count_tokens";
|
||||||
pub(super) const CHAT_COMPLETIONS_PATH: &str = "/v1/chat/completions";
|
pub(super) const CHAT_COMPLETIONS_PATH: &str = "/v1/chat/completions";
|
||||||
pub(super) const IMAGE_GENERATIONS_PATH: &str = "/v1/images/generations";
|
|
||||||
pub(super) const IMAGE_EDITS_PATH: &str = "/v1/images/edits";
|
|
||||||
pub(super) const SEARCH_PATH: &str = "/v1/alpha/search";
|
|
||||||
pub(super) const MODELS_PATH: &str = "/v1/models";
|
pub(super) const MODELS_PATH: &str = "/v1/models";
|
||||||
pub(super) const MODEL_DETAIL_PATH: &str = "/v1/models/{model_id}";
|
pub(super) const MODEL_DETAIL_PATH: &str = "/v1/models/{model_id}";
|
||||||
pub(super) const USAGE_PATH: &str = "/v1/usage";
|
pub(super) const USAGE_PATH: &str = "/v1/usage";
|
||||||
@@ -35,9 +29,6 @@ pub(super) const PEER_LINK_PATH: &str = "/v1/cpr/link";
|
|||||||
/// 构造模型数据面路由
|
/// 构造模型数据面路由
|
||||||
pub(crate) fn router() -> Router<ApiState> {
|
pub(crate) fn router() -> Router<ApiState> {
|
||||||
Router::new()
|
Router::new()
|
||||||
.route(IMAGE_GENERATIONS_PATH, post(image_generations))
|
|
||||||
.route(IMAGE_EDITS_PATH, post(image_edits))
|
|
||||||
.route(SEARCH_PATH, post(standalone_search))
|
|
||||||
.route(RESPONSES_PATH, get(responses_websocket).post(responses))
|
.route(RESPONSES_PATH, get(responses_websocket).post(responses))
|
||||||
.route(CHAT_COMPLETIONS_PATH, post(chat_completions))
|
.route(CHAT_COMPLETIONS_PATH, post(chat_completions))
|
||||||
.route(MESSAGES_PATH, post(messages))
|
.route(MESSAGES_PATH, post(messages))
|
||||||
@@ -48,7 +39,7 @@ pub(crate) fn router() -> Router<ApiState> {
|
|||||||
.merge(super::genai::router())
|
.merge(super::genai::router())
|
||||||
.merge(usage::router())
|
.merge(usage::router())
|
||||||
.merge(super::peer_link::router())
|
.merge(super::peer_link::router())
|
||||||
.merge(live::router())
|
.merge(super::openai::router())
|
||||||
// 生成请求正文属于客户端/上游协议;代理不能用私有大小上限提前拒绝
|
// 生成请求正文属于客户端/上游协议;代理不能用私有大小上限提前拒绝
|
||||||
// 上游本可接受的未来 payload
|
// 上游本可接受的未来 payload
|
||||||
.layer(DefaultBodyLimit::disable())
|
.layer(DefaultBodyLimit::disable())
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use gateway_core::engine::execution::{
|
|||||||
};
|
};
|
||||||
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
use gateway_core::error::{GatewayError, GatewayErrorKind};
|
||||||
use gateway_core::lifecycle::{ConnectionDraining, ConnectionGuard, ConnectionLifecycle};
|
use gateway_core::lifecycle::{ConnectionDraining, ConnectionGuard, ConnectionLifecycle};
|
||||||
use gateway_core::routing::{ProviderCatalogUnavailable, PublicModelDescriptor, PublicModelId};
|
use gateway_core::routing::PublicModelId;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use super::auth::ClientApiKeyAuthError;
|
use super::auth::ClientApiKeyAuthError;
|
||||||
@@ -68,22 +68,6 @@ impl DataPlaneService {
|
|||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) async fn client_model_catalog(
|
|
||||||
&self,
|
|
||||||
client: &AuthenticatedClient,
|
|
||||||
client_version: &str,
|
|
||||||
) -> Result<Vec<PublicModelDescriptor>, ProviderCatalogUnavailable> {
|
|
||||||
let context = crate::middleware::current();
|
|
||||||
self.execution
|
|
||||||
.client_model_catalog(
|
|
||||||
client,
|
|
||||||
"codex",
|
|
||||||
client_version,
|
|
||||||
context.as_ref().and_then(|ctx| ctx.extensions.peer_route()),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn contains_public_model(
|
pub(crate) fn contains_public_model(
|
||||||
&self,
|
&self,
|
||||||
client: &AuthenticatedClient,
|
client: &AuthenticatedClient,
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ use crate::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
auth::{client_access_error_response, verify_client},
|
auth::{ClientKeyHeaders, client_access_error_response, verify_client},
|
||||||
error::{missing_client_api_key_response, openai_error_response},
|
error::{missing_client_api_key_response, openai_error_response},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -40,7 +40,7 @@ async fn usage(
|
|||||||
headers: HeaderMap,
|
headers: HeaderMap,
|
||||||
uri: axum::http::Uri,
|
uri: axum::http::Uri,
|
||||||
) -> Response {
|
) -> Response {
|
||||||
let client = match verify_client(state.data_plane(), &headers).await {
|
let client = match verify_client(state.data_plane(), &headers, ClientKeyHeaders::Bearer).await {
|
||||||
Ok(client) => client,
|
Ok(client) => client,
|
||||||
Err(error) => return client_access_error_response(error.into()),
|
Err(error) => return client_access_error_response(error.into()),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -255,6 +255,7 @@ pub fn initialize(
|
|||||||
axum::http::header::AUTHORIZATION,
|
axum::http::header::AUTHORIZATION,
|
||||||
axum::http::header::CONTENT_TYPE,
|
axum::http::header::CONTENT_TYPE,
|
||||||
HeaderName::from_static("x-api-key"),
|
HeaderName::from_static("x-api-key"),
|
||||||
|
HeaderName::from_static("x-goog-api-key"),
|
||||||
HeaderName::from_static("anthropic-version"),
|
HeaderName::from_static("anthropic-version"),
|
||||||
HeaderName::from_static("anthropic-beta"),
|
HeaderName::from_static("anthropic-beta"),
|
||||||
request_id_header.clone(),
|
request_id_header.clone(),
|
||||||
|
|||||||
@@ -475,17 +475,17 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
|
|||||||
last_error_reason: None,
|
last_error_reason: None,
|
||||||
last_error_message: None,
|
last_error_message: None,
|
||||||
};
|
};
|
||||||
for (authentication_kind, read, write) in [
|
for (provider_kind, authentication_kind, window_kind, read, write) in [
|
||||||
("api_key", Some(13), Some(7)),
|
("openai", "api_key", "general", Some(13), Some(7)),
|
||||||
("api_key", None, None),
|
("openai", "api_key", "general", None, None),
|
||||||
("oauth", Some(13), Some(7)),
|
("xai", "oauth", "daily", Some(13), Some(7)),
|
||||||
("oauth", None, None),
|
("xai", "oauth", "daily", None, None),
|
||||||
|
("antigravity", "oauth", "recent_week", Some(13), Some(7)),
|
||||||
|
("antigravity", "oauth", "recent_week", None, None),
|
||||||
] {
|
] {
|
||||||
let mut account = account_page_item(facts.clone(), now, authentication_kind);
|
let mut account = account_page_item(facts.clone(), now, authentication_kind);
|
||||||
if authentication_kind == "oauth" {
|
account.account.provider_kind =
|
||||||
account.account.provider_kind =
|
gateway_core::routing::ProviderKind::new(provider_kind).unwrap();
|
||||||
gateway_core::routing::ProviderKind::new("xai").unwrap();
|
|
||||||
}
|
|
||||||
*fixture.account.lock().unwrap() = Some(account);
|
*fixture.account.lock().unwrap() = Some(account);
|
||||||
let local_usage = AccountUsage {
|
let local_usage = AccountUsage {
|
||||||
account_id: "acct_cooldown".to_owned(),
|
account_id: "acct_cooldown".to_owned(),
|
||||||
@@ -576,14 +576,7 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
|
|||||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||||
assert_eq!(status, StatusCode::OK, "{value}");
|
assert_eq!(status, StatusCode::OK, "{value}");
|
||||||
let usage = &value["data"]["items"][0]["usage"];
|
let usage = &value["data"]["items"][0]["usage"];
|
||||||
assert_eq!(
|
assert_eq!(usage["windowKind"], window_kind);
|
||||||
usage["windowKind"],
|
|
||||||
if authentication_kind == "oauth" {
|
|
||||||
"daily"
|
|
||||||
} else {
|
|
||||||
"general"
|
|
||||||
}
|
|
||||||
);
|
|
||||||
assert_eq!(usage["models"][0]["successRateDisplay"], "33.3%");
|
assert_eq!(usage["models"][0]["successRateDisplay"], "33.3%");
|
||||||
assert!((usage["models"][0]["successRate"].as_f64().unwrap() - 100.0 / 3.0).abs() < 0.001);
|
assert!((usage["models"][0]["successRate"].as_f64().unwrap() - 100.0 / 3.0).abs() < 0.001);
|
||||||
assert_eq!(usage["models"][1]["successRate"], 0.0);
|
assert_eq!(usage["models"][1]["successRate"], 0.0);
|
||||||
@@ -608,6 +601,26 @@ async fn account_usage_preserves_periods_cache_counts_and_missing_values() {
|
|||||||
usage["cacheWriteInputTokensDisplay"],
|
usage["cacheWriteInputTokensDisplay"],
|
||||||
if write.is_some() { "7" } else { "—" }
|
if write.is_some() { "7" } else { "—" }
|
||||||
);
|
);
|
||||||
|
fixture.account_usage.lock().unwrap().clear();
|
||||||
|
let response = admin::accounts::router::<AdminTestState>()
|
||||||
|
.with_state(fixture.state())
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.uri("/api/admin/accounts")
|
||||||
|
.header("x-request-id", "req_empty_account_usage_contract")
|
||||||
|
.header(header::COOKIE, "cpr_session=valid-session")
|
||||||
|
.body(Body::empty())
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
|
let body = to_bytes(response.into_body(), 32768).await.unwrap();
|
||||||
|
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||||
|
let usage = &value["data"]["items"][0]["usage"];
|
||||||
|
assert_eq!(usage["windowKind"], window_kind);
|
||||||
|
assert!(usage["totalTokens"].is_null());
|
||||||
|
assert_eq!(usage["models"], serde_json::json!([]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -200,6 +200,13 @@ impl AdminTestFixture {
|
|||||||
let provider_quota_gate = Arc::new(Mutex::new(None));
|
let provider_quota_gate = Arc::new(Mutex::new(None));
|
||||||
let provider_models = Arc::new(Mutex::new(None));
|
let provider_models = Arc::new(Mutex::new(None));
|
||||||
let providers: Vec<Arc<dyn ProviderAdmin>> = vec![
|
let providers: Vec<Arc<dyn ProviderAdmin>> = vec![
|
||||||
|
Arc::new(UnusedProvider::new(
|
||||||
|
"antigravity",
|
||||||
|
Arc::clone(&provider_error),
|
||||||
|
Arc::clone(&provider_quota),
|
||||||
|
Arc::clone(&provider_quota_gate),
|
||||||
|
Arc::clone(&provider_models),
|
||||||
|
)),
|
||||||
Arc::new(UnusedProvider::new(
|
Arc::new(UnusedProvider::new(
|
||||||
"openai",
|
"openai",
|
||||||
Arc::clone(&provider_error),
|
Arc::clone(&provider_error),
|
||||||
@@ -1735,6 +1742,16 @@ impl UnusedProvider {
|
|||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl ProviderAdmin for UnusedProvider {
|
impl ProviderAdmin for UnusedProvider {
|
||||||
|
fn account_usage_lookback(
|
||||||
|
&self,
|
||||||
|
) -> gateway_admin::model::provider_credentials::AccountUsageLookback {
|
||||||
|
use gateway_admin::model::provider_credentials::AccountUsageLookback;
|
||||||
|
match self.kind.as_str() {
|
||||||
|
"antigravity" => AccountUsageLookback::RecentWeek,
|
||||||
|
_ => AccountUsageLookback::RollingDay,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn account_capabilities(
|
fn account_capabilities(
|
||||||
&self,
|
&self,
|
||||||
_: &ProviderAccountId,
|
_: &ProviderAccountId,
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//! Chat 字节交付只消费 Chat wire,并核对终态、身份与截断
|
||||||
|
|
||||||
|
use super::{
|
||||||
|
chat_request, chunk, completed, created,
|
||||||
|
http::{Fixture, json_body},
|
||||||
|
};
|
||||||
|
use crate::support::generation::Session;
|
||||||
|
use axum::{body::to_bytes, http::StatusCode, response::Response};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
pub(super) async fn sse_body(response: Response) -> (String, Vec<Value>) {
|
||||||
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
|
assert_eq!(response.headers()["content-type"], "text/event-stream");
|
||||||
|
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
|
let text = String::from_utf8(bytes.to_vec()).unwrap();
|
||||||
|
assert_eq!(text.matches("data: [DONE]").count(), 1, "{text}");
|
||||||
|
assert!(text.ends_with("data: [DONE]\n\n"), "{text}");
|
||||||
|
let chunks = text
|
||||||
|
.lines()
|
||||||
|
.filter_map(|line| line.strip_prefix("data: "))
|
||||||
|
.filter(|data| *data != "[DONE]")
|
||||||
|
.map(|data| serde_json::from_str(data).unwrap())
|
||||||
|
.collect();
|
||||||
|
(text, chunks)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn buffers_chat_chunks_as_json() {
|
||||||
|
let fixture = Fixture::new(Session::new(vec![
|
||||||
|
created(),
|
||||||
|
chunk(json!({"content":"你好 "}), Value::Null),
|
||||||
|
completed("🌍"),
|
||||||
|
]))
|
||||||
|
.await;
|
||||||
|
let response = fixture.post(chat_request(false)).await;
|
||||||
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
|
let body = json_body(response).await;
|
||||||
|
assert_eq!(body["object"], "chat.completion");
|
||||||
|
assert_eq!(body["choices"][0]["message"]["content"], "你好 🌍");
|
||||||
|
assert_eq!(body["choices"][0]["finish_reason"], "stop");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn returns_chat_sse_with_one_terminal_and_one_done() {
|
||||||
|
let fixture = Fixture::new(Session::new(vec![created(), completed("answer")])).await;
|
||||||
|
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||||
|
assert!(
|
||||||
|
chunks
|
||||||
|
.iter()
|
||||||
|
.all(|value| value["object"] == "chat.completion.chunk")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
chunks
|
||||||
|
.iter()
|
||||||
|
.filter(|value| value["choices"][0]["finish_reason"].is_string())
|
||||||
|
.count(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert!(chunks.iter().all(|value| value["id"] == "chatcmpl_fixture"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn truncation_produces_error_without_success_finish() {
|
||||||
|
let fixture = Fixture::new(Session::new(vec![
|
||||||
|
created(),
|
||||||
|
chunk(json!({"content":"partial"}), Value::Null),
|
||||||
|
]))
|
||||||
|
.await;
|
||||||
|
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||||
|
assert!(chunks.iter().any(|value| value.get("error").is_some()));
|
||||||
|
assert!(
|
||||||
|
!chunks
|
||||||
|
.iter()
|
||||||
|
.any(|value| value["choices"][0]["finish_reason"].is_string())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn rejects_invalid_chat_input_before_starting_execution() {
|
||||||
|
let fixture = Fixture::new(Session::new(Vec::new())).await;
|
||||||
|
let mut body = chat_request(false);
|
||||||
|
body["n"] = json!(2);
|
||||||
|
let response = fixture.post(body).await;
|
||||||
|
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(json_body(response).await["error"]["param"], "n");
|
||||||
|
assert!(fixture.execution.captured.lock().unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn buffered_chat_rejects_multiple_json_or_mixed_representations() {
|
||||||
|
for events in [
|
||||||
|
vec![super::json_completed(), super::json_completed()],
|
||||||
|
vec![created(), super::json_completed()],
|
||||||
|
vec![super::json_completed(), created()],
|
||||||
|
] {
|
||||||
|
let fixture = Fixture::new(Session::new(vec![]).with_batch(events)).await;
|
||||||
|
let response = fixture.post(chat_request(false)).await;
|
||||||
|
assert!(response.status().is_server_error());
|
||||||
|
assert!(json_body(response).await.get("choices").is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn final_usage_follows_the_finish_chunk_and_precedes_done() {
|
||||||
|
use gateway_core::event::{GatewayEvent, ProtocolWireEvent, ProviderEvent, ResponseMeta};
|
||||||
|
let usage = ProviderEvent::wire(ProtocolWireEvent::json("chat_completions", None, json!({
|
||||||
|
"id":"chatcmpl_fixture","object":"chat.completion.chunk","created":100,"model":"model-a",
|
||||||
|
"choices":[],"usage":{"prompt_tokens":3,"completion_tokens":2,"total_tokens":5}
|
||||||
|
})).unwrap()).with_fact(GatewayEvent::Completed(ResponseMeta::new("upstream", "model-a")));
|
||||||
|
let fixture = Fixture::new(Session::new(vec![
|
||||||
|
created(),
|
||||||
|
chunk(json!({"content":"answer"}), Value::Null),
|
||||||
|
chunk(json!({}), json!("stop")),
|
||||||
|
usage,
|
||||||
|
]))
|
||||||
|
.await;
|
||||||
|
let (_, chunks) = sse_body(fixture.post(chat_request(true)).await).await;
|
||||||
|
assert_eq!(
|
||||||
|
chunks[chunks.len() - 2]["choices"][0]["finish_reason"],
|
||||||
|
"stop"
|
||||||
|
);
|
||||||
|
assert_eq!(chunks.last().unwrap()["usage"]["total_tokens"], 5);
|
||||||
|
assert!(chunks.iter().all(|value| value.get("error").is_none()));
|
||||||
|
}
|
||||||
@@ -36,7 +36,7 @@ use gateway_core::{
|
|||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use tower::ServiceExt as _;
|
use tower::ServiceExt as _;
|
||||||
|
|
||||||
use super::{chat_request, completed, created, message};
|
use super::{chat_request, completed, created};
|
||||||
use crate::data_plane::{
|
use crate::data_plane::{
|
||||||
api_router, authenticated_client, authenticated_client_for_provider_with_limit,
|
api_router, authenticated_client, authenticated_client_for_provider_with_limit,
|
||||||
middleware::{RequestMiddleware, ResponseFrameAction},
|
middleware::{RequestMiddleware, ResponseFrameAction},
|
||||||
@@ -50,6 +50,7 @@ use crate::support::generation::{Finish, Session};
|
|||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub(super) struct Captured {
|
pub(super) struct Captured {
|
||||||
pub body: Value,
|
pub body: Value,
|
||||||
|
pub protocol: String,
|
||||||
pub context: Value,
|
pub context: Value,
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
}
|
}
|
||||||
@@ -99,6 +100,7 @@ impl ExecutionService for Execution {
|
|||||||
};
|
};
|
||||||
*self.captured.lock().unwrap() = Some(Captured {
|
*self.captured.lock().unwrap() = Some(Captured {
|
||||||
body: Value::Object(generation.protocol_payload().body().clone()),
|
body: Value::Object(generation.protocol_payload().body().clone()),
|
||||||
|
protocol: generation.protocol_payload().protocol().to_owned(),
|
||||||
context: Value::Object(generation.protocol_payload().context().clone()),
|
context: Value::Object(generation.protocol_payload().context().clone()),
|
||||||
endpoint: request.metadata.endpoint,
|
endpoint: request.metadata.endpoint,
|
||||||
});
|
});
|
||||||
@@ -209,7 +211,7 @@ impl MiddlewarePlan for InspectMiddleware {
|
|||||||
let headers = request.headers().to_vec();
|
let headers = request.headers().to_vec();
|
||||||
request = request
|
request = request
|
||||||
.replace_parts(
|
.replace_parts(
|
||||||
"openai".to_owned(),
|
"chat_completions".to_owned(),
|
||||||
headers,
|
headers,
|
||||||
Bytes::from(body.to_string()),
|
Bytes::from(body.to_string()),
|
||||||
None,
|
None,
|
||||||
@@ -240,18 +242,18 @@ async fn rejects_missing_authentication_before_decoding_or_execution() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn request_middleware_sees_responses_and_preserves_the_chat_endpoint() {
|
async fn request_middleware_sees_original_chat_and_preserves_the_endpoint() {
|
||||||
let middleware = Arc::new(InspectMiddleware {
|
let middleware = Arc::new(InspectMiddleware {
|
||||||
inner: RequestMiddleware {
|
inner: RequestMiddleware {
|
||||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||||
..RequestMiddleware::default()
|
..RequestMiddleware::default()
|
||||||
},
|
},
|
||||||
update: Some(|body| {
|
update: Some(|body| {
|
||||||
body["input"] = json!("rewritten by request middleware");
|
body["messages"][0]["content"] = json!("rewritten by request middleware");
|
||||||
}),
|
}),
|
||||||
..InspectMiddleware::default()
|
..InspectMiddleware::default()
|
||||||
});
|
});
|
||||||
let mut execution = Execution::new(Session::new(vec![completed(json!([message("ok")]))]));
|
let mut execution = Execution::new(Session::new(vec![created(), completed("ok")]));
|
||||||
execution.middleware = Some(middleware.frozen());
|
execution.middleware = Some(middleware.frozen());
|
||||||
let fixture = Fixture::with_execution(execution).await;
|
let fixture = Fixture::with_execution(execution).await;
|
||||||
let response = fixture.post(chat_request(false)).await;
|
let response = fixture.post(chat_request(false)).await;
|
||||||
@@ -259,15 +261,18 @@ async fn request_middleware_sees_responses_and_preserves_the_chat_endpoint() {
|
|||||||
let downstream = json_body(response).await;
|
let downstream = json_body(response).await;
|
||||||
assert_eq!(downstream["object"], "chat.completion");
|
assert_eq!(downstream["object"], "chat.completion");
|
||||||
let observed = middleware.requests.lock().unwrap();
|
let observed = middleware.requests.lock().unwrap();
|
||||||
assert!(observed[0].get("messages").is_none());
|
assert_eq!(observed.as_slice(), [chat_request(false)]);
|
||||||
assert_eq!(observed[0]["input"][0]["role"], "user");
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
middleware.inner.endpoints.lock().unwrap().as_slice(),
|
||||||
[PATH]
|
[PATH]
|
||||||
);
|
);
|
||||||
let captured = fixture.captured();
|
let captured = fixture.captured();
|
||||||
assert_eq!(captured.endpoint, PATH);
|
assert_eq!(captured.endpoint, PATH);
|
||||||
assert_eq!(captured.body["input"], "rewritten by request middleware");
|
assert_eq!(captured.protocol, "chat_completions");
|
||||||
|
assert_eq!(
|
||||||
|
captured.body["messages"][0]["content"],
|
||||||
|
"rewritten by request middleware"
|
||||||
|
);
|
||||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -288,7 +293,7 @@ async fn dropping_chat_body_cancels_and_finalizes_the_original_execution() {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn gzip_and_headers_reuse_the_responses_ingress_contract() {
|
async fn gzip_and_headers_reuse_the_responses_ingress_contract() {
|
||||||
let mut session = Session::new(vec![completed(json!([message("ok")]))]);
|
let mut session = Session::new(vec![created(), completed("ok")]);
|
||||||
session.response_headers = vec![
|
session.response_headers = vec![
|
||||||
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"first")),
|
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"first")),
|
||||||
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"second")),
|
ProviderResponseHeader::new("x-future-multi", Bytes::from_static(b"second")),
|
||||||
@@ -368,10 +373,13 @@ async fn corrupt_or_oversized_compressed_chat_never_starts_execution() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn response_middleware_is_validated_as_responses_before_chat_projection() {
|
async fn response_middleware_must_preserve_chat_shape_and_identity() {
|
||||||
for matching_identity in [true, false] {
|
for (matching_identity, raw_json) in
|
||||||
let replacement = json!({"id":if matching_identity {"resp_chat_test"} else {"resp_other"},
|
[(true, false), (false, false), (true, true), (false, true)]
|
||||||
"status":"completed","output":[message("plugin text")]});
|
{
|
||||||
|
let replacement = json!({"id":if matching_identity {"chatcmpl_fixture"} else {"chatcmpl_other"},
|
||||||
|
"object":"chat.completion","created":100,"model":"model-a",
|
||||||
|
"choices":[{"index":0,"message":{"role":"assistant","content":"plugin text"},"finish_reason":"stop"}]});
|
||||||
let middleware = Arc::new(
|
let middleware = Arc::new(
|
||||||
RequestMiddleware {
|
RequestMiddleware {
|
||||||
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
expected_operation: Some(gateway_core::operation::OperationKind::Generate),
|
||||||
@@ -381,8 +389,11 @@ async fn response_middleware_is_validated_as_responses_before_chat_projection()
|
|||||||
replacement.to_string(),
|
replacement.to_string(),
|
||||||
))]),
|
))]),
|
||||||
);
|
);
|
||||||
let mut execution =
|
let mut execution = Execution::new(Session::new(if raw_json {
|
||||||
Execution::new(Session::new(vec![completed(json!([message("original")]))]));
|
vec![super::json_completed()]
|
||||||
|
} else {
|
||||||
|
vec![created(), completed("original")]
|
||||||
|
}));
|
||||||
execution.middleware = Some(middleware.frozen());
|
execution.middleware = Some(middleware.frozen());
|
||||||
let fixture = Fixture::with_execution(execution).await;
|
let fixture = Fixture::with_execution(execution).await;
|
||||||
let response = fixture.post(chat_request(false)).await;
|
let response = fixture.post(chat_request(false)).await;
|
||||||
@@ -406,7 +417,7 @@ async fn response_middleware_is_validated_as_responses_before_chat_projection()
|
|||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn commit_failure_does_not_deliver_buffered_or_first_terminal_chat_success() {
|
async fn commit_failure_does_not_deliver_buffered_or_first_terminal_chat_success() {
|
||||||
for streaming in [false, true] {
|
for streaming in [false, true] {
|
||||||
let mut session = Session::new(vec![completed(json!([message("not delivered")]))]);
|
let mut session = Session::new(vec![created(), completed("not delivered")]);
|
||||||
session.fail_commit = true;
|
session.fail_commit = true;
|
||||||
let fixture = Fixture::new(session).await;
|
let fixture = Fixture::new(session).await;
|
||||||
let response = fixture.post(chat_request(streaming)).await;
|
let response = fixture.post(chat_request(streaming)).await;
|
||||||
@@ -418,41 +429,14 @@ async fn commit_failure_does_not_deliver_buffered_or_first_terminal_chat_success
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn the_same_execution_fixture_finishes_native_responses_with_one_commit() {
|
|
||||||
for already_started in [false, true] {
|
|
||||||
let mut events = Vec::new();
|
|
||||||
if already_started {
|
|
||||||
events.push(created());
|
|
||||||
}
|
|
||||||
events.push(completed(json!([message("native baseline")])));
|
|
||||||
let fixture = Fixture::new(Session::new(events)).await;
|
|
||||||
let mut request = request(json!({"model":"model-a","input":"hello","stream":true}));
|
|
||||||
*request.uri_mut() = "/v1/responses".parse().unwrap();
|
|
||||||
let response = fixture.router.clone().oneshot(request).await.unwrap();
|
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
|
||||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
|
||||||
let text = String::from_utf8(bytes.to_vec()).unwrap();
|
|
||||||
assert!(text.contains("event: response.completed"), "{text}");
|
|
||||||
assert!(text.contains("native baseline"), "{text}");
|
|
||||||
assert!(!text.contains("response.failed"), "{text}");
|
|
||||||
assert_eq!(text.matches("data: [DONE]").count(), 1, "{text}");
|
|
||||||
assert!(text.ends_with("data: [DONE]\n\n"), "{text}");
|
|
||||||
assert!(fixture.trace.finalized.load(Ordering::SeqCst));
|
|
||||||
assert_eq!(fixture.trace.commits.load(Ordering::SeqCst), 1);
|
|
||||||
assert_eq!(fixture.trace.response_commit.status_code(), Some(200));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
||||||
for already_started in [false, true] {
|
for already_started in [false, true] {
|
||||||
let mut events = Vec::new();
|
let mut session = if already_started {
|
||||||
if already_started {
|
Session::new(vec![created(), completed("")])
|
||||||
events.push(created());
|
} else {
|
||||||
}
|
Session::new(Vec::new()).with_batch(vec![created(), completed("")])
|
||||||
events.push(completed(json!([])));
|
};
|
||||||
let mut session = Session::new(events);
|
|
||||||
session.finish = Finish::Error;
|
session.finish = Finish::Error;
|
||||||
let fixture = Fixture::new(session).await;
|
let fixture = Fixture::new(session).await;
|
||||||
let mut body = chat_request(true);
|
let mut body = chat_request(true);
|
||||||
@@ -460,7 +444,7 @@ async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
|||||||
let response = fixture.post(body).await;
|
let response = fixture.post(body).await;
|
||||||
// 原会话已经接受 200 提交,后续终结错误只能作为流内错误交付
|
// 原会话已经接受 200 提交,后续终结错误只能作为流内错误交付
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let (_, chunks) = super::response::sse_body(response).await;
|
let (_, chunks) = super::delivery::sse_body(response).await;
|
||||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||||
assert!(
|
assert!(
|
||||||
!chunks
|
!chunks
|
||||||
@@ -477,11 +461,11 @@ async fn finalization_failure_never_leaks_success_finish_or_usage() {
|
|||||||
#[tokio::test(start_paused = true)]
|
#[tokio::test(start_paused = true)]
|
||||||
async fn error_after_admission_keepalive_uses_chat_error_encoding() {
|
async fn error_after_admission_keepalive_uses_chat_error_encoding() {
|
||||||
let mut session = Session::new(Vec::new());
|
let mut session = Session::new(Vec::new());
|
||||||
session.delay = Some(Duration::from_secs(31));
|
session.read_delay = Some(Duration::from_secs(31));
|
||||||
session.finish = Finish::Error;
|
session.finish = Finish::Error;
|
||||||
let fixture = Fixture::new(session).await;
|
let fixture = Fixture::new(session).await;
|
||||||
let response = fixture.post(chat_request(true)).await;
|
let response = fixture.post(chat_request(true)).await;
|
||||||
let (body, chunks) = super::response::sse_body(response).await;
|
let (body, chunks) = super::delivery::sse_body(response).await;
|
||||||
assert!(body.starts_with(": keep-alive\n\n"));
|
assert!(body.starts_with(": keep-alive\n\n"));
|
||||||
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
assert!(chunks.iter().any(|chunk| chunk.get("error").is_some()));
|
||||||
assert!(!body.contains("response.failed"));
|
assert!(!body.contains("response.failed"));
|
||||||
@@ -498,7 +482,7 @@ async fn early_middleware_failure_is_recorded_at_ingress_without_a_reserved_mode
|
|||||||
}
|
}
|
||||||
.with_json_short_circuit(Bytes::from_static(b"{}")),
|
.with_json_short_circuit(Bytes::from_static(b"{}")),
|
||||||
);
|
);
|
||||||
let mut execution = Execution::new(Session::new(vec![completed(json!([message("OK")]))]));
|
let mut execution = Execution::new(Session::new(vec![created(), completed("OK")]));
|
||||||
execution.middleware = Some(middleware.frozen());
|
execution.middleware = Some(middleware.frozen());
|
||||||
let execution = Arc::new(execution);
|
let execution = Arc::new(execution);
|
||||||
let diagnostics = Arc::new(crate::support::RecordingDiagnostics::default());
|
let diagnostics = Arc::new(crate::support::RecordingDiagnostics::default());
|
||||||
|
|||||||
@@ -1,45 +1,42 @@
|
|||||||
//! Chat Completions 的请求转换、输出投影与 HTTP 生命周期测试
|
//! Chat 原始入口与交付生命周期测试,纯转换测试归 gateway-protocol
|
||||||
|
|
||||||
|
mod delivery;
|
||||||
mod http;
|
mod http;
|
||||||
mod request;
|
|
||||||
mod response;
|
|
||||||
|
|
||||||
use gateway_core::event::{ProtocolWireEvent, ProviderEvent};
|
use gateway_core::event::{GatewayEvent, ProtocolWireEvent, ProviderEvent, ResponseMeta};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
fn chat_request(stream: bool) -> Value {
|
fn chat_request(stream: bool) -> Value {
|
||||||
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
|
json!({"model":"model-a","messages":[{"role":"user","content":"hello"}],"stream":stream})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn wire(kind: &str, mut value: Value) -> ProviderEvent {
|
fn chunk(delta: Value, finish: Value) -> ProviderEvent {
|
||||||
value["type"] = json!(kind);
|
ProviderEvent::wire(
|
||||||
ProviderEvent::wire(ProtocolWireEvent::json("openai", Some(kind.to_owned()), value).unwrap())
|
ProtocolWireEvent::json(
|
||||||
}
|
"chat_completions",
|
||||||
|
None,
|
||||||
fn completed(output: Value) -> ProviderEvent {
|
json!({
|
||||||
wire(
|
"id":"chatcmpl_fixture", "object":"chat.completion.chunk", "created":100,
|
||||||
"response.completed",
|
"model":"model-a", "choices":[{"index":0,"delta":delta,"finish_reason":finish}]
|
||||||
json!({"response":{
|
}),
|
||||||
"id":"resp_chat_test","object":"response","model":"upstream-model",
|
)
|
||||||
"status":"completed","output":output,
|
.unwrap(),
|
||||||
"usage":{"input_tokens":11,"output_tokens":7,"total_tokens":18,
|
|
||||||
"input_tokens_details":{"cached_tokens":3},
|
|
||||||
"output_tokens_details":{"reasoning_tokens":2}}
|
|
||||||
}}),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn message(text: &str) -> Value {
|
fn completed(text: &str) -> ProviderEvent {
|
||||||
json!({"id":"msg_chat_test","type":"message","role":"assistant","status":"completed",
|
chunk(json!({"content":text}), json!("stop")).with_fact(GatewayEvent::Completed(
|
||||||
"content":[{"type":"output_text","text":text,"annotations":[]}]})
|
ResponseMeta::new("upstream_response", "model-a"),
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn created() -> ProviderEvent {
|
fn created() -> ProviderEvent {
|
||||||
wire(
|
chunk(json!({"role":"assistant"}), Value::Null)
|
||||||
"response.created",
|
}
|
||||||
json!({"response":{
|
|
||||||
"id":"resp_chat_test","object":"response","model":"upstream-model",
|
fn json_completed() -> ProviderEvent {
|
||||||
"status":"in_progress","output":[]
|
ProviderEvent::wire(ProtocolWireEvent::raw_json("chat_completions", bytes::Bytes::from(json!({
|
||||||
}}),
|
"id":"chatcmpl_fixture", "object":"chat.completion", "created":100,
|
||||||
)
|
"model":"model-a", "choices":[{"index":0,"message":{"role":"assistant","content":"answer"},"finish_reason":"stop"}]
|
||||||
|
}).to_string())).unwrap()).with_fact(GatewayEvent::Completed(ResponseMeta::new("upstream_response", "model-a")))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -715,17 +715,10 @@ async fn session_policy_rejection_returns_bad_request_with_the_policy_code() {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn continuation_recovery_should_preserve_the_official_retry_signal() {
|
async fn continuation_recovery_should_preserve_the_official_retry_signal() {
|
||||||
let error = GatewayError::from_provider(
|
let error = GatewayError::from_provider(&ProviderError::responses_replay_required(
|
||||||
&ProviderError::new(
|
"scope_unavailable",
|
||||||
ProviderErrorKind::ContinuationRecoveryRequired,
|
UpstreamSendState::NotSent,
|
||||||
UpstreamSendState::NotSent,
|
));
|
||||||
)
|
|
||||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
|
||||||
"Previous response was not found. Retrying the full request.",
|
|
||||||
Some("previous_response_not_found".to_owned()),
|
|
||||||
Some("invalid_request_error".to_owned()),
|
|
||||||
)),
|
|
||||||
);
|
|
||||||
|
|
||||||
let response = gateway_error_response(&error);
|
let response = gateway_error_response(&error);
|
||||||
let status = response.status();
|
let status = response.status();
|
||||||
@@ -894,3 +887,30 @@ fn final_connection_failures_and_local_capacity_have_distinct_http_statuses() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn local_request_details_survive_execution_without_exposing_the_diagnostic_source() {
|
||||||
|
for with_details in [false, true] {
|
||||||
|
let mut provider =
|
||||||
|
ProviderError::invalid_request("The parameter is not supported by this upstream.")
|
||||||
|
.with_source(std::io::Error::other("PRIVATE_REQUEST_CONTENT"));
|
||||||
|
if with_details {
|
||||||
|
provider = provider
|
||||||
|
.with_request_details("unsupported_parameter", Some("tools[0].custom.format"));
|
||||||
|
}
|
||||||
|
let error = EngineError::Provider(provider.stable_snapshot());
|
||||||
|
let response = engine_error_response(&error);
|
||||||
|
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||||
|
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
|
let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
|
||||||
|
assert_eq!(body["error"]["type"], "invalid_request_error");
|
||||||
|
if with_details {
|
||||||
|
assert_eq!(body["error"]["code"], "unsupported_parameter");
|
||||||
|
assert_eq!(body["error"]["param"], "tools[0].custom.format");
|
||||||
|
} else {
|
||||||
|
assert_eq!(body["error"]["code"], "invalid_request");
|
||||||
|
assert!(body["error"].get("param").is_none());
|
||||||
|
}
|
||||||
|
assert!(!String::from_utf8_lossy(&bytes).contains("PRIVATE_REQUEST_CONTENT"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,117 @@
|
|||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn google_api_key_authenticates_native_endpoints_without_changing_wire() {
|
||||||
|
for action in [
|
||||||
|
"generateContent",
|
||||||
|
"streamGenerateContent?alt=sse",
|
||||||
|
"countTokens",
|
||||||
|
] {
|
||||||
|
let stream = action.starts_with("stream");
|
||||||
|
let raw = if action == "countTokens" {
|
||||||
|
Bytes::from_static(br#"{ "totalTokens":42 }"#)
|
||||||
|
} else {
|
||||||
|
Bytes::from_static(br#"{ "candidates":[{"content":{"parts":[{"text":"ok"}]},"finishReason":"STOP"}] }"#)
|
||||||
|
};
|
||||||
|
let frame = "data: { \"candidates\":[{\"content\":{\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}] }\n\n";
|
||||||
|
let event = if stream {
|
||||||
|
wire_frame(frame)
|
||||||
|
} else {
|
||||||
|
ProviderEvent::wire(ProtocolWireEvent::raw_json(GENAI_PROTOCOL, raw.clone()).unwrap())
|
||||||
|
};
|
||||||
|
let execution = Arc::new(Execution {
|
||||||
|
session: Mutex::new(Some(Session::new(vec![event]))),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let mut req = request(&format!("{SHORT}:{action}"));
|
||||||
|
req.headers_mut().remove("authorization");
|
||||||
|
req.headers_mut()
|
||||||
|
.insert("x-goog-api-key", KEY.parse().unwrap());
|
||||||
|
let response = api_router(execution.clone())
|
||||||
|
.await
|
||||||
|
.oneshot(req)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(response.status(), StatusCode::OK, "{action}");
|
||||||
|
let expected = if stream { frame.as_bytes() } else { &raw };
|
||||||
|
assert_eq!(
|
||||||
|
to_bytes(response.into_body(), 2048).await.unwrap().as_ref(),
|
||||||
|
expected
|
||||||
|
);
|
||||||
|
let captured = execution.seen.lock().unwrap().take().unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
captured.operation.middleware_body().unwrap().as_ref(),
|
||||||
|
BODY.as_bytes()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn google_api_key_reuses_validation_and_never_overrides_authorization() {
|
||||||
|
use axum::http::HeaderValue;
|
||||||
|
|
||||||
|
let execution = Arc::new(Execution::default());
|
||||||
|
let router = api_router(execution.clone()).await;
|
||||||
|
for (authorization, key, status) in [
|
||||||
|
(None, Some(HeaderValue::from_static(KEY)), StatusCode::OK),
|
||||||
|
(None, None, StatusCode::UNAUTHORIZED),
|
||||||
|
(
|
||||||
|
None,
|
||||||
|
Some(HeaderValue::from_static("invalid")),
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
None,
|
||||||
|
Some(HeaderValue::from_static("")),
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
None,
|
||||||
|
Some(HeaderValue::from_bytes(b"\xff").unwrap()),
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
Some("Bearer invalid"),
|
||||||
|
Some(HeaderValue::from_static(KEY)),
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
Some("Basic invalid"),
|
||||||
|
Some(HeaderValue::from_static(KEY)),
|
||||||
|
StatusCode::UNAUTHORIZED,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
Some("Bearer sk_genai_test"),
|
||||||
|
Some(HeaderValue::from_static("invalid")),
|
||||||
|
StatusCode::OK,
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let mut req = request("/v1beta:recordCodeAssistMetrics");
|
||||||
|
req.headers_mut().remove("authorization");
|
||||||
|
if let Some(value) = authorization {
|
||||||
|
req.headers_mut()
|
||||||
|
.insert("authorization", value.parse().unwrap());
|
||||||
|
}
|
||||||
|
if let Some(value) = key {
|
||||||
|
req.headers_mut().insert("x-goog-api-key", value);
|
||||||
|
}
|
||||||
|
assert_eq!(router.clone().oneshot(req).await.unwrap().status(), status);
|
||||||
|
}
|
||||||
|
for path in ["/v1/models", "/v1/usage", "/v1/cpr/link"] {
|
||||||
|
let req = Request::get(path)
|
||||||
|
.header("x-goog-api-key", KEY)
|
||||||
|
.body(Body::empty())
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
router.clone().oneshot(req).await.unwrap().status(),
|
||||||
|
StatusCode::UNAUTHORIZED
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(execution.seen.lock().unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn session_headers_reach_provider_context_except_when_declared_hop_by_hop() {
|
async fn session_headers_reach_provider_context_except_when_declared_hop_by_hop() {
|
||||||
@@ -183,15 +294,16 @@ async fn committed_stream_delivers_raw_error_once() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test(start_paused = true)]
|
||||||
async fn stream_preserves_finish_and_later_usage_bytes_before_eof() {
|
async fn silent_stream_delivers_only_native_finish_and_late_usage_frames() {
|
||||||
let first = "data: { \"candidates\":[{\"finishReason\":\"STOP\"}], \"error\":null }\r\n\r\n";
|
let first = "data: { \"candidates\":[{\"finishReason\":\"STOP\"}], \"error\":null }\r\n\r\n";
|
||||||
let last = "data: {\"usageMetadata\":{\"totalTokenCount\":7}}\r\n\r\n";
|
let last = "data: {\"usageMetadata\":{\"totalTokenCount\":7}}\r\n\r\n";
|
||||||
let mut events = vec![wire_frame(first), wire_frame(last)];
|
let mut events = vec![wire_frame(first), wire_frame(last)];
|
||||||
events.push(ProviderEvent::canonical(GatewayEvent::Completed(
|
events.push(ProviderEvent::canonical(GatewayEvent::Completed(
|
||||||
ResponseMeta::new("id", "model-a"),
|
ResponseMeta::new("id", "model-a"),
|
||||||
)));
|
)));
|
||||||
let session = Session::new(events);
|
let mut session = Session::new(events);
|
||||||
|
session.read_delay = Some(Duration::from_secs(45));
|
||||||
let trace = session.trace.clone();
|
let trace = session.trace.clone();
|
||||||
let execution = Arc::new(Execution {
|
let execution = Arc::new(Execution {
|
||||||
session: Mutex::new(Some(session)),
|
session: Mutex::new(Some(session)),
|
||||||
@@ -211,6 +323,27 @@ async fn stream_preserves_finish_and_later_usage_bytes_before_eof() {
|
|||||||
assert!(trace.finalized.load(Ordering::SeqCst));
|
assert!(trace.finalized.load(Ordering::SeqCst));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test(start_paused = true)]
|
||||||
|
async fn error_after_waiting_for_first_frame_preserves_http_status() {
|
||||||
|
let mut session = Session::new(Vec::new());
|
||||||
|
session.read_delay = Some(Duration::from_secs(45));
|
||||||
|
session.finish = Finish::Error;
|
||||||
|
let execution = Arc::new(Execution {
|
||||||
|
session: Mutex::new(Some(session)),
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let response = api_router(execution)
|
||||||
|
.await
|
||||||
|
.oneshot(request(&format!("{SHORT}:streamGenerateContent?alt=sse")))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let status = response.status();
|
||||||
|
assert!(status.is_server_error());
|
||||||
|
let body: Value =
|
||||||
|
serde_json::from_slice(&to_bytes(response.into_body(), 2048).await.unwrap()).unwrap();
|
||||||
|
assert_eq!(body["error"]["code"], status.as_u16());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn metric_validates_bearer_and_invalid_generation_never_starts_inference() {
|
async fn metric_validates_bearer_and_invalid_generation_never_starts_inference() {
|
||||||
let execution = Arc::new(Execution::default());
|
let execution = Arc::new(Execution::default());
|
||||||
|
|||||||
@@ -123,3 +123,24 @@ async fn directory_errors_follow_google_rpc_and_require_authentication() {
|
|||||||
assert_eq!(body["error"]["code"], status.as_u16(), "{path}");
|
assert_eq!(body["error"]["code"], status.as_u16(), "{path}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn google_api_key_reads_the_same_authorized_catalog() {
|
||||||
|
let router = api_router(Arc::new(Execution {
|
||||||
|
client: Some(client()),
|
||||||
|
..Default::default()
|
||||||
|
}))
|
||||||
|
.await;
|
||||||
|
for path in ["/v1beta/models", "/v1beta/models/model-a"] {
|
||||||
|
let (expected_status, expected) = query(&router, path, true).await;
|
||||||
|
let request = Request::get(path)
|
||||||
|
.header("x-goog-api-key", KEY)
|
||||||
|
.body(Body::empty())
|
||||||
|
.unwrap();
|
||||||
|
let response = router.clone().oneshot(request).await.unwrap();
|
||||||
|
assert_eq!(response.status(), expected_status);
|
||||||
|
let actual: Value =
|
||||||
|
serde_json::from_slice(&to_bytes(response.into_body(), 8192).await.unwrap()).unwrap();
|
||||||
|
assert_eq!(actual, expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,17 +5,14 @@ mod chat_completions;
|
|||||||
mod error;
|
mod error;
|
||||||
mod genai;
|
mod genai;
|
||||||
mod group_permissions;
|
mod group_permissions;
|
||||||
mod images;
|
|
||||||
mod live;
|
|
||||||
mod messages;
|
mod messages;
|
||||||
mod middleware;
|
mod middleware;
|
||||||
mod models;
|
mod models;
|
||||||
mod openai_endpoints;
|
mod openai;
|
||||||
mod peer_link;
|
mod peer_link;
|
||||||
mod provider_endpoints;
|
mod provider_endpoints;
|
||||||
mod responses;
|
mod responses;
|
||||||
mod router;
|
mod router;
|
||||||
mod search;
|
|
||||||
mod usage;
|
mod usage;
|
||||||
|
|
||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|||||||
+1
-1
@@ -30,7 +30,7 @@ use gateway_core::upstream::UpstreamSendState;
|
|||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
|
|
||||||
use super::{api_router, authenticated_client};
|
use crate::data_plane::{api_router, authenticated_client};
|
||||||
|
|
||||||
const IMAGE_RESPONSE: &[u8] =
|
const IMAGE_RESPONSE: &[u8] =
|
||||||
br#"{ "created": 1787212800, "data": [{"b64_json":"AAEC"}], "future": 9007199254740993 }"#;
|
br#"{ "created": 1787212800, "data": [{"b64_json":"AAEC"}], "future": 9007199254740993 }"#;
|
||||||
+3
-3
@@ -22,9 +22,9 @@ use gateway_core::operation::Operation;
|
|||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
|
|
||||||
use super::api_router;
|
use crate::data_plane::api_router;
|
||||||
use super::authenticated_client;
|
use crate::data_plane::authenticated_client;
|
||||||
use super::models::ModelsExecution;
|
use crate::data_plane::models::ModelsExecution;
|
||||||
|
|
||||||
const LIVE_KEY: &str = "sk_live_test";
|
const LIVE_KEY: &str = "sk_live_test";
|
||||||
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
//! OpenAI 专属端点的路由、透传与交付测试
|
||||||
|
|
||||||
|
mod endpoints;
|
||||||
|
mod images;
|
||||||
|
mod live;
|
||||||
|
mod search;
|
||||||
+2
-2
@@ -26,8 +26,8 @@ use gateway_core::upstream::UpstreamSendState;
|
|||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
|
|
||||||
use super::openai_endpoints::BufferedJsonSession;
|
use super::endpoints::BufferedJsonSession;
|
||||||
use super::{api_router, authenticated_client};
|
use crate::data_plane::{api_router, authenticated_client};
|
||||||
|
|
||||||
const SEARCH_RESPONSE: &[u8] = br#"{ "encrypted_output":"ciphertext", "output":"search result", "results":[{"type":"text_result","ref_id":"turn0search0","future":9007199254740993}] }"#;
|
const SEARCH_RESPONSE: &[u8] = br#"{ "encrypted_output":"ciphertext", "output":"search result", "results":[{"type":"text_result","ref_id":"turn0search0","future":9007199254740993}] }"#;
|
||||||
|
|
||||||
@@ -41,7 +41,6 @@ use gateway_core::upstream::{OpaqueUpstreamValue, UpstreamSendState};
|
|||||||
use gateway_protocol::openai::sse::{encode_sse_event, parse_sse_events};
|
use gateway_protocol::openai::sse::{encode_sse_event, parse_sse_events};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
use gateway_api::data_plane::responses::{collect_execution_response, stream_execution_response};
|
|
||||||
use tower::ServiceExt;
|
use tower::ServiceExt;
|
||||||
|
|
||||||
use crate::data_plane::middleware::{RequestMiddleware, ResponseFrameAction};
|
use crate::data_plane::middleware::{RequestMiddleware, ResponseFrameAction};
|
||||||
@@ -49,6 +48,30 @@ use crate::data_plane::{
|
|||||||
api_router, authenticated_client_for_provider, authenticated_client_with_min_versions,
|
api_router, authenticated_client_for_provider, authenticated_client_with_min_versions,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
async fn execute_session(
|
||||||
|
session: Box<dyn ExecutionSession>,
|
||||||
|
streaming: bool,
|
||||||
|
) -> axum::response::Response {
|
||||||
|
let execution = Arc::new(SessionExecution {
|
||||||
|
client: authenticated_client_for_provider("sk_delivery_test", "openai"),
|
||||||
|
session: Mutex::new(Some(session)),
|
||||||
|
middleware: None,
|
||||||
|
});
|
||||||
|
api_router(execution)
|
||||||
|
.await
|
||||||
|
.oneshot(
|
||||||
|
Request::post("/v1/responses")
|
||||||
|
.header(AUTHORIZATION, "Bearer sk_delivery_test")
|
||||||
|
.body(Body::from(
|
||||||
|
json!({"model": "model-a", "input": "synthetic", "stream": streaming})
|
||||||
|
.to_string(),
|
||||||
|
))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
fn responses_middleware() -> RequestMiddleware {
|
fn responses_middleware() -> RequestMiddleware {
|
||||||
RequestMiddleware {
|
RequestMiddleware {
|
||||||
expected_operation: Some(OperationKind::Generate),
|
expected_operation: Some(OperationKind::Generate),
|
||||||
@@ -930,7 +953,7 @@ async fn streaming_encodes_first_frame_before_commit_and_http_delivery() {
|
|||||||
))],
|
))],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
|
|
||||||
assert_eq!(response.status(), axum::http::StatusCode::OK);
|
assert_eq!(response.status(), axum::http::StatusCode::OK);
|
||||||
assert_eq!(trace.client_statuses(), vec![200]);
|
assert_eq!(trace.client_statuses(), vec![200]);
|
||||||
@@ -1225,7 +1248,7 @@ async fn streaming_should_keep_alive_during_silent_compaction_without_restarting
|
|||||||
NextStep::FinalizeSuccess,
|
NextStep::FinalizeSuccess,
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let mut body = response.into_body().into_data_stream();
|
let mut body = response.into_body().into_data_stream();
|
||||||
let first = body.next().await.expect("first frame").expect("body bytes");
|
let first = body.next().await.expect("first frame").expect("body bytes");
|
||||||
assert!(String::from_utf8_lossy(&first).contains("response.created"));
|
assert!(String::from_utf8_lossy(&first).contains("response.created"));
|
||||||
@@ -1280,7 +1303,7 @@ async fn dropping_stream_during_keepalive_should_cancel_and_finalize_execution()
|
|||||||
NextStep::FinalizeCancelled,
|
NextStep::FinalizeCancelled,
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let mut body = response.into_body().into_data_stream();
|
let mut body = response.into_body().into_data_stream();
|
||||||
let _ = body.next().await.expect("first frame").expect("body bytes");
|
let _ = body.next().await.expect("first frame").expect("body bytes");
|
||||||
let heartbeat = tokio::time::timeout(Duration::from_secs(20), body.next())
|
let heartbeat = tokio::time::timeout(Duration::from_secs(20), body.next())
|
||||||
@@ -1317,7 +1340,7 @@ async fn streaming_keepalive_should_cover_four_minutes_before_first_event() {
|
|||||||
let start = tokio::time::Instant::now();
|
let start = tokio::time::Instant::now();
|
||||||
let response = tokio::time::timeout(
|
let response = tokio::time::timeout(
|
||||||
Duration::from_secs(20),
|
Duration::from_secs(20),
|
||||||
stream_execution_response(Box::new(session), None),
|
execute_session(Box::new(session), true),
|
||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.expect("headers and heartbeat must precede the first upstream event");
|
.expect("headers and heartbeat must precede the first upstream event");
|
||||||
@@ -1361,7 +1384,7 @@ async fn streaming_error_after_initial_keepalive_should_be_a_terminal_sse_failur
|
|||||||
)],
|
)],
|
||||||
)
|
)
|
||||||
.with_response_headers(headers(&[("x-codex-turn-state", "private-attempt-state")]));
|
.with_response_headers(headers(&[("x-codex-turn-state", "private-attempt-state")]));
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
assert!(!response.headers().contains_key("x-codex-turn-state"));
|
assert!(!response.headers().contains_key("x-codex-turn-state"));
|
||||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
@@ -1400,7 +1423,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
|
|||||||
Arc::new(Trace::default()),
|
Arc::new(Trace::default()),
|
||||||
vec![NextStep::Error(EngineError::Provider(failure()))],
|
vec![NextStep::Error(EngineError::Provider(failure()))],
|
||||||
);
|
);
|
||||||
let response = stream_execution_response(Box::new(immediate), None).await;
|
let response = execute_session(Box::new(immediate), true).await;
|
||||||
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
||||||
assert_eq!(response.headers()[CONTENT_TYPE], "application/json");
|
assert_eq!(response.headers()[CONTENT_TYPE], "application/json");
|
||||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
@@ -1415,7 +1438,7 @@ async fn streaming_bad_request_preserves_extended_error_fields_before_and_after_
|
|||||||
EngineError::Provider(failure()),
|
EngineError::Provider(failure()),
|
||||||
)],
|
)],
|
||||||
);
|
);
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
let events = parse_sse_events(std::str::from_utf8(&bytes).unwrap()).unwrap();
|
let events = parse_sse_events(std::str::from_utf8(&bytes).unwrap()).unwrap();
|
||||||
@@ -1502,7 +1525,7 @@ async fn dropping_stream_before_first_event_should_cancel_the_original_wait() {
|
|||||||
NextStep::FinalizeCancelled,
|
NextStep::FinalizeCancelled,
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let mut body = response.into_body().into_data_stream();
|
let mut body = response.into_body().into_data_stream();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
body.next().await.unwrap().unwrap(),
|
body.next().await.unwrap().unwrap(),
|
||||||
@@ -1529,7 +1552,7 @@ async fn streaming_response_should_disable_proxy_buffering_and_cache_transformat
|
|||||||
ProviderResponseHeader::new("cache-control", Bytes::from_static(b"public, max-age=60")),
|
ProviderResponseHeader::new("cache-control", Bytes::from_static(b"public, max-age=60")),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
|
|
||||||
assert_eq!(response.headers()["x-accel-buffering"], "no");
|
assert_eq!(response.headers()["x-accel-buffering"], "no");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1581,7 +1604,7 @@ async fn streaming_response_should_append_ordinary_headers_and_skip_unrepresenta
|
|||||||
)
|
)
|
||||||
.with_response_headers(headers);
|
.with_response_headers(headers);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
response
|
response
|
||||||
@@ -1674,7 +1697,7 @@ async fn streaming_commit_batch_preserves_pre_identity_wire_before_committing()
|
|||||||
vec![NextStep::Event(batch), NextStep::FinalizeSuccess],
|
vec![NextStep::Event(batch), NextStep::FinalizeSuccess],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read SSE body");
|
.expect("read SSE body");
|
||||||
@@ -1706,7 +1729,7 @@ async fn streaming_first_frame_encode_failure_cancels_before_commit() {
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
response.status(),
|
response.status(),
|
||||||
@@ -1728,7 +1751,7 @@ async fn streaming_rate_limit_before_first_frame_should_persist_the_returned_429
|
|||||||
))],
|
))],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
|
|
||||||
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
assert_eq!(trace.client_statuses(), vec![429]);
|
assert_eq!(trace.client_statuses(), vec![429]);
|
||||||
@@ -1755,7 +1778,7 @@ async fn streaming_failure_before_first_frame_should_return_safe_observed_header
|
|||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
|
|
||||||
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1795,7 +1818,7 @@ async fn streaming_upstream_http_failure_before_first_frame_should_preserve_raw_
|
|||||||
vec![NextStep::Error(EngineError::Provider(error))],
|
vec![NextStep::Error(EngineError::Provider(error))],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
|
|
||||||
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1867,7 +1890,7 @@ async fn buffered_upstream_http_failure_should_preserve_raw_response() {
|
|||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let response = collect_execution_response(Box::new(session)).await;
|
let response = execute_session(Box::new(session), false).await;
|
||||||
|
|
||||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
@@ -1902,7 +1925,7 @@ async fn streaming_canonical_identity_change_does_not_interrupt_wire_delivery()
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read SSE body");
|
.expect("read SSE body");
|
||||||
@@ -1943,7 +1966,7 @@ async fn streaming_success_should_emit_terminal_event_and_done_marker() {
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read complete SSE body");
|
.expect("read complete SSE body");
|
||||||
@@ -1967,35 +1990,47 @@ async fn streaming_success_should_emit_terminal_event_and_done_marker() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn streaming_finalized_unknown_wire_should_end_cleanly_without_synthetic_failure() {
|
async fn streaming_finalized_native_wire_should_end_cleanly() {
|
||||||
let trace = Arc::new(Trace::default());
|
let completed = json!({
|
||||||
let raw = Bytes::from_static(
|
"type": "response.completed",
|
||||||
b"event: response.future_terminal\ndata: {\"type\":\"response.future_terminal\",\"opaque\":true}\n\n",
|
"response": {
|
||||||
);
|
"id": "resp_test", "object": "response", "model": "public-model", "status": "completed",
|
||||||
let event = ProviderEvent::wire(
|
"output": [{"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "native baseline"}]}]
|
||||||
ProtocolWireEvent::raw_sse("openai", raw.clone()).expect("raw future event"),
|
}
|
||||||
);
|
});
|
||||||
let session = FakeSession::streaming(
|
let frames = [
|
||||||
Arc::clone(&trace),
|
Bytes::from_static(
|
||||||
vec![
|
b"event: response.future_terminal\ndata: {\"type\":\"response.future_terminal\",\"opaque\":true}\n\n",
|
||||||
NextStep::Event(delivery_provider(
|
),
|
||||||
event,
|
Bytes::from(format!("event: response.completed\ndata: {completed}\n\n")),
|
||||||
CommitRequirement::CommitBeforeDelivery,
|
];
|
||||||
)),
|
for raw in frames {
|
||||||
NextStep::FinalizeSuccess,
|
let trace = Arc::new(Trace::default());
|
||||||
],
|
let event = ProviderEvent::wire(
|
||||||
);
|
ProtocolWireEvent::raw_sse("openai", raw.clone()).expect("native wire event"),
|
||||||
|
);
|
||||||
|
let session = FakeSession::streaming(
|
||||||
|
Arc::clone(&trace),
|
||||||
|
vec![
|
||||||
|
NextStep::Event(delivery_provider(
|
||||||
|
event,
|
||||||
|
CommitRequirement::CommitBeforeDelivery,
|
||||||
|
)),
|
||||||
|
NextStep::FinalizeSuccess,
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read transparent SSE body");
|
.expect("read transparent SSE body");
|
||||||
|
|
||||||
assert!(body.as_ref().starts_with(raw.as_ref()));
|
let expected = [raw.as_ref(), b"data: [DONE]\n\n"].concat();
|
||||||
assert!(body.as_ref().ends_with(b"data: [DONE]\n\n"));
|
assert_eq!(body.as_ref(), expected.as_slice());
|
||||||
assert!(!String::from_utf8_lossy(&body).contains("response.failed"));
|
assert!(!trace.is_cancelled());
|
||||||
assert!(!trace.is_cancelled());
|
assert_eq!(trace.snapshot(), vec!["next_event", "commit", "next_end"]);
|
||||||
assert_eq!(trace.snapshot(), vec!["next_event", "commit", "next_end"]);
|
assert_eq!(trace.detached_finalizations(), 0);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
@@ -2011,7 +2046,7 @@ async fn streaming_completed_event_without_finalized_execution_should_fail_close
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read failed SSE body");
|
.expect("read failed SSE body");
|
||||||
@@ -2047,7 +2082,7 @@ async fn streaming_empty_terminal_should_emit_failure_done_and_cancel_execution(
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read failed SSE body");
|
.expect("read failed SSE body");
|
||||||
@@ -2080,7 +2115,7 @@ async fn streaming_error_should_emit_client_visible_upstream_details() {
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read SSE body");
|
.expect("read SSE body");
|
||||||
@@ -2154,7 +2189,7 @@ async fn streaming_upstream_wire_failure_should_not_be_rewritten_as_a_gateway_er
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read SSE body");
|
.expect("read SSE body");
|
||||||
@@ -2259,7 +2294,7 @@ async fn streaming_upstream_error_event_should_be_translated_to_response_failed_
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
@@ -2330,7 +2365,7 @@ async fn streaming_capacity_error_after_commit_offers_client_retry() {
|
|||||||
NextStep::Error(EngineError::Provider(error)),
|
NextStep::Error(EngineError::Provider(error)),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let body = to_bytes(response.into_body(), 16 * 1024)
|
let body = to_bytes(response.into_body(), 16 * 1024)
|
||||||
.await
|
.await
|
||||||
@@ -2414,7 +2449,7 @@ async fn atomic_uncommitted_upstream_failure_batch_should_be_forwarded_once() {
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read SSE body");
|
.expect("read SSE body");
|
||||||
@@ -2444,7 +2479,7 @@ async fn streaming_second_commit_request_should_fail_and_finalize_once() {
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read failed SSE body");
|
.expect("read failed SSE body");
|
||||||
@@ -2471,7 +2506,7 @@ async fn streaming_commit_failure_should_not_deliver_the_prepared_first_frame()
|
|||||||
)
|
)
|
||||||
.with_commit_failure();
|
.with_commit_failure();
|
||||||
|
|
||||||
let response = stream_execution_response(Box::new(session), None).await;
|
let response = execute_session(Box::new(session), true).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read error response");
|
.expect("read error response");
|
||||||
@@ -2493,7 +2528,7 @@ async fn buffered_response_commits_only_after_complete_json_is_encoded() {
|
|||||||
let trace = Arc::new(Trace::default());
|
let trace = Arc::new(Trace::default());
|
||||||
let session = FakeSession::buffered(Arc::clone(&trace), vec![started(), completed()]);
|
let session = FakeSession::buffered(Arc::clone(&trace), vec![started(), completed()]);
|
||||||
|
|
||||||
let response = collect_execution_response(Box::new(session)).await;
|
let response = execute_session(Box::new(session), false).await;
|
||||||
let body = to_bytes(response.into_body(), usize::MAX)
|
let body = to_bytes(response.into_body(), usize::MAX)
|
||||||
.await
|
.await
|
||||||
.expect("read JSON body");
|
.expect("read JSON body");
|
||||||
@@ -2558,7 +2593,7 @@ async fn buffered_response_collects_completed_output_items_without_rewriting_str
|
|||||||
|
|
||||||
let trace = Arc::new(Trace::default());
|
let trace = Arc::new(Trace::default());
|
||||||
let session = FakeSession::buffered_provider(Arc::clone(&trace), events);
|
let session = FakeSession::buffered_provider(Arc::clone(&trace), events);
|
||||||
let response = collect_execution_response(Box::new(session)).await;
|
let response = execute_session(Box::new(session), false).await;
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
let mut expected = terminal;
|
let mut expected = terminal;
|
||||||
@@ -2656,7 +2691,7 @@ async fn native_responses_route_preserves_images_and_encrypted_reasoning_in_json
|
|||||||
} else {
|
} else {
|
||||||
FakeSession::buffered_provider(Arc::clone(&trace), events)
|
FakeSession::buffered_provider(Arc::clone(&trace), events)
|
||||||
};
|
};
|
||||||
// 使用真实 /v1/responses 入口,覆盖共享执行函数的可选适配器为空分支
|
// 使用真实 /v1/responses 入口验证原生字段与 SSE 字节交付
|
||||||
let response = response(&admin, "openai", session, streaming).await;
|
let response = response(&admin, "openai", session, streaming).await;
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
@@ -2703,7 +2738,7 @@ async fn buffered_response_keeps_authoritative_terminal_and_supports_omitted_out
|
|||||||
super::openai_wire_event(vec![], event_type, json!({"response": terminal})),
|
super::openai_wire_event(vec![], event_type, json!({"response": terminal})),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
let response = collect_execution_response(Box::new(session)).await;
|
let response = execute_session(Box::new(session), false).await;
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
let mut expected = terminal;
|
let mut expected = terminal;
|
||||||
@@ -2740,10 +2775,10 @@ async fn buffered_response_rejects_incomplete_or_conflicting_output_items_before
|
|||||||
"response.completed",
|
"response.completed",
|
||||||
json!({"response": {"id": "resp_test", "output": []}}),
|
json!({"response": {"id": "resp_test", "output": []}}),
|
||||||
));
|
));
|
||||||
let response = collect_execution_response(Box::new(FakeSession::buffered_provider(
|
let response = execute_session(
|
||||||
Arc::clone(&trace),
|
Box::new(FakeSession::buffered_provider(Arc::clone(&trace), events)),
|
||||||
events,
|
false,
|
||||||
)))
|
)
|
||||||
.await;
|
.await;
|
||||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
@@ -2773,10 +2808,10 @@ async fn buffered_response_never_merges_items_from_a_different_wire_response() {
|
|||||||
super::openai_wire_event(vec![], "response.output_item.done", conflicting_event),
|
super::openai_wire_event(vec![], "response.output_item.done", conflicting_event),
|
||||||
super::openai_wire_event(vec![], "response.completed", json!({"response": terminal})),
|
super::openai_wire_event(vec![], "response.completed", json!({"response": terminal})),
|
||||||
];
|
];
|
||||||
let response = collect_execution_response(Box::new(FakeSession::buffered_provider(
|
let response = execute_session(
|
||||||
Arc::clone(&trace),
|
Box::new(FakeSession::buffered_provider(Arc::clone(&trace), events)),
|
||||||
events,
|
false,
|
||||||
)))
|
)
|
||||||
.await;
|
.await;
|
||||||
assert_eq!(response.status(), StatusCode::OK);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||||
@@ -2874,7 +2909,7 @@ async fn buffered_response_forwards_long_ordinary_provider_header_values() {
|
|||||||
let session = FakeSession::buffered(Arc::clone(&trace), vec![started(), completed()])
|
let session = FakeSession::buffered(Arc::clone(&trace), vec![started(), completed()])
|
||||||
.with_response_headers(vec![header]);
|
.with_response_headers(vec![header]);
|
||||||
|
|
||||||
let response = collect_execution_response(Box::new(session)).await;
|
let response = execute_session(Box::new(session), false).await;
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
response
|
response
|
||||||
@@ -2893,7 +2928,7 @@ async fn buffered_encode_failure_cancels_without_commit() {
|
|||||||
vec![ProviderEvent::canonical(completed())],
|
vec![ProviderEvent::canonical(completed())],
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = collect_execution_response(Box::new(session)).await;
|
let response = execute_session(Box::new(session), false).await;
|
||||||
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
response.status(),
|
response.status(),
|
||||||
@@ -2910,7 +2945,7 @@ async fn buffered_commit_failure_should_cancel_after_encoding_without_returning_
|
|||||||
let session = FakeSession::buffered(Arc::clone(&trace), vec![started(), completed()])
|
let session = FakeSession::buffered(Arc::clone(&trace), vec![started(), completed()])
|
||||||
.with_commit_failure();
|
.with_commit_failure();
|
||||||
|
|
||||||
let response = collect_execution_response(Box::new(session)).await;
|
let response = execute_session(Box::new(session), false).await;
|
||||||
let status = response.status();
|
let status = response.status();
|
||||||
|
|
||||||
assert_eq!(status, axum::http::StatusCode::INTERNAL_SERVER_ERROR);
|
assert_eq!(status, axum::http::StatusCode::INTERNAL_SERVER_ERROR);
|
||||||
@@ -2926,7 +2961,7 @@ async fn buffered_commit_failure_should_cancel_after_encoding_without_returning_
|
|||||||
async fn dropping_buffered_handler_before_commit_cancels_execution() {
|
async fn dropping_buffered_handler_before_commit_cancels_execution() {
|
||||||
let trace = Arc::new(Trace::default());
|
let trace = Arc::new(Trace::default());
|
||||||
let session = FakeSession::pending_buffered(Arc::clone(&trace));
|
let session = FakeSession::pending_buffered(Arc::clone(&trace));
|
||||||
let task = tokio::spawn(async move { collect_execution_response(Box::new(session)).await });
|
let task = tokio::spawn(async move { execute_session(Box::new(session), false).await });
|
||||||
tokio::task::yield_now().await;
|
tokio::task::yield_now().await;
|
||||||
|
|
||||||
task.abort();
|
task.abort();
|
||||||
@@ -2947,7 +2982,7 @@ async fn buffered_rate_limit_should_persist_the_returned_429_status() {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
let response = collect_execution_response(Box::new(session)).await;
|
let response = execute_session(Box::new(session), false).await;
|
||||||
|
|
||||||
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
assert_eq!(trace.client_statuses(), vec![429]);
|
assert_eq!(trace.client_statuses(), vec![429]);
|
||||||
|
|||||||
@@ -371,7 +371,6 @@ fn decoder_should_preserve_the_openai_body_and_only_derive_stable_routing_facts(
|
|||||||
]))
|
]))
|
||||||
);
|
);
|
||||||
assert!(!decoded.metadata().stream());
|
assert!(!decoded.metadata().stream());
|
||||||
assert!(decoded.metadata().store());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -59,6 +59,7 @@ struct CrossingLimitTrace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
struct CrossingLimitSession {
|
struct CrossingLimitSession {
|
||||||
|
response_id: String,
|
||||||
trace: Arc<CrossingLimitTrace>,
|
trace: Arc<CrossingLimitTrace>,
|
||||||
started_emitted: bool,
|
started_emitted: bool,
|
||||||
terminal_emitted: bool,
|
terminal_emitted: bool,
|
||||||
@@ -70,12 +71,13 @@ impl ExecutionSession for CrossingLimitSession {
|
|||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
if !self.started_emitted {
|
if !self.started_emitted {
|
||||||
self.started_emitted = true;
|
self.started_emitted = true;
|
||||||
return Ok(Some(crossing_limit_started_batch()));
|
return Ok(Some(crossing_limit_started_batch(&self.response_id)));
|
||||||
}
|
}
|
||||||
if !self.terminal_emitted {
|
if !self.terminal_emitted {
|
||||||
self.trace.release_terminal.notified().await;
|
self.trace.release_terminal.notified().await;
|
||||||
self.terminal_emitted = true;
|
self.terminal_emitted = true;
|
||||||
return Ok(Some(crossing_limit_terminal_batch(
|
return Ok(Some(crossing_limit_terminal_batch(
|
||||||
|
&self.response_id,
|
||||||
self.trace.reconnect_for_replay.load(Ordering::Acquire),
|
self.trace.reconnect_for_replay.load(Ordering::Acquire),
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
@@ -145,7 +147,7 @@ impl ExecutionService for CrossingLimitExecution {
|
|||||||
request: StartExecution,
|
request: StartExecution,
|
||||||
) -> BoxFuture<'_, Result<StartedExecution, GatewayError>> {
|
) -> BoxFuture<'_, Result<StartedExecution, GatewayError>> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
self.trace.starts.fetch_add(1, Ordering::AcqRel);
|
let sequence = self.trace.starts.fetch_add(1, Ordering::AcqRel) + 1;
|
||||||
if let Operation::Generate(generate) = &request.operation {
|
if let Operation::Generate(generate) = &request.operation {
|
||||||
self.trace
|
self.trace
|
||||||
.inputs
|
.inputs
|
||||||
@@ -154,11 +156,14 @@ impl ExecutionService for CrossingLimitExecution {
|
|||||||
.push(generate.protocol_payload().body()["input"].clone());
|
.push(generate.protocol_payload().body()["input"].clone());
|
||||||
}
|
}
|
||||||
Ok(StartedExecution {
|
Ok(StartedExecution {
|
||||||
request_id: gateway_core::engine::ModelRequestId::new("req_ws_crossing_limit")
|
request_id: gateway_core::engine::ModelRequestId::new(format!(
|
||||||
.expect("request id"),
|
"req_ws_crossing_limit_{sequence}"
|
||||||
|
))
|
||||||
|
.expect("request id"),
|
||||||
created_at: SystemTime::now(),
|
created_at: SystemTime::now(),
|
||||||
stream: request.metadata.stream,
|
stream: request.metadata.stream,
|
||||||
session: Box::new(CrossingLimitSession {
|
session: Box::new(CrossingLimitSession {
|
||||||
|
response_id: format!("resp_ws_crossing_limit_{sequence}"),
|
||||||
trace: Arc::clone(&self.trace),
|
trace: Arc::clone(&self.trace),
|
||||||
started_emitted: false,
|
started_emitted: false,
|
||||||
terminal_emitted: false,
|
terminal_emitted: false,
|
||||||
@@ -176,10 +181,10 @@ impl ExecutionService for CrossingLimitExecution {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn crossing_limit_started_batch() -> CoordinatedEvent {
|
fn crossing_limit_started_batch(response_id: &str) -> CoordinatedEvent {
|
||||||
let started = ProviderEvent::canonical_with_wire(
|
let started = ProviderEvent::canonical_with_wire(
|
||||||
vec![GatewayEvent::Started(ResponseMeta::new(
|
vec![GatewayEvent::Started(ResponseMeta::new(
|
||||||
"resp_ws_crossing_limit",
|
response_id,
|
||||||
"model-a",
|
"model-a",
|
||||||
))],
|
))],
|
||||||
ProtocolWireEvent::json(
|
ProtocolWireEvent::json(
|
||||||
@@ -188,7 +193,7 @@ fn crossing_limit_started_batch() -> CoordinatedEvent {
|
|||||||
json!({
|
json!({
|
||||||
"type": "response.created",
|
"type": "response.created",
|
||||||
"response": {
|
"response": {
|
||||||
"id": "resp_ws_crossing_limit",
|
"id": response_id,
|
||||||
"model": "model-a",
|
"model": "model-a",
|
||||||
"status": "in_progress"
|
"status": "in_progress"
|
||||||
}
|
}
|
||||||
@@ -200,7 +205,7 @@ fn crossing_limit_started_batch() -> CoordinatedEvent {
|
|||||||
.expect("started WebSocket batch")
|
.expect("started WebSocket batch")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn crossing_limit_terminal_batch(reconnect: bool) -> CoordinatedEvent {
|
fn crossing_limit_terminal_batch(response_id: &str, reconnect: bool) -> CoordinatedEvent {
|
||||||
let mut completed = ProviderEvent::wire(
|
let mut completed = ProviderEvent::wire(
|
||||||
ProtocolWireEvent::json(
|
ProtocolWireEvent::json(
|
||||||
"openai",
|
"openai",
|
||||||
@@ -208,7 +213,7 @@ fn crossing_limit_terminal_batch(reconnect: bool) -> CoordinatedEvent {
|
|||||||
json!({
|
json!({
|
||||||
"type": "response.completed",
|
"type": "response.completed",
|
||||||
"response": {
|
"response": {
|
||||||
"id": "resp_ws_crossing_limit",
|
"id": response_id,
|
||||||
"model": "model-a",
|
"model": "model-a",
|
||||||
"output": [],
|
"output": [],
|
||||||
"status": "completed"
|
"status": "completed"
|
||||||
@@ -218,11 +223,7 @@ fn crossing_limit_terminal_batch(reconnect: bool) -> CoordinatedEvent {
|
|||||||
.expect("completed wire"),
|
.expect("completed wire"),
|
||||||
);
|
);
|
||||||
if reconnect {
|
if reconnect {
|
||||||
completed.attach_session_update(
|
completed.request_websocket_reconnect();
|
||||||
gateway_core::operation::ProviderSessionState::new("openai", serde_json::Map::new())
|
|
||||||
.unwrap()
|
|
||||||
.with_websocket_reconnect(),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
CoordinatedEvent::try_batch(vec![completed], CommitRequirement::AlreadyCommitted)
|
CoordinatedEvent::try_batch(vec![completed], CommitRequirement::AlreadyCommitted)
|
||||||
.expect("terminal WebSocket batch")
|
.expect("terminal WebSocket batch")
|
||||||
@@ -925,9 +926,19 @@ async fn start_active_response_with(
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn replay_reconnect_waits_for_queued_requests_and_writes_the_last_terminal() {
|
async fn replay_reconnect_waits_for_queued_requests_and_writes_the_last_terminal() {
|
||||||
|
for reconnect_last in [true, false] {
|
||||||
|
check_queued_reconnect(reconnect_last).await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn check_queued_reconnect(reconnect_last: bool) {
|
||||||
let (trace, mut socket, server) = start_active_response().await;
|
let (trace, mut socket, server) = start_active_response().await;
|
||||||
trace.reconnect_for_replay.store(true, Ordering::Release);
|
let with_tool_result = json!([
|
||||||
for input in ["second", "third"] {
|
{"role":"user","content":"check the color"},
|
||||||
|
{"type":"function_call","call_id":"c","name":"lookup","arguments":"{}"},
|
||||||
|
{"type":"function_call_output","call_id":"c","output":"amber"}
|
||||||
|
]);
|
||||||
|
for input in [with_tool_result.clone(), json!("third")] {
|
||||||
socket
|
socket
|
||||||
.send(ClientMessage::Text(
|
.send(ClientMessage::Text(
|
||||||
json!({"type": "response.create", "model": "model-a", "input": input})
|
json!({"type": "response.create", "model": "model-a", "input": input})
|
||||||
@@ -950,6 +961,9 @@ async fn replay_reconnect_waits_for_queued_requests_and_writes_the_last_terminal
|
|||||||
assert_eq!(trace.starts.load(Ordering::Acquire), 1);
|
assert_eq!(trace.starts.load(Ordering::Acquire), 1);
|
||||||
|
|
||||||
for completed_count in 1..=3 {
|
for completed_count in 1..=3 {
|
||||||
|
trace
|
||||||
|
.reconnect_for_replay
|
||||||
|
.store(completed_count < 3 || reconnect_last, Ordering::Release);
|
||||||
trace.release_terminal.notify_one();
|
trace.release_terminal.notify_one();
|
||||||
let expected_types = if completed_count < 3 {
|
let expected_types = if completed_count < 3 {
|
||||||
vec![
|
vec![
|
||||||
@@ -971,6 +985,17 @@ async fn replay_reconnect_waits_for_queued_requests_and_writes_the_last_terminal
|
|||||||
panic!("unexpected frame during serial execution: {message:?}");
|
panic!("unexpected frame during serial execution: {message:?}");
|
||||||
};
|
};
|
||||||
let event: Value = serde_json::from_str(&text).expect("response event JSON");
|
let event: Value = serde_json::from_str(&text).expect("response event JSON");
|
||||||
|
match event["type"].as_str() {
|
||||||
|
Some("response.completed") => assert_eq!(
|
||||||
|
event["response"]["id"],
|
||||||
|
format!("resp_ws_crossing_limit_{completed_count}")
|
||||||
|
),
|
||||||
|
Some("response.created") => assert_eq!(
|
||||||
|
event["response"]["id"],
|
||||||
|
format!("resp_ws_crossing_limit_{}", completed_count + 1)
|
||||||
|
),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
event_types.push(event["type"].as_str().expect("event type").to_owned());
|
event_types.push(event["type"].as_str().expect("event type").to_owned());
|
||||||
}
|
}
|
||||||
assert_eq!(event_types, expected_types);
|
assert_eq!(event_types, expected_types);
|
||||||
@@ -981,16 +1006,27 @@ async fn replay_reconnect_waits_for_queued_requests_and_writes_the_last_terminal
|
|||||||
}
|
}
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
*trace.inputs.lock().expect("input trace lock"),
|
*trace.inputs.lock().expect("input trace lock"),
|
||||||
vec![json!("hello"), json!("second"), json!("third")]
|
vec![json!("hello"), with_tool_result, json!("third")]
|
||||||
);
|
);
|
||||||
assert!(!trace.cancelled.load(Ordering::Acquire));
|
assert!(!trace.cancelled.load(Ordering::Acquire));
|
||||||
|
if !reconnect_last {
|
||||||
|
// 后续请求可选中支持增量续接的 Provider,先前排队让过的关闭提示只属于原响应
|
||||||
|
socket
|
||||||
|
.send(ClientMessage::Ping(vec![9].into()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
let next = tokio::time::timeout(Duration::from_secs(2), socket.next())
|
let next = tokio::time::timeout(Duration::from_secs(2), socket.next())
|
||||||
.await
|
.await
|
||||||
.expect("replay close timeout")
|
.expect("idle connection disposition")
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert!(matches!(next, ClientMessage::Close(Some(frame))
|
if reconnect_last {
|
||||||
if frame.code == CloseCode::Normal && frame.reason == "Reconnect with full input."));
|
assert!(matches!(next, ClientMessage::Close(Some(frame))
|
||||||
|
if frame.code == CloseCode::Normal && frame.reason == "Reconnect with full input."));
|
||||||
|
} else {
|
||||||
|
assert_eq!(next, ClientMessage::Pong(vec![9].into()));
|
||||||
|
}
|
||||||
server.abort();
|
server.abort();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -642,15 +642,8 @@ async fn initial_quota_recovery_delivers_client_projection_instead_of_upstream_s
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn initial_continuation_recovery_delivers_the_official_client_replay_signal() {
|
async fn initial_continuation_recovery_delivers_the_official_client_replay_signal() {
|
||||||
let provider = ProviderError::new(
|
let provider =
|
||||||
ProviderErrorKind::ContinuationRecoveryRequired,
|
ProviderError::responses_replay_required("scope_unavailable", UpstreamSendState::NotSent);
|
||||||
UpstreamSendState::NotSent,
|
|
||||||
)
|
|
||||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
|
||||||
"Previous response was not found. Retrying the full request.",
|
|
||||||
Some("previous_response_not_found".to_owned()),
|
|
||||||
Some("invalid_request_error".to_owned()),
|
|
||||||
));
|
|
||||||
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
let error = initial_error(EngineError::Provider(provider), Vec::new()).await;
|
||||||
assert_eq!(error["type"], "error");
|
assert_eq!(error["type"], "error");
|
||||||
assert_eq!(error["status"], 400);
|
assert_eq!(error["status"], 400);
|
||||||
|
|||||||
@@ -263,6 +263,26 @@ struct InterruptProvider {
|
|||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
impl Provider for InterruptProvider {
|
impl Provider for InterruptProvider {
|
||||||
|
fn local_websocket_prewarm(
|
||||||
|
&self,
|
||||||
|
_: &Operation,
|
||||||
|
id: &ModelRequestId,
|
||||||
|
) -> Option<gateway_core::engine::provider::LocalWebSocketPrewarm> {
|
||||||
|
self.http_only.then(|| {
|
||||||
|
let response_id = format!("resp_{}", id.as_str());
|
||||||
|
let frame = |kind: &str, status: &str| {
|
||||||
|
ProtocolWireEvent::json("openai", Some(kind.to_owned()), json!({
|
||||||
|
"type":kind,"response":{"id":response_id,"model":"model-a","status":status,"output":[]}
|
||||||
|
})).unwrap()
|
||||||
|
};
|
||||||
|
gateway_core::engine::provider::LocalWebSocketPrewarm {
|
||||||
|
created: frame("response.created", "in_progress"),
|
||||||
|
completed: frame("response.completed", "completed"),
|
||||||
|
response_id,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn name(&self) -> &'static str {
|
fn name(&self) -> &'static str {
|
||||||
"openai"
|
"openai"
|
||||||
}
|
}
|
||||||
@@ -516,6 +536,106 @@ fn interrupt(id: &str, mode: &str) -> Value {
|
|||||||
json!({"type":"response.interrupt","response_id":id,"mode":mode,"future_extension":true})
|
json!({"type":"response.interrupt","response_id":id,"mode":mode,"future_extension":true})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn streaming_turn_finishes_before_queued_generation_and_local_prewarm() {
|
||||||
|
let provider = Arc::new(InterruptProvider {
|
||||||
|
http_only: true,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let admissions = Arc::new(InterruptAdmissions::default());
|
||||||
|
let (mut socket, _server) = connect(provider.clone(), admissions.clone()).await;
|
||||||
|
send(
|
||||||
|
&mut socket,
|
||||||
|
json!({"type":"response.create","model":"model-a","input":"first"}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let active = next(&mut socket).await;
|
||||||
|
assert_eq!(active["type"], "response.created");
|
||||||
|
let upstream = provider
|
||||||
|
.transport
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.sender
|
||||||
|
.clone();
|
||||||
|
let chunk = |text: &str| {
|
||||||
|
json!({"type":"response.output_text.delta","response_id":active["response"]["id"],
|
||||||
|
"item_id":"msg_first","output_index":0,"content_index":0,"delta":text})
|
||||||
|
};
|
||||||
|
upstream.send(chunk("one")).await.unwrap();
|
||||||
|
assert_eq!(next(&mut socket).await, chunk("one"));
|
||||||
|
send(
|
||||||
|
&mut socket,
|
||||||
|
json!({"type":"response.create","model":"model-a","input":"second"}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
send(
|
||||||
|
&mut socket,
|
||||||
|
json!({"type":"response.create","model":"model-a","generate":false,"input":[]}),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
socket
|
||||||
|
.send(ClientMessage::Ping(vec![17].into()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let pong = tokio::time::timeout(Duration::from_secs(5), socket.next())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(pong, ClientMessage::Pong(vec![17].into()));
|
||||||
|
assert_eq!(admissions.active.load(Ordering::SeqCst), 1);
|
||||||
|
assert_eq!(provider.calls.load(Ordering::SeqCst), 1);
|
||||||
|
upstream.send(chunk(" two")).await.unwrap();
|
||||||
|
assert_eq!(next(&mut socket).await, chunk(" two"));
|
||||||
|
upstream.send(json!({"type":"response.completed","response":{"id":active["response"]["id"],
|
||||||
|
"model":"model-a","status":"completed","output":[{"type":"message","id":"msg_first",
|
||||||
|
"role":"assistant","content":[{"type":"output_text","text":"one two","annotations":[]}]}]}})).await.unwrap();
|
||||||
|
let first_terminal = next(&mut socket).await;
|
||||||
|
assert_eq!(first_terminal["type"], "response.completed");
|
||||||
|
assert_eq!(first_terminal["response"]["id"], active["response"]["id"]);
|
||||||
|
let second = next(&mut socket).await;
|
||||||
|
assert_eq!(second["type"], "response.created");
|
||||||
|
assert_ne!(second["response"]["id"], active["response"]["id"]);
|
||||||
|
provider.complete.notify_one();
|
||||||
|
let second_terminal = next(&mut socket).await;
|
||||||
|
assert_eq!(second_terminal["type"], "response.completed");
|
||||||
|
assert_eq!(second_terminal["response"]["id"], second["response"]["id"]);
|
||||||
|
let warm = next(&mut socket).await;
|
||||||
|
assert_eq!(warm["type"], "response.created");
|
||||||
|
assert_ne!(warm["response"]["id"], active["response"]["id"]);
|
||||||
|
let completed = next(&mut socket).await;
|
||||||
|
assert_eq!(completed["type"], "response.completed");
|
||||||
|
assert_eq!(completed["response"]["id"], warm["response"]["id"]);
|
||||||
|
let close = tokio::time::timeout(Duration::from_secs(5), socket.next())
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.unwrap()
|
||||||
|
.unwrap();
|
||||||
|
assert!(matches!(close, ClientMessage::Close(Some(frame)) if u16::from(frame.code) == 1000));
|
||||||
|
assert_eq!(provider.calls.load(Ordering::SeqCst), 2);
|
||||||
|
assert_eq!(admissions.active.load(Ordering::SeqCst), 0);
|
||||||
|
let audits = provider.store.finalizations.lock().unwrap();
|
||||||
|
assert_eq!(audits.len(), 3);
|
||||||
|
assert_eq!(audits[0].attempt_count, 1);
|
||||||
|
assert_eq!(audits[1].attempt_count, 1);
|
||||||
|
let local = &audits[2];
|
||||||
|
assert_eq!(
|
||||||
|
local.outcome,
|
||||||
|
gateway_core::engine::ExecutionOutcome::Succeeded
|
||||||
|
);
|
||||||
|
assert_eq!(local.attempt_count, 0);
|
||||||
|
assert_eq!(local.send_state, UpstreamSendState::NotSent);
|
||||||
|
assert_eq!(
|
||||||
|
local.client_response_id.as_deref(),
|
||||||
|
warm["response"]["id"].as_str()
|
||||||
|
);
|
||||||
|
assert!(local.downstream_committed_at.is_some());
|
||||||
|
assert!(local.upstream_response_id.is_none());
|
||||||
|
assert!(local.upstream_transport.is_none());
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn http_response_rejects_interrupt_without_aborting_or_admitting_queued_requests() {
|
async fn http_response_rejects_interrupt_without_aborting_or_admitting_queued_requests() {
|
||||||
let provider = Arc::new(InterruptProvider {
|
let provider = Arc::new(InterruptProvider {
|
||||||
|
|||||||
@@ -96,10 +96,10 @@ fn response_create_should_default_to_the_websocket_streaming_contract() {
|
|||||||
.expect("decode response.create");
|
.expect("decode response.create");
|
||||||
|
|
||||||
assert!(decoded.metadata().stream());
|
assert!(decoded.metadata().stream());
|
||||||
assert!(!decoded.metadata().store());
|
|
||||||
let Operation::Generate(request) = decoded.operation() else {
|
let Operation::Generate(request) = decoded.operation() else {
|
||||||
panic!("Responses must map to Generate");
|
panic!("Responses must map to Generate");
|
||||||
};
|
};
|
||||||
|
assert_eq!(request.protocol_payload().body()["store"], false);
|
||||||
assert!(request.protocol_payload().body().get("stream").is_none());
|
assert!(request.protocol_payload().body().get("stream").is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -180,6 +180,7 @@ async fn configured_cors_origin_assembles_router_and_answers_preflight() {
|
|||||||
.expect("allow-headers present");
|
.expect("allow-headers present");
|
||||||
assert!(allow_headers.contains("authorization"));
|
assert!(allow_headers.contains("authorization"));
|
||||||
assert!(allow_headers.contains("x-api-key"));
|
assert!(allow_headers.contains("x-api-key"));
|
||||||
|
assert!(allow_headers.contains("x-goog-api-key"));
|
||||||
assert!(allow_headers.contains("anthropic-version"));
|
assert!(allow_headers.contains("anthropic-version"));
|
||||||
assert!(allow_headers.contains("anthropic-beta"));
|
assert!(allow_headers.contains("anthropic-beta"));
|
||||||
assert!(allow_headers.contains("x-request-id"));
|
assert!(allow_headers.contains("x-request-id"));
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ pub(crate) struct Session {
|
|||||||
events: VecDeque<Vec<ProviderEvent>>,
|
events: VecDeque<Vec<ProviderEvent>>,
|
||||||
pub trace: Arc<Trace>,
|
pub trace: Arc<Trace>,
|
||||||
pub finish: Finish,
|
pub finish: Finish,
|
||||||
pub delay: Option<Duration>,
|
pub read_delay: Option<Duration>,
|
||||||
pub fail_commit: bool,
|
pub fail_commit: bool,
|
||||||
pub response_headers: Vec<ProviderResponseHeader>,
|
pub response_headers: Vec<ProviderResponseHeader>,
|
||||||
committed: bool,
|
committed: bool,
|
||||||
@@ -52,7 +52,7 @@ impl Session {
|
|||||||
events: events.into_iter().map(|event| vec![event]).collect(),
|
events: events.into_iter().map(|event| vec![event]).collect(),
|
||||||
trace: Arc::default(),
|
trace: Arc::default(),
|
||||||
finish: Finish::Success,
|
finish: Finish::Success,
|
||||||
delay: None,
|
read_delay: None,
|
||||||
fail_commit: false,
|
fail_commit: false,
|
||||||
response_headers: Vec::new(),
|
response_headers: Vec::new(),
|
||||||
committed: false,
|
committed: false,
|
||||||
@@ -73,7 +73,7 @@ impl ExecutionSession for Session {
|
|||||||
|
|
||||||
fn next_event(&mut self) -> BoxFuture<'_, Result<Option<CoordinatedEvent>, EngineError>> {
|
fn next_event(&mut self) -> BoxFuture<'_, Result<Option<CoordinatedEvent>, EngineError>> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
if let Some(delay) = self.delay.take() {
|
if let Some(delay) = self.read_delay {
|
||||||
tokio::time::sleep(delay).await;
|
tokio::time::sleep(delay).await;
|
||||||
}
|
}
|
||||||
if let Some(event) = self.events.pop_front() {
|
if let Some(event) = self.events.pop_front() {
|
||||||
|
|||||||
@@ -424,12 +424,17 @@ impl FrozenAccountScope {
|
|||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn excluding_account(&self, account: ProviderAccountId) -> Self {
|
pub fn excluding_account(&self, account: ProviderAccountId) -> Self {
|
||||||
let mut restricted = self.clone();
|
let mut restricted = self.clone();
|
||||||
let mut excluded = self.excluded_account_ids.as_ref().clone();
|
restricted.exclude_accounts([account]);
|
||||||
excluded.insert(account);
|
|
||||||
restricted.excluded_account_ids = Arc::new(excluded);
|
|
||||||
restricted
|
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]
|
#[must_use]
|
||||||
pub fn allows(&self, account_id: &ProviderAccountId) -> bool {
|
pub fn allows(&self, account_id: &ProviderAccountId) -> bool {
|
||||||
self.allows_with_policy(account_id, |_| true)
|
self.allows_with_policy(account_id, |_| true)
|
||||||
@@ -480,6 +485,18 @@ impl FrozenAccountScope {
|
|||||||
self.allows_with_policy(account_id, |access| access.allows_optional_model(None))
|
self.allows_with_policy(account_id, |access| access.allows_optional_model(None))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 同一个账号和授权该账号的同一个分组须同时允许请求型号和实际执行型号
|
||||||
|
pub(crate) fn allows_model_pair(
|
||||||
|
&self,
|
||||||
|
account: &ProviderAccountId,
|
||||||
|
requested: &str,
|
||||||
|
actual: &str,
|
||||||
|
) -> bool {
|
||||||
|
self.allows_with_policy(account, |access| {
|
||||||
|
access.allows(requested) && access.allows(actual)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
/// 只报告所有已启用绑定分组均明确拒绝模型的情况,空池沿用原路由错误
|
/// 只报告所有已启用绑定分组均明确拒绝模型的情况,空池沿用原路由错误
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn groups_deny_model(&self, upstream_model: Option<&str>) -> bool {
|
pub fn groups_deny_model(&self, upstream_model: Option<&str>) -> bool {
|
||||||
|
|||||||
@@ -160,6 +160,14 @@ pub trait ProviderAccountStore: Send + Sync {
|
|||||||
.collect())
|
.collect())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 批量返回在各自额度快照之后有成功生成请求完成的账号
|
||||||
|
async fn accounts_used_since_quota(
|
||||||
|
&self,
|
||||||
|
_snapshots: &[QuotaObservationVersion],
|
||||||
|
) -> Result<Vec<ProviderAccountId>, StoreError> {
|
||||||
|
Err(StoreError::new(crate::error::StoreErrorKind::InvalidData))
|
||||||
|
}
|
||||||
|
|
||||||
async fn compare_and_swap_quota(
|
async fn compare_and_swap_quota(
|
||||||
&self,
|
&self,
|
||||||
observation: QuotaObservation,
|
observation: QuotaObservation,
|
||||||
|
|||||||
@@ -380,6 +380,7 @@ where
|
|||||||
client_status_code: None,
|
client_status_code: None,
|
||||||
delivery_pending: false,
|
delivery_pending: false,
|
||||||
upstream_complete: false,
|
upstream_complete: false,
|
||||||
|
local_prewarm: false,
|
||||||
finalization: None,
|
finalization: None,
|
||||||
finalized_at: None,
|
finalized_at: None,
|
||||||
image_generation_requested,
|
image_generation_requested,
|
||||||
@@ -549,6 +550,7 @@ pub struct ResponseExecutionSession<S: ?Sized> {
|
|||||||
client_status_code: Option<u16>,
|
client_status_code: Option<u16>,
|
||||||
delivery_pending: bool,
|
delivery_pending: bool,
|
||||||
upstream_complete: bool,
|
upstream_complete: bool,
|
||||||
|
local_prewarm: bool,
|
||||||
finalization: Option<RequestFinalization>,
|
finalization: Option<RequestFinalization>,
|
||||||
finalized_at: Option<SystemTime>,
|
finalized_at: Option<SystemTime>,
|
||||||
image_generation_requested: bool,
|
image_generation_requested: bool,
|
||||||
@@ -912,6 +914,10 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
async fn pull(&mut self) -> Result<PullOutcome, EngineError> {
|
async fn pull(&mut self) -> Result<PullOutcome, EngineError> {
|
||||||
|
if self.local_prewarm {
|
||||||
|
self.upstream_complete = true;
|
||||||
|
return Ok(PullOutcome::End);
|
||||||
|
}
|
||||||
loop {
|
loop {
|
||||||
if self.pending_stream_failure.is_some() {
|
if self.pending_stream_failure.is_some() {
|
||||||
return self.resume_stream_failure().await;
|
return self.resume_stream_failure().await;
|
||||||
@@ -1076,6 +1082,43 @@ where
|
|||||||
.await?;
|
.await?;
|
||||||
return Err(EngineError::EmptyRoutingPlan);
|
return Err(EngineError::EmptyRoutingPlan);
|
||||||
};
|
};
|
||||||
|
let provider = self
|
||||||
|
.engine
|
||||||
|
.providers()
|
||||||
|
.get(candidate.provider())
|
||||||
|
.cloned()
|
||||||
|
.ok_or_else(|| EngineError::ProviderNotRegistered {
|
||||||
|
provider: candidate.provider().as_str().to_owned(),
|
||||||
|
})?;
|
||||||
|
if self.attempts == 0
|
||||||
|
&& self.client_transport == super::execution::ClientTransport::WebSocket
|
||||||
|
&& self
|
||||||
|
.pending_request
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|request| request.request_kind.as_deref() == Some("prewarm"))
|
||||||
|
&& let Some(prewarm) =
|
||||||
|
provider.local_websocket_prewarm(&self.operation, &self.request_id)
|
||||||
|
{
|
||||||
|
if self.cancellation.is_cancelled() {
|
||||||
|
return Err(EngineError::Cancelled);
|
||||||
|
}
|
||||||
|
if self.deadline.is_elapsed() {
|
||||||
|
return Err(EngineError::Deadline);
|
||||||
|
}
|
||||||
|
self.trace.record(
|
||||||
|
"request.local_prewarm",
|
||||||
|
json!({"provider": candidate.provider().as_str()}),
|
||||||
|
);
|
||||||
|
self.last_observed_provider = Some(candidate.provider().clone());
|
||||||
|
self.observation.client_response_id = Some(prewarm.response_id);
|
||||||
|
self.local_prewarm = true;
|
||||||
|
let mut completed = ProviderEvent::wire(prewarm.completed);
|
||||||
|
completed.request_websocket_reconnect();
|
||||||
|
return Ok(Some(PullOutcome::Events(vec![
|
||||||
|
ProviderEvent::wire(prewarm.created),
|
||||||
|
completed,
|
||||||
|
])));
|
||||||
|
}
|
||||||
let next_attempt = self
|
let next_attempt = self
|
||||||
.attempts
|
.attempts
|
||||||
.checked_add(1)
|
.checked_add(1)
|
||||||
@@ -1120,14 +1163,6 @@ where
|
|||||||
account_context
|
account_context
|
||||||
.excluded_proxy_endpoints
|
.excluded_proxy_endpoints
|
||||||
.clone_from(&self.excluded_proxy_endpoints);
|
.clone_from(&self.excluded_proxy_endpoints);
|
||||||
let provider = self
|
|
||||||
.engine
|
|
||||||
.providers()
|
|
||||||
.get(candidate.provider())
|
|
||||||
.cloned()
|
|
||||||
.ok_or_else(|| EngineError::ProviderNotRegistered {
|
|
||||||
provider: candidate.provider().as_str().to_owned(),
|
|
||||||
})?;
|
|
||||||
if !self.request_profiles.contains_key(candidate.provider()) {
|
if !self.request_profiles.contains_key(candidate.provider()) {
|
||||||
let profile = match self
|
let profile = match self
|
||||||
.plan
|
.plan
|
||||||
@@ -2355,7 +2390,11 @@ where
|
|||||||
self.persist_finalization(ModelRequestFinalization {
|
self.persist_finalization(ModelRequestFinalization {
|
||||||
request_id: self.request_id.clone(),
|
request_id: self.request_id.clone(),
|
||||||
outcome: ExecutionOutcome::Succeeded,
|
outcome: ExecutionOutcome::Succeeded,
|
||||||
send_state: UpstreamSendState::Sent,
|
send_state: if self.local_prewarm {
|
||||||
|
self.current_send_state()
|
||||||
|
} else {
|
||||||
|
UpstreamSendState::Sent
|
||||||
|
},
|
||||||
attempt_count: self.attempts,
|
attempt_count: self.attempts,
|
||||||
downstream_committed_at: self.response_commit.committed_at(),
|
downstream_committed_at: self.response_commit.committed_at(),
|
||||||
client_status_code: self
|
client_status_code: self
|
||||||
|
|||||||
@@ -24,6 +24,14 @@ pub(super) fn authentication_gateway_error(error: ClientAuthenticationError) ->
|
|||||||
|
|
||||||
pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> GatewayError {
|
pub(super) fn map_routing_error(error: crate::validation::RoutingError) -> GatewayError {
|
||||||
match error {
|
match error {
|
||||||
|
crate::validation::RoutingError::WebSearchUnavailable => GatewayError::new(
|
||||||
|
GatewayErrorKind::InvalidRequest,
|
||||||
|
crate::validation::WEB_SEARCH_UNAVAILABLE_MESSAGE,
|
||||||
|
),
|
||||||
|
crate::validation::RoutingError::InvalidReasoningVariant => GatewayError::new(
|
||||||
|
GatewayErrorKind::InvalidRequest,
|
||||||
|
"A supported reasoning effort is required for this model group.",
|
||||||
|
),
|
||||||
crate::validation::RoutingError::GroupModelDenied => GatewayError::new(
|
crate::validation::RoutingError::GroupModelDenied => GatewayError::new(
|
||||||
GatewayErrorKind::PolicyDenied,
|
GatewayErrorKind::PolicyDenied,
|
||||||
crate::validation::GROUP_MODEL_DENIED_MESSAGE,
|
crate::validation::GROUP_MODEL_DENIED_MESSAGE,
|
||||||
|
|||||||
@@ -40,6 +40,13 @@ use crate::upstream::{UpstreamSendState, UpstreamTransport};
|
|||||||
pub type EventStream =
|
pub type EventStream =
|
||||||
Pin<Box<dyn Stream<Item = Result<ProviderEvent, ProviderError>> + Send + 'static>>;
|
Pin<Box<dyn Stream<Item = Result<ProviderEvent, ProviderError>> + Send + 'static>>;
|
||||||
|
|
||||||
|
/// 本地预热的客户端响应,不持有账号、上游响应 ID 或可续接的私有状态
|
||||||
|
pub struct LocalWebSocketPrewarm {
|
||||||
|
pub response_id: String,
|
||||||
|
pub created: ProtocolWireEvent,
|
||||||
|
pub completed: ProtocolWireEvent,
|
||||||
|
}
|
||||||
|
|
||||||
/// Provider 选定单个 credential 后返回的调用事实
|
/// Provider 选定单个 credential 后返回的调用事实
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ProviderCallMetadata {
|
pub struct ProviderCallMetadata {
|
||||||
@@ -245,7 +252,8 @@ pub trait NativeResponseTranslator: Send + 'static {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT: usize = 64;
|
/// 单个原生输入帧允许展开的 wire 事件数
|
||||||
|
pub const MAX_NATIVE_RESPONSE_EVENTS_PER_INPUT: usize = 64;
|
||||||
|
|
||||||
/// Metadata、canonical event stream 与 owned lease 的统一返回值
|
/// Metadata、canonical event stream 与 owned lease 的统一返回值
|
||||||
///
|
///
|
||||||
@@ -1177,6 +1185,15 @@ impl fmt::Debug for ProviderRequest {
|
|||||||
/// 新的 attempt 再次调用
|
/// 新的 attempt 再次调用
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
pub trait Provider: Send + Sync {
|
pub trait Provider: Send + Sync {
|
||||||
|
/// 为没有原生预热能力的上游在本地应答;正常完成后由客户端在新连接上提交完整输入
|
||||||
|
fn local_websocket_prewarm(
|
||||||
|
&self,
|
||||||
|
_operation: &Operation,
|
||||||
|
_request_id: &crate::engine::ModelRequestId,
|
||||||
|
) -> Option<LocalWebSocketPrewarm> {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
/// 声明可用于互联共享的直连认证方式,不执行网络查询
|
/// 声明可用于互联共享的直连认证方式,不执行网络查询
|
||||||
fn is_direct_account(&self, _authentication_kind: &str) -> bool {
|
fn is_direct_account(&self, _authentication_kind: &str) -> bool {
|
||||||
false
|
false
|
||||||
|
|||||||
@@ -183,6 +183,16 @@ pub struct ClientVisibleUpstreamError {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ClientVisibleUpstreamError {
|
impl ClientVisibleUpstreamError {
|
||||||
|
/// Responses 客户端据此重新提交完整输入
|
||||||
|
#[must_use]
|
||||||
|
pub fn previous_response_not_found() -> Self {
|
||||||
|
Self::new(
|
||||||
|
"Previous response was not found. Retrying the full request.",
|
||||||
|
Some("previous_response_not_found".to_owned()),
|
||||||
|
Some("invalid_request_error".to_owned()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/// 原样保存结构化上游 `message`、`code` 和 `type`
|
/// 原样保存结构化上游 `message`、`code` 和 `type`
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn new(
|
pub fn new(
|
||||||
@@ -542,11 +552,20 @@ struct ProviderErrorUpstreamValues {
|
|||||||
|
|
||||||
#[derive(Clone, Default)]
|
#[derive(Clone, Default)]
|
||||||
struct ProviderErrorFailureObservation {
|
struct ProviderErrorFailureObservation {
|
||||||
|
invalid_request_message: Option<&'static str>,
|
||||||
|
invalid_request_details: Option<RequestErrorDetails>,
|
||||||
unreachable_proxy: Option<crate::upstream::ProxyEndpoint>,
|
unreachable_proxy: Option<crate::upstream::ProxyEndpoint>,
|
||||||
continuation_unavailable_reason: Option<&'static str>,
|
continuation_unavailable_reason: Option<&'static str>,
|
||||||
connection: Option<ProviderConnectionObservation>,
|
connection: Option<ProviderConnectionObservation>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 本地校验显式提供的协议字段,不从任意错误来源或请求值反推
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct RequestErrorDetails {
|
||||||
|
code: &'static str,
|
||||||
|
parameter: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
struct AtomicClientEvents(Vec<ProviderEvent>);
|
struct AtomicClientEvents(Vec<ProviderEvent>);
|
||||||
|
|
||||||
@@ -581,6 +600,41 @@ impl ProviderError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 本地请求校验只向客户端返回固定提示,内部原因仍独立保存
|
||||||
|
#[must_use]
|
||||||
|
pub fn invalid_request(message: &'static str) -> Self {
|
||||||
|
let mut error = Self::new(
|
||||||
|
ProviderErrorKind::InvalidRequest,
|
||||||
|
UpstreamSendState::NotSent,
|
||||||
|
);
|
||||||
|
error.failure_observation_mut().invalid_request_message = Some(message);
|
||||||
|
error
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 附加本地请求校验的安全机器码与协议字段路径,禁止传入字段值
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_request_details(mut self, code: &'static str, parameter: Option<&str>) -> Self {
|
||||||
|
self.failure_observation_mut().invalid_request_details = Some(RequestErrorDetails {
|
||||||
|
code,
|
||||||
|
parameter: parameter.map(str::to_owned),
|
||||||
|
});
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 当前上游无法解析 Responses 历史,仅客户端持有完整输入可重放
|
||||||
|
#[must_use]
|
||||||
|
pub fn responses_replay_required(reason: &'static str, send_state: UpstreamSendState) -> Self {
|
||||||
|
Self::new(ProviderErrorKind::ContinuationRecoveryRequired, send_state)
|
||||||
|
.with_continuation_failure(ContinuationFailure::HistoryUnavailable)
|
||||||
|
.with_continuation_recovery_disposition(
|
||||||
|
ContinuationRecoveryDisposition::ClientReplayRequired,
|
||||||
|
)
|
||||||
|
.with_continuation_unavailable_reason(reason)
|
||||||
|
.with_client_visible_upstream_error(
|
||||||
|
ClientVisibleUpstreamError::previous_response_not_found(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn group_feature_denied(feature: DeniedGroupFeature) -> Self {
|
pub(crate) fn group_feature_denied(feature: DeniedGroupFeature) -> Self {
|
||||||
let mut error = Self::new(
|
let mut error = Self::new(
|
||||||
ProviderErrorKind::RequestPolicyDenied,
|
ProviderErrorKind::RequestPolicyDenied,
|
||||||
@@ -1294,6 +1348,7 @@ pub struct GatewayError {
|
|||||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
struct GatewayClientErrorDetails {
|
struct GatewayClientErrorDetails {
|
||||||
code: Option<&'static str>,
|
code: Option<&'static str>,
|
||||||
|
parameter: Option<String>,
|
||||||
retry_after: Option<Duration>,
|
retry_after: Option<Duration>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1362,7 +1417,11 @@ impl GatewayError {
|
|||||||
}
|
}
|
||||||
ProviderErrorKind::InvalidRequest => Self::new(
|
ProviderErrorKind::InvalidRequest => Self::new(
|
||||||
GatewayErrorKind::InvalidRequest,
|
GatewayErrorKind::InvalidRequest,
|
||||||
"Invalid upstream request.",
|
error
|
||||||
|
.failure_observation
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|details| details.invalid_request_message)
|
||||||
|
.unwrap_or("Invalid upstream request."),
|
||||||
),
|
),
|
||||||
ProviderErrorKind::SessionPolicyRestricted => Self::new(
|
ProviderErrorKind::SessionPolicyRestricted => Self::new(
|
||||||
GatewayErrorKind::InvalidRequest,
|
GatewayErrorKind::InvalidRequest,
|
||||||
@@ -1427,6 +1486,17 @@ impl GatewayError {
|
|||||||
"Upstream service is unavailable.",
|
"Upstream service is unavailable.",
|
||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
let mut gateway = gateway;
|
||||||
|
if gateway.kind() == GatewayErrorKind::InvalidRequest
|
||||||
|
&& let Some(details) = error
|
||||||
|
.failure_observation
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|observation| observation.invalid_request_details.as_ref())
|
||||||
|
{
|
||||||
|
let client = gateway.client_details.get_or_insert_with(Default::default);
|
||||||
|
client.code = Some(details.code);
|
||||||
|
client.parameter.clone_from(&details.parameter);
|
||||||
|
}
|
||||||
let gateway = match error.diagnostic() {
|
let gateway = match error.diagnostic() {
|
||||||
Some(diagnostic) => gateway.with_diagnostic(diagnostic.clone()),
|
Some(diagnostic) => gateway.with_diagnostic(diagnostic.clone()),
|
||||||
None => gateway,
|
None => gateway,
|
||||||
@@ -1498,6 +1568,14 @@ impl GatewayError {
|
|||||||
.and_then(|details| details.code)
|
.and_then(|details| details.code)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 返回本地校验明确标注的协议字段路径,不包含请求值
|
||||||
|
#[must_use]
|
||||||
|
pub fn client_error_parameter(&self) -> Option<&str> {
|
||||||
|
self.client_details
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|details| details.parameter.as_deref())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl fmt::Debug for GatewayError {
|
impl fmt::Debug for GatewayError {
|
||||||
|
|||||||
@@ -813,6 +813,7 @@ pub struct ProviderEvent {
|
|||||||
wire: Option<Box<ProtocolWireEvent>>,
|
wire: Option<Box<ProtocolWireEvent>>,
|
||||||
observation: Option<Box<ProviderResponseObservation>>,
|
observation: Option<Box<ProviderResponseObservation>>,
|
||||||
session_update: Option<Box<ProviderSessionState>>,
|
session_update: Option<Box<ProviderSessionState>>,
|
||||||
|
reconnect_websocket: bool,
|
||||||
middleware_transformed: bool,
|
middleware_transformed: bool,
|
||||||
replayable_prelude: bool,
|
replayable_prelude: bool,
|
||||||
middleware_origin_wire: Option<Arc<ProtocolWireEvent>>,
|
middleware_origin_wire: Option<Arc<ProtocolWireEvent>>,
|
||||||
@@ -827,6 +828,7 @@ impl ProviderEvent {
|
|||||||
wire: None,
|
wire: None,
|
||||||
observation: None,
|
observation: None,
|
||||||
session_update: None,
|
session_update: None,
|
||||||
|
reconnect_websocket: false,
|
||||||
middleware_transformed: false,
|
middleware_transformed: false,
|
||||||
replayable_prelude: false,
|
replayable_prelude: false,
|
||||||
middleware_origin_wire: None,
|
middleware_origin_wire: None,
|
||||||
@@ -848,6 +850,7 @@ impl ProviderEvent {
|
|||||||
wire: Some(Box::new(wire)),
|
wire: Some(Box::new(wire)),
|
||||||
observation: None,
|
observation: None,
|
||||||
session_update: None,
|
session_update: None,
|
||||||
|
reconnect_websocket: false,
|
||||||
middleware_transformed: false,
|
middleware_transformed: false,
|
||||||
replayable_prelude: false,
|
replayable_prelude: false,
|
||||||
middleware_origin_wire: None,
|
middleware_origin_wire: None,
|
||||||
@@ -862,6 +865,7 @@ impl ProviderEvent {
|
|||||||
wire: Some(Box::new(wire)),
|
wire: Some(Box::new(wire)),
|
||||||
observation: None,
|
observation: None,
|
||||||
session_update: None,
|
session_update: None,
|
||||||
|
reconnect_websocket: false,
|
||||||
middleware_transformed: false,
|
middleware_transformed: false,
|
||||||
replayable_prelude: false,
|
replayable_prelude: false,
|
||||||
middleware_origin_wire: None,
|
middleware_origin_wire: None,
|
||||||
@@ -876,12 +880,23 @@ impl ProviderEvent {
|
|||||||
wire: None,
|
wire: None,
|
||||||
observation: Some(Box::new(observation)),
|
observation: Some(Box::new(observation)),
|
||||||
session_update: None,
|
session_update: None,
|
||||||
|
reconnect_websocket: false,
|
||||||
middleware_transformed: false,
|
middleware_transformed: false,
|
||||||
replayable_prelude: false,
|
replayable_prelude: false,
|
||||||
middleware_origin_wire: None,
|
middleware_origin_wire: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 提示下游在本次成功终态交付后重连,不创建下一轮的 Provider 会话状态
|
||||||
|
pub fn request_websocket_reconnect(&mut self) {
|
||||||
|
self.reconnect_websocket = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub const fn prefers_websocket_reconnect(&self) -> bool {
|
||||||
|
self.reconnect_websocket
|
||||||
|
}
|
||||||
|
|
||||||
/// Provider 确认该事件仅为可替换的前导信息,客户端支持后续 attempt 的新前导事件
|
/// Provider 确认该事件仅为可替换的前导信息,客户端支持后续 attempt 的新前导事件
|
||||||
/// 此证明不代替错误分类、发送状态、预算或续接恢复检查
|
/// 此证明不代替错误分类、发送状态、预算或续接恢复检查
|
||||||
#[must_use]
|
#[must_use]
|
||||||
|
|||||||
@@ -124,9 +124,6 @@ pub struct ProviderSessionState {
|
|||||||
payload: Map<String, Value>,
|
payload: Map<String, Value>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
extension_owner: Option<Box<ExtensionSessionOwner>>,
|
extension_owner: Option<Box<ExtensionSessionOwner>>,
|
||||||
// 仅供本次终态交付后处置客户端连接,不持久化或传给外部适配器
|
|
||||||
#[serde(skip)]
|
|
||||||
reconnect_websocket: bool,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 受管扩展会话的宿主归属,不能把插件私有状态交给原生 Provider 解码
|
/// 受管扩展会话的宿主归属,不能把插件私有状态交给原生 Provider 解码
|
||||||
@@ -159,7 +156,6 @@ impl ProviderSessionState {
|
|||||||
provider,
|
provider,
|
||||||
payload,
|
payload,
|
||||||
extension_owner: None,
|
extension_owner: None,
|
||||||
reconnect_websocket: false,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,18 +169,6 @@ impl ProviderSessionState {
|
|||||||
&self.payload
|
&self.payload
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 提示能重连重放的客户端在本次成功交付后重建连接
|
|
||||||
#[must_use]
|
|
||||||
pub const fn with_websocket_reconnect(mut self) -> Self {
|
|
||||||
self.reconnect_websocket = true;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
|
||||||
pub const fn prefers_websocket_reconnect(&self) -> bool {
|
|
||||||
self.reconnect_websocket
|
|
||||||
}
|
|
||||||
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn with_extension_owner(mut self, owner: ExtensionSessionOwner) -> Self {
|
pub fn with_extension_owner(mut self, owner: ExtensionSessionOwner) -> Self {
|
||||||
self.extension_owner = Some(Box::new(owner));
|
self.extension_owner = Some(Box::new(owner));
|
||||||
@@ -440,6 +424,7 @@ pub struct GenerateRequest {
|
|||||||
|
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone, PartialEq)]
|
||||||
struct GeneratePayload {
|
struct GeneratePayload {
|
||||||
|
source_protocol: Option<String>,
|
||||||
requires_native_protocol: bool,
|
requires_native_protocol: bool,
|
||||||
source_image_generation: bool,
|
source_image_generation: bool,
|
||||||
wire_facts: RequestFacts,
|
wire_facts: RequestFacts,
|
||||||
@@ -477,6 +462,15 @@ impl ClientTurn {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl GenerateRequest {
|
impl GenerateRequest {
|
||||||
|
/// 返回可信入口协议,直接转换只能更新当前 wire,不能改写请求来源
|
||||||
|
#[must_use]
|
||||||
|
pub fn source_protocol(&self) -> &str {
|
||||||
|
self.payload
|
||||||
|
.source_protocol
|
||||||
|
.as_deref()
|
||||||
|
.unwrap_or_else(|| self.payload.protocol_payload.protocol())
|
||||||
|
}
|
||||||
|
|
||||||
/// 创建携带协议不透明正文的生成请求
|
/// 创建携带协议不透明正文的生成请求
|
||||||
///
|
///
|
||||||
/// 完整请求以原始 wire object 保存,协议层提取路由与权限所需的纯事实
|
/// 完整请求以原始 wire object 保存,协议层提取路由与权限所需的纯事实
|
||||||
@@ -485,6 +479,7 @@ impl GenerateRequest {
|
|||||||
pub fn from_protocol_payload(protocol_payload: ProtocolPayload) -> Self {
|
pub fn from_protocol_payload(protocol_payload: ProtocolPayload) -> Self {
|
||||||
Self {
|
Self {
|
||||||
payload: Arc::new(GeneratePayload {
|
payload: Arc::new(GeneratePayload {
|
||||||
|
source_protocol: None,
|
||||||
requires_native_protocol: false,
|
requires_native_protocol: false,
|
||||||
source_image_generation: false,
|
source_image_generation: false,
|
||||||
wire_facts: request_facts(protocol_payload.protocol(), protocol_payload.body()),
|
wire_facts: request_facts(protocol_payload.protocol(), protocol_payload.body()),
|
||||||
@@ -920,6 +915,53 @@ pub enum Operation {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl 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,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Responses 要求本轮执行托管搜索时,按账号快照选择搜索目标
|
||||||
|
#[must_use]
|
||||||
|
pub fn requires_web_search(&self) -> bool {
|
||||||
|
matches!(self, Self::Generate(request) if {
|
||||||
|
let payload = request.protocol_payload();
|
||||||
|
match payload.protocol() {
|
||||||
|
gateway_protocol::openai::OPENAI_PROTOCOL => gateway_protocol::openai::web_search::is_required(payload.body()),
|
||||||
|
gateway_protocol::chat_completions::CHAT_PROTOCOL => payload.body().get("web_search_options").is_some_and(serde_json::Value::is_object),
|
||||||
|
_ => 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(
|
pub(crate) fn with_inherited_capability_requirements(
|
||||||
self,
|
self,
|
||||||
inherited: CapabilityRequirements,
|
inherited: CapabilityRequirements,
|
||||||
@@ -1063,6 +1105,7 @@ impl Operation {
|
|||||||
}
|
}
|
||||||
})?;
|
})?;
|
||||||
if let Some(protocol) = target_protocol {
|
if let Some(protocol) = target_protocol {
|
||||||
|
payload.source_protocol = Some(payload.protocol_payload.protocol.clone());
|
||||||
payload.protocol_payload.protocol = protocol;
|
payload.protocol_payload.protocol = protocol;
|
||||||
}
|
}
|
||||||
payload.wire_facts =
|
payload.wire_facts =
|
||||||
|
|||||||
@@ -12,6 +12,55 @@ use super::{
|
|||||||
ModelCapabilities, ModelPresentation, PublicModelId, PublicModelProfile, UpstreamModelId,
|
ModelCapabilities, ModelPresentation, PublicModelId, PublicModelProfile, UpstreamModelId,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Provider 声明的推理档位目标及确认该分组成员关系的账号
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct ReasoningModelVariant {
|
||||||
|
pub model: UpstreamModelId,
|
||||||
|
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
|
/// 扩展集合持有的直接模型别名;执行与元数据仍归属内置 Provider
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct ContributedModelAlias {
|
pub struct ContributedModelAlias {
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ pub use crate::account::scope::{
|
|||||||
};
|
};
|
||||||
pub use crate::identity::ProviderKind;
|
pub use crate::identity::ProviderKind;
|
||||||
pub use catalog::{
|
pub use catalog::{
|
||||||
ContributedModel, ContributedModelAlias, ProviderCatalogGeneration, ProviderCatalogPort,
|
AccountModelMetadata, ContributedModel, ContributedModelAlias, ProviderCatalogGeneration,
|
||||||
ProviderCatalogUnavailable, ProviderModelCapabilities, ProviderModelContent,
|
ProviderCatalogPort, ProviderCatalogUnavailable, ProviderModelCapabilities,
|
||||||
ProviderModelDescriptor, PublicModelDescriptor,
|
ProviderModelContent, ProviderModelDescriptor, PublicModelDescriptor, ReasoningModelVariant,
|
||||||
};
|
};
|
||||||
pub use snapshot::RuntimeSnapshot;
|
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`
|
/// `runtime_settings.config_revision`
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
pub struct ConfigRevision(NonZeroU64);
|
pub struct ConfigRevision(NonZeroU64);
|
||||||
@@ -151,8 +157,11 @@ pub struct ModelCapabilities {
|
|||||||
features: BTreeMap<Feature, SupportLevel>,
|
features: BTreeMap<Feature, SupportLevel>,
|
||||||
max_output_tokens: Option<u64>,
|
max_output_tokens: Option<u64>,
|
||||||
upstream_validates_features: bool,
|
upstream_validates_features: bool,
|
||||||
generation_protocol: Option<&'static str>,
|
native_generation_protocols: BTreeSet<&'static str>,
|
||||||
translated_generation_protocols: BTreeSet<&'static str>,
|
translated_generation_protocols: BTreeSet<&'static str>,
|
||||||
|
reasoning_variants: BTreeMap<String, ReasoningModelVariant>,
|
||||||
|
account_metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||||
|
dedicated_web_search: Option<Arc<BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Provider 为客户端模型目录提供的展示与交互能力
|
/// Provider 为客户端模型目录提供的展示与交互能力
|
||||||
@@ -425,8 +434,11 @@ impl ModelCapabilities {
|
|||||||
features: BTreeMap::new(),
|
features: BTreeMap::new(),
|
||||||
max_output_tokens,
|
max_output_tokens,
|
||||||
upstream_validates_features: false,
|
upstream_validates_features: false,
|
||||||
generation_protocol: None,
|
native_generation_protocols: BTreeSet::new(),
|
||||||
translated_generation_protocols: BTreeSet::new(),
|
translated_generation_protocols: BTreeSet::new(),
|
||||||
|
reasoning_variants: BTreeMap::new(),
|
||||||
|
account_metadata: BTreeMap::new(),
|
||||||
|
dedicated_web_search: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -436,6 +448,40 @@ impl ModelCapabilities {
|
|||||||
self
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_account_metadata(
|
||||||
|
mut self,
|
||||||
|
metadata: BTreeMap<crate::account::ProviderAccountId, AccountModelMetadata>,
|
||||||
|
) -> Self {
|
||||||
|
self.account_metadata = metadata;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 声明托管搜索必须独立选型,空目录表示目前没有搜索目标
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_dedicated_web_search(
|
||||||
|
mut self,
|
||||||
|
targets: BTreeMap<crate::account::ProviderAccountId, UpstreamModelId>,
|
||||||
|
) -> Self {
|
||||||
|
self.dedicated_web_search = Some(Arc::new(targets));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// 将请求形态 feature 的最终合法性判断交给上游 wire API
|
/// 将请求形态 feature 的最终合法性判断交给上游 wire API
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn with_upstream_feature_validation(mut self) -> Self {
|
pub const fn with_upstream_feature_validation(mut self) -> Self {
|
||||||
@@ -445,8 +491,18 @@ impl ModelCapabilities {
|
|||||||
|
|
||||||
/// 声明原生生成协议;额外转换入口须显式登记,其他操作沿用各自的能力约束
|
/// 声明原生生成协议;额外转换入口须显式登记,其他操作沿用各自的能力约束
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn with_generation_protocol(mut self, protocol: &'static str) -> Self {
|
pub fn with_generation_protocol(mut self, protocol: &'static str) -> Self {
|
||||||
self.generation_protocol = Some(protocol);
|
self.native_generation_protocols = BTreeSet::from([protocol]);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 同一 Provider 可包含不同协议的账号,最终资格仍由账号选择器核对
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_native_generation_protocols(
|
||||||
|
mut self,
|
||||||
|
protocols: impl IntoIterator<Item = &'static str>,
|
||||||
|
) -> Self {
|
||||||
|
self.native_generation_protocols = protocols.into_iter().collect();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -465,13 +521,30 @@ impl ModelCapabilities {
|
|||||||
operation: &crate::operation::Operation,
|
operation: &crate::operation::Operation,
|
||||||
requirements: &CapabilityRequirements,
|
requirements: &CapabilityRequirements,
|
||||||
) -> Option<BTreeSet<Feature>> {
|
) -> Option<BTreeSet<Feature>> {
|
||||||
|
if operation.requires_native_protocol()
|
||||||
|
&& !self
|
||||||
|
.native_generation_protocols
|
||||||
|
.contains(operation.protocol())
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
if matches!(operation, crate::operation::Operation::Generate(_))
|
if matches!(operation, crate::operation::Operation::Generate(_))
|
||||||
&& self.generation_protocol.is_some_and(|protocol| {
|
&& !self.native_generation_protocols.is_empty()
|
||||||
protocol != operation.protocol()
|
&& !self
|
||||||
&& !self
|
.native_generation_protocols
|
||||||
.translated_generation_protocols
|
.contains(operation.protocol())
|
||||||
.contains(operation.protocol())
|
&& !self
|
||||||
})
|
.translated_generation_protocols
|
||||||
|
.contains(operation.protocol())
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if matches!(operation, crate::operation::Operation::CountTokens(_))
|
||||||
|
&& operation.protocol() != "token-count"
|
||||||
|
&& !self.native_generation_protocols.is_empty()
|
||||||
|
&& !self
|
||||||
|
.native_generation_protocols
|
||||||
|
.contains(operation.protocol())
|
||||||
{
|
{
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -958,32 +958,35 @@ impl RuntimeSnapshot {
|
|||||||
let mut profiles = BTreeMap::new();
|
let mut profiles = BTreeMap::new();
|
||||||
for (model, presentation) in presentations {
|
for (model, presentation) in presentations {
|
||||||
if let Ok(public_model) = PublicModelId::new(model.as_str().to_owned()) {
|
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() {
|
for alias in self.settings.values.model_mappings.keys() {
|
||||||
let target = self.mapped_model(alias);
|
let Ok(public_model) = PublicModelId::new(alias.clone()) else {
|
||||||
let Some(presentation) = presentations.iter().find_map(|(model, presentation)| {
|
|
||||||
(model.as_str() == target).then_some(presentation)
|
|
||||||
}) else {
|
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if let Ok(public_model) = PublicModelId::new(alias.clone()) {
|
let target = self.mapped_model(alias);
|
||||||
profiles.insert(public_model, presentation.clone());
|
if let Some(presentation) = presentations.get(target.as_str()) {
|
||||||
|
profiles.insert(public_model, presentation);
|
||||||
|
} else {
|
||||||
|
profiles.remove(&public_model);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for alias in self
|
for alias in self.model_aliases() {
|
||||||
.model_aliases()
|
if &alias.provider == provider
|
||||||
.iter()
|
&& let Some(presentation) = presentations.get(&alias.target)
|
||||||
.filter(|alias| &alias.provider == provider)
|
{
|
||||||
{
|
profiles.insert(alias.id.clone(), presentation);
|
||||||
if let Some(presentation) = presentations.get(&alias.target) {
|
} else {
|
||||||
profiles.insert(alias.id.clone(), presentation.clone());
|
profiles.remove(&alias.id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
profiles
|
profiles
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(model, presentation)| super::PublicModelProfile::new(model, presentation))
|
.map(|(model, presentation)| {
|
||||||
|
super::PublicModelProfile::new(model, presentation.clone())
|
||||||
|
})
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1078,6 +1081,35 @@ impl RuntimeSnapshot {
|
|||||||
&RoutingContext::default(),
|
&RoutingContext::default(),
|
||||||
)
|
)
|
||||||
.is_ok()
|
.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()
|
.collect()
|
||||||
}
|
}
|
||||||
@@ -1108,8 +1140,30 @@ impl RuntimeSnapshot {
|
|||||||
scope: &FrozenAccountScope,
|
scope: &FrozenAccountScope,
|
||||||
) -> Vec<super::PublicModelProfile> {
|
) -> Vec<super::PublicModelProfile> {
|
||||||
let mut profiles = self.public_model_profiles_for_provider(provider);
|
let mut profiles = self.public_model_profiles_for_provider(provider);
|
||||||
profiles.retain(|profile| {
|
profiles.retain_mut(|profile| {
|
||||||
self.native_catalog_model_allowed_for_scope(provider, profile.model(), scope)
|
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 排序,追加的插件画像保留注册顺序,不参与二分查找
|
// Provider 画像按公开 ID 排序,追加的插件画像保留注册顺序,不参与二分查找
|
||||||
let provider_count = profiles.len();
|
let provider_count = profiles.len();
|
||||||
@@ -1121,6 +1175,30 @@ impl RuntimeSnapshot {
|
|||||||
Err(_) => profiles.push(model.public_profile()),
|
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
|
profiles
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1172,6 +1250,13 @@ impl RuntimeSnapshot {
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
let upstream = self.mapped_model(public_model.as_str());
|
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)
|
if !scope.allows_model(account, &upstream)
|
||||||
|| !self.contains_public_model_for_provider(public_model, provider)
|
|| !self.contains_public_model_for_provider(public_model, provider)
|
||||||
{
|
{
|
||||||
@@ -1237,6 +1322,35 @@ 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 {
|
||||||
|
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())
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn native_catalog_model_allowed_for_scope(
|
fn native_catalog_model_allowed_for_scope(
|
||||||
&self,
|
&self,
|
||||||
provider: &ProviderKind,
|
provider: &ProviderKind,
|
||||||
@@ -1244,6 +1358,12 @@ impl RuntimeSnapshot {
|
|||||||
scope: &FrozenAccountScope,
|
scope: &FrozenAccountScope,
|
||||||
) -> bool {
|
) -> bool {
|
||||||
let upstream_model = self.mapped_model(public_model.as_str());
|
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
|
match self
|
||||||
.model_catalog_accounts
|
.model_catalog_accounts
|
||||||
.get(provider)
|
.get(provider)
|
||||||
@@ -1461,7 +1581,13 @@ impl RuntimeSnapshot {
|
|||||||
}
|
}
|
||||||
.map_err(|_| RoutingError::InvalidIdentifier)?
|
.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);
|
return Err(RoutingError::GroupModelDenied);
|
||||||
}
|
}
|
||||||
@@ -1476,6 +1602,9 @@ impl RuntimeSnapshot {
|
|||||||
|| account_scope.provider_kinds().clone(),
|
|| account_scope.provider_kinds().clone(),
|
||||||
|provider| BTreeSet::from([provider.clone()]),
|
|provider| BTreeSet::from([provider.clone()]),
|
||||||
);
|
);
|
||||||
|
let mut invalid_variant = false;
|
||||||
|
let mut group_model_denied = false;
|
||||||
|
let mut search_unavailable = false;
|
||||||
for provider in &providers {
|
for provider in &providers {
|
||||||
if !self.providers.contains(provider) {
|
if !self.providers.contains(provider) {
|
||||||
continue;
|
continue;
|
||||||
@@ -1495,25 +1624,55 @@ impl RuntimeSnapshot {
|
|||||||
{
|
{
|
||||||
continue;
|
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 授权;管理诊断的目标账号由探测入口固定
|
// 强制 Provider 路由也不能扩大 Key 授权;管理诊断的目标账号由探测入口固定
|
||||||
if enforce_routing_policy
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
let capabilities = self
|
let capabilities = self
|
||||||
.provider_models
|
.provider_models
|
||||||
.get(provider)
|
.get(provider)
|
||||||
.and_then(|models| models.get(&upstream_model));
|
.and_then(|models| models.get(upstream_model));
|
||||||
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
// 原生入口不能借同名模型、发现型目录的匿名透传或插件声明跨协议分派
|
||||||
let native_protocol = match operation {
|
if operation.requires_native_protocol()
|
||||||
Operation::Generate(request) => request.requires_native_protocol(),
|
&& !capabilities.is_some_and(|model| {
|
||||||
Operation::CountTokens(request) => request.requires_native_protocol(),
|
model
|
||||||
_ => false,
|
.native_generation_protocols
|
||||||
};
|
.contains(operation.protocol())
|
||||||
if native_protocol
|
})
|
||||||
&& capabilities.and_then(|model| model.generation_protocol)
|
|
||||||
!= Some(operation.protocol())
|
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -1530,7 +1689,6 @@ impl RuntimeSnapshot {
|
|||||||
&& &model.id == public_model
|
&& &model.id == public_model
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
let mut candidate_scope = Arc::clone(&account_scope);
|
|
||||||
let emulated_features = if contributions.is_empty() {
|
let emulated_features = if contributions.is_empty() {
|
||||||
match capabilities {
|
match capabilities {
|
||||||
Some(capabilities) => {
|
Some(capabilities) => {
|
||||||
@@ -1562,14 +1720,14 @@ impl RuntimeSnapshot {
|
|||||||
})
|
})
|
||||||
.flat_map(|model| model.accounts.iter())
|
.flat_map(|model| model.accounts.iter())
|
||||||
.filter(|account| {
|
.filter(|account| {
|
||||||
account_scope.account_provider(account) == Some(provider)
|
candidate_scope.account_provider(account) == Some(provider)
|
||||||
&& account_scope.allows_model(account, upstream_model.as_str())
|
&& candidate_scope.allows_model(account, upstream_model.as_str())
|
||||||
})
|
})
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect();
|
.collect();
|
||||||
if native.is_some() {
|
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) {
|
for account in contributions.iter().flat_map(|model| &model.accounts) {
|
||||||
if !capable_accounts.contains(account) {
|
if !capable_accounts.contains(account) {
|
||||||
restricted = restricted.excluding_account(account.clone());
|
restricted = restricted.excluding_account(account.clone());
|
||||||
@@ -1582,7 +1740,7 @@ impl RuntimeSnapshot {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
candidate_scope = Arc::new(
|
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()) {
|
if !candidate_scope.allows_provider_model(provider, upstream_model.as_str()) {
|
||||||
@@ -1590,6 +1748,84 @@ impl RuntimeSnapshot {
|
|||||||
}
|
}
|
||||||
native.unwrap_or_default()
|
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 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;
|
||||||
|
}
|
||||||
candidates.push(ProviderCandidate {
|
candidates.push(ProviderCandidate {
|
||||||
requires_direct_authentication: direct_model.is_some(),
|
requires_direct_authentication: direct_model.is_some(),
|
||||||
provider: provider.clone(),
|
provider: provider.clone(),
|
||||||
@@ -1607,6 +1843,15 @@ impl RuntimeSnapshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if candidates.is_empty() {
|
if candidates.is_empty() {
|
||||||
|
if group_model_denied {
|
||||||
|
return Err(RoutingError::GroupModelDenied);
|
||||||
|
}
|
||||||
|
if search_unavailable {
|
||||||
|
return Err(RoutingError::WebSearchUnavailable);
|
||||||
|
}
|
||||||
|
if invalid_variant {
|
||||||
|
return Err(RoutingError::InvalidReasoningVariant);
|
||||||
|
}
|
||||||
// 模型存在性必须包含被请求路由限制排除的 Provider;目录未知时不能断言模型不存在
|
// 模型存在性必须包含被请求路由限制排除的 Provider;目录未知时不能断言模型不存在
|
||||||
let mut scoped_providers = providers.intersection(&self.providers).peekable();
|
let mut scoped_providers = providers.intersection(&self.providers).peekable();
|
||||||
if scoped_providers.peek().is_some()
|
if scoped_providers.peek().is_some()
|
||||||
|
|||||||
@@ -49,8 +49,6 @@ pub enum PrivacyAction {
|
|||||||
RenameKey,
|
RenameKey,
|
||||||
RemoveField,
|
RemoveField,
|
||||||
AnonymizeProject,
|
AnonymizeProject,
|
||||||
/// 已保存的组合动作继续执行,编辑器将其展开为独立步骤
|
|
||||||
AnonymizeWorkspace,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
|||||||
@@ -60,6 +60,10 @@ pub const GROUP_MODEL_DENIED_CODE: &str = "group_model_denied";
|
|||||||
pub const GROUP_MODEL_DENIED_MESSAGE: &str =
|
pub const GROUP_MODEL_DENIED_MESSAGE: &str =
|
||||||
"Model is not allowed by the API key's account groups.";
|
"Model is not allowed by the API key's account groups.";
|
||||||
|
|
||||||
|
/// 搜索请求在当前授权范围没有对应的账号目录目标
|
||||||
|
pub const WEB_SEARCH_UNAVAILABLE_MESSAGE: &str =
|
||||||
|
"No authorized web search model is available for this account scope.";
|
||||||
|
|
||||||
/// 路由快照或 Route Plan 不满足不变量
|
/// 路由快照或 Route Plan 不满足不变量
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||||
pub enum RoutingError {
|
pub enum RoutingError {
|
||||||
@@ -81,6 +85,12 @@ pub enum RoutingError {
|
|||||||
/// 已启用的绑定分组均明确禁止请求模型
|
/// 已启用的绑定分组均明确禁止请求模型
|
||||||
#[error("{GROUP_MODEL_DENIED_MESSAGE}")]
|
#[error("{GROUP_MODEL_DENIED_MESSAGE}")]
|
||||||
GroupModelDenied,
|
GroupModelDenied,
|
||||||
|
/// 已知模型分组没有与本次请求匹配的推理档位
|
||||||
|
#[error("model group requires a supported reasoning effort")]
|
||||||
|
InvalidReasoningVariant,
|
||||||
|
/// 当前授权账号的目录没有专用搜索型号
|
||||||
|
#[error("{WEB_SEARCH_UNAVAILABLE_MESSAGE}")]
|
||||||
|
WebSearchUnavailable,
|
||||||
/// 快照中存在重复实体
|
/// 快照中存在重复实体
|
||||||
#[error("duplicate {entity} `{id}`")]
|
#[error("duplicate {entity} `{id}`")]
|
||||||
DuplicateEntity {
|
DuplicateEntity {
|
||||||
|
|||||||
@@ -198,15 +198,8 @@ fn gateway_error_should_keep_client_visible_upstream_fields_out_of_safe_diagnost
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn continuation_recovery_should_keep_its_internal_classification_and_client_contract() {
|
fn continuation_recovery_should_keep_its_internal_classification_and_client_contract() {
|
||||||
let error = ProviderError::new(
|
let error =
|
||||||
ProviderErrorKind::ContinuationRecoveryRequired,
|
ProviderError::responses_replay_required("scope_unavailable", UpstreamSendState::NotSent);
|
||||||
UpstreamSendState::NotSent,
|
|
||||||
)
|
|
||||||
.with_client_visible_upstream_error(ClientVisibleUpstreamError::new(
|
|
||||||
"Previous response was not found. Retrying the full request.",
|
|
||||||
Some("previous_response_not_found".to_owned()),
|
|
||||||
Some("invalid_request_error".to_owned()),
|
|
||||||
));
|
|
||||||
let gateway = GatewayError::from_provider(&error);
|
let gateway = GatewayError::from_provider(&error);
|
||||||
|
|
||||||
assert_eq!(error.kind().as_str(), "continuation_recovery_required");
|
assert_eq!(error.kind().as_str(), "continuation_recovery_required");
|
||||||
|
|||||||
@@ -399,3 +399,41 @@ fn image_request_should_preserve_generation_and_edit_payloads_opaque() {
|
|||||||
);
|
);
|
||||||
assert!(!format!("{edit:?}").contains("data:image/png"));
|
assert!(!format!("{edit:?}").contains("data:image/png"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chat_source_survives_the_one_authorized_wire_translation() {
|
||||||
|
let original = serde_json::json!({"model":"shared", "messages":[{"role":"user","content":"hello"}], "max_completion_tokens":1024});
|
||||||
|
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||||
|
ProtocolPayload::json_object(
|
||||||
|
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||||
|
original.as_object().unwrap().clone(),
|
||||||
|
)
|
||||||
|
.unwrap(),
|
||||||
|
));
|
||||||
|
let requirements = operation.capability_requirements();
|
||||||
|
let translated = operation.translate_protocol_wire("anthropic", Bytes::from_static(br#"{"model":"shared","messages":[{"role":"user","content":"hello"}],"max_tokens":1024}"#)).unwrap();
|
||||||
|
let Operation::Generate(generate) = &translated else {
|
||||||
|
unreachable!()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
generate.source_protocol(),
|
||||||
|
gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||||
|
);
|
||||||
|
assert_eq!(generate.protocol_payload().protocol(), "anthropic");
|
||||||
|
assert_eq!(translated.capability_requirements(), requirements);
|
||||||
|
let replaced = translated
|
||||||
|
.replace_protocol_wire(None, serde_json::Map::new())
|
||||||
|
.unwrap();
|
||||||
|
let Operation::Generate(generate) = &replaced else {
|
||||||
|
unreachable!()
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
generate.source_protocol(),
|
||||||
|
gateway_protocol::chat_completions::CHAT_PROTOCOL
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
replaced
|
||||||
|
.translate_protocol_wire("genai", Bytes::from_static(b"{}"))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -1039,3 +1039,57 @@ fn native_count_catalog_and_execution_do_not_fall_back_to_another_protocol() {
|
|||||||
.is_empty()
|
.is_empty()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn same_model_native_protocols_do_not_borrow_chat_conversion_capabilities() {
|
||||||
|
let native = capabilities()
|
||||||
|
.with_native_generation_protocols(["openai", "anthropic"])
|
||||||
|
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL]);
|
||||||
|
let genai = capabilities()
|
||||||
|
.with_generation_protocol("genai")
|
||||||
|
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL]);
|
||||||
|
let snapshot = RuntimeSnapshot::new(
|
||||||
|
ConfigRevision::new(1).unwrap(),
|
||||||
|
settings(),
|
||||||
|
vec![
|
||||||
|
ProviderKind::new("openai").unwrap(),
|
||||||
|
ProviderKind::new("xai").unwrap(),
|
||||||
|
],
|
||||||
|
vec![
|
||||||
|
model("openai", "shared", native),
|
||||||
|
model("xai", "shared", genai),
|
||||||
|
],
|
||||||
|
vec![],
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
.with_account_directory(account_directory());
|
||||||
|
for (protocol, expected) in [
|
||||||
|
("openai", vec!["openai"]),
|
||||||
|
("anthropic", vec!["openai"]),
|
||||||
|
("genai", vec!["xai"]),
|
||||||
|
(
|
||||||
|
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
||||||
|
vec!["openai", "xai"],
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||||
|
ProtocolPayload::json_object(protocol, Default::default()).unwrap(),
|
||||||
|
));
|
||||||
|
let plan = snapshot
|
||||||
|
.plan(
|
||||||
|
&PublicModelId::new("shared").unwrap(),
|
||||||
|
&operation,
|
||||||
|
account_scope(),
|
||||||
|
&RoutingContext::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
plan.candidates()
|
||||||
|
.iter()
|
||||||
|
.map(|candidate| candidate.provider().as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
expected,
|
||||||
|
"{protocol}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -26,6 +26,442 @@ use gateway_core::routing::{
|
|||||||
};
|
};
|
||||||
use gateway_core::settings::SettingsValues;
|
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::{
|
||||||
|
AccountModelMetadata, 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 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(), high_only.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_translated_generation_protocols(["openai"])
|
||||||
|
.with_upstream_feature_validation()
|
||||||
|
};
|
||||||
|
let variants = BTreeMap::from_iter(["medium", "high"].map(|level| {
|
||||||
|
(
|
||||||
|
level.into(),
|
||||||
|
ReasoningModelVariant {
|
||||||
|
model: UpstreamModelId::new(format!("family-{level}")).unwrap(),
|
||||||
|
accounts: if level == "medium" {
|
||||||
|
BTreeSet::from([declared.clone()])
|
||||||
|
} else {
|
||||||
|
BTreeSet::from([declared.clone(), high_only.clone()])
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
let snapshot = RuntimeSnapshot::new(
|
||||||
|
revision(1),
|
||||||
|
SettingsValues::new(
|
||||||
|
2,
|
||||||
|
"smart",
|
||||||
|
BTreeMap::from([
|
||||||
|
("alias".into(), "family".into()),
|
||||||
|
("pinned".into(), "family-medium".into()),
|
||||||
|
]),
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
vec![provider.clone()],
|
||||||
|
vec![
|
||||||
|
ProviderModel::new(
|
||||||
|
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()
|
||||||
|
.with_dedicated_web_search(BTreeMap::from([(
|
||||||
|
declared.clone(),
|
||||||
|
UpstreamModelId::new("search").unwrap(),
|
||||||
|
)]))
|
||||||
|
.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().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![],
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let search_body = serde_json::json!({"input":"query","tools":[{"type":"web_search"}],"tool_choice":"required"});
|
||||||
|
let search = Operation::Generate(GenerateRequest::from_protocol_payload(
|
||||||
|
ProtocolPayload::json_object("openai", search_body.as_object().unwrap().clone()).unwrap(),
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
snapshot.plan(
|
||||||
|
&PublicModelId::new("family-medium").unwrap(),
|
||||||
|
&search,
|
||||||
|
scope.clone(),
|
||||||
|
&RoutingContext::default()
|
||||||
|
),
|
||||||
|
Err(RoutingError::GroupModelDenied)
|
||||||
|
));
|
||||||
|
let old_account =
|
||||||
|
Arc::new(scope.restricted_to(&BTreeSet::new(), &BTreeSet::from([other.clone()])));
|
||||||
|
assert!(matches!(
|
||||||
|
snapshot.plan(
|
||||||
|
&PublicModelId::new("family-medium").unwrap(),
|
||||||
|
&search,
|
||||||
|
old_account,
|
||||||
|
&RoutingContext::default()
|
||||||
|
),
|
||||||
|
Err(RoutingError::WebSearchUnavailable)
|
||||||
|
));
|
||||||
|
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();
|
||||||
|
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"] {
|
||||||
|
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
|
||||||
|
.public_model_profiles_for_scope(&blocked)
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
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)]
|
#[derive(Clone)]
|
||||||
struct TestSnapshotStore {
|
struct TestSnapshotStore {
|
||||||
facts: Arc<Mutex<Result<SnapshotFacts, SnapshotStoreError>>>,
|
facts: Arc<Mutex<Result<SnapshotFacts, SnapshotStoreError>>>,
|
||||||
|
|||||||
@@ -508,15 +508,14 @@ Responses 终端重新解码插件正文时读取改写后的正文上限;atte
|
|||||||
更早的改写使用上述 HTTP 请求的 `settings`。`request.head.settings_sources` 使用相同的来源结构,`execution.input` 表示进入当前 Key 作用域时的有效值。
|
更早的改写使用上述 HTTP 请求的 `settings`。`request.head.settings_sources` 使用相同的来源结构,`execution.input` 表示进入当前 Key 作用域时的有效值。
|
||||||
原生 Responses WebSocket 每轮请求读取当前宿主快照,重新认证并解析 Key 策略,同时保留握手阶段的显式改写;已开始的执行保持自己的冻结值
|
原生 Responses WebSocket 每轮请求读取当前宿主快照,重新认证并解析 Key 策略,同时保留握手阶段的显式改写;已开始的执行保持自己的冻结值
|
||||||
|
|
||||||
Chat Completions 在 request 与 attempt 挂载中使用规范化的 Responses 请求和响应正文,
|
Chat Completions 在 request 与 attempt 挂载中保留 Chat 正文,`request.head.endpoint` 为 `/v1/chat/completions`,
|
||||||
`request.head.endpoint` 仍为 `/v1/chat/completions`,`protocol` 仍为 `openai`。
|
`protocol` 为 `chat_completions`。request 改写按 Chat 合同重新解码,`messages` 不会在进入选路前变成 Responses `input`。
|
||||||
request 改写按 Responses 合同重新解码,响应先经过该合同的复核,再由 API 投影成 Chat 交给外层 HTTP 挂载。
|
Provider 选定账号后直接转换到实际目标,`outbound` 看到目标协议请求;回程直接产生 Chat JSON 或 chunks,再经过对应响应挂载与 API 交付校验。
|
||||||
Chat 的下游流模式及 `include_usage` 由 API 持有,request 阶段不能切换已确定的下游流模式。
|
下游流模式由 API 入口固定,request 阶段不能切换已经确定的 HTTP 响应模式。
|
||||||
同一边界的原样保留不要求 Chat 与 Responses 字节相同;需要读写 `messages` 或 `choices` 的插件应使用 HTTP 挂载,
|
同一挂载边界仍遵守原始字节保留规则;字段范围见 [Chat 合同](../../../../../docs/api.md#chat-completions-请求)
|
||||||
字段范围见 [Chat 合同](../../../../../docs/api.md#chat-completions-请求)
|
|
||||||
|
|
||||||
Messages 入站的 `protocol` 为 `anthropic`,端点为 `/v1/messages`;计数使用 `/v1/messages/count_tokens` 与 `count_tokens` 操作
|
Messages 入站的 `protocol` 为 `anthropic`,端点为 `/v1/messages`;计数使用 `/v1/messages/count_tokens` 与 `count_tokens` 操作。
|
||||||
同协议请求保留原生正文,Responses 与 Messages 之间的转换发生在所选上游的执行边界
|
原生请求只选择同协议账号,不调用内置 Chat 转换。插件自行承担转换与回译;宿主不保留旧 Chat 视图,不修复插件输出或补偿插件状态
|
||||||
|
|
||||||
中间件可读取和改写完整请求、响应 headers、正文与响应帧,也不按字段名称过滤认证、Cookie、会话或连接头。
|
中间件可读取和改写完整请求、响应 headers、正文与响应帧,也不按字段名称过滤认证、Cookie、会话或连接头。
|
||||||
该能力遵循[完整信任](manifest.md#完整信任)边界;类型、HTTP 格式、大小及资源生命周期仍需符合合同
|
该能力遵循[完整信任](manifest.md#完整信任)边界;类型、HTTP 格式、大小及资源生命周期仍需符合合同
|
||||||
|
|||||||
@@ -87,8 +87,6 @@ pub enum PrivacyAction {
|
|||||||
RenameKey,
|
RenameKey,
|
||||||
RemoveField,
|
RemoveField,
|
||||||
AnonymizeProject,
|
AnonymizeProject,
|
||||||
/// 已保存的组合动作继续执行,编辑器将其展开为独立步骤
|
|
||||||
AnonymizeWorkspace,
|
|
||||||
}
|
}
|
||||||
#[derive(Clone, Serialize, Deserialize)]
|
#[derive(Clone, Serialize, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ name = "main"
|
|||||||
path = "tests/main.rs"
|
path = "tests/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
sha2 = "0.11.0"
|
||||||
|
url = "2.5.8"
|
||||||
http = "1.5.0"
|
http = "1.5.0"
|
||||||
httpdate = "1.0.3"
|
httpdate = "1.0.3"
|
||||||
memchr = "2.8.3"
|
memchr = "2.8.3"
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ use serde_json::Value;
|
|||||||
/// 转换器消费的模型目录事实;None 表示上游未声明
|
/// 转换器消费的模型目录事实;None 表示上游未声明
|
||||||
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
#[derive(Debug, Default, Clone, PartialEq, Eq)]
|
||||||
pub struct MessagesModelCapabilities {
|
pub struct MessagesModelCapabilities {
|
||||||
|
pub hosted_web_search: Option<bool>,
|
||||||
pub thinking: Option<bool>,
|
pub thinking: Option<bool>,
|
||||||
pub adaptive_thinking: Option<bool>,
|
pub adaptive_thinking: Option<bool>,
|
||||||
pub manual_thinking: Option<bool>,
|
pub manual_thinking: Option<bool>,
|
||||||
@@ -17,6 +18,7 @@ impl MessagesModelCapabilities {
|
|||||||
/// 从 Anthropic Models 条目提取转换所需事实,未知扩展不影响解析
|
/// 从 Anthropic Models 条目提取转换所需事实,未知扩展不影响解析
|
||||||
pub fn from_model(model: &Value) -> Self {
|
pub fn from_model(model: &Value) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
hosted_web_search: None,
|
||||||
thinking: model
|
thinking: model
|
||||||
.pointer("/capabilities/thinking/supported")
|
.pointer("/capabilities/thinking/supported")
|
||||||
.and_then(Value::as_bool),
|
.and_then(Value::as_bool),
|
||||||
|
|||||||
@@ -1,173 +0,0 @@
|
|||||||
//! 文本、多模态内容和不透明回传载荷的协议表示
|
|
||||||
|
|
||||||
use serde_json::{Value, json};
|
|
||||||
|
|
||||||
const ANTHROPIC_CARRIER: &str = "cpr:anthropic:v1:";
|
|
||||||
const OPENAI_CARRIER: &str = "cpr:openai:v1:";
|
|
||||||
pub(crate) const GENAI_CARRIER: &str = "cpr:genai:v1:";
|
|
||||||
const REDACTED_CARRIER: &str = "claude-redacted-thinking:";
|
|
||||||
|
|
||||||
pub(super) fn text(value: &Value) -> String {
|
|
||||||
match value {
|
|
||||||
Value::String(value) => value.clone(),
|
|
||||||
Value::Array(parts) => parts
|
|
||||||
.iter()
|
|
||||||
.filter_map(|part| {
|
|
||||||
part.get("text")
|
|
||||||
.or_else(|| part.get("thinking"))
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.join("\n"),
|
|
||||||
_ => String::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn blocks(value: Option<&Value>) -> Vec<Value> {
|
|
||||||
match value {
|
|
||||||
Some(Value::String(text)) => vec![json!({"type":"text","text":text})],
|
|
||||||
Some(Value::Array(parts)) => parts.clone(),
|
|
||||||
_ => Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn to_responses_content(block: &Value, assistant: bool) -> Option<Value> {
|
|
||||||
match block.get("type").and_then(Value::as_str)? {
|
|
||||||
"text" => Some(
|
|
||||||
json!({"type": if assistant {"output_text"} else {"input_text"}, "text":block.get("text").and_then(Value::as_str).unwrap_or_default()}),
|
|
||||||
),
|
|
||||||
"image" => {
|
|
||||||
let source = block.get("source")?;
|
|
||||||
let url = source_url(source)?;
|
|
||||||
Some(json!({"type":"input_image","image_url":url}))
|
|
||||||
}
|
|
||||||
"document" => {
|
|
||||||
let source = block.get("source")?;
|
|
||||||
match source.get("type").and_then(Value::as_str)? {
|
|
||||||
"text" => Some(
|
|
||||||
json!({"type":"input_text","text":source.get("data").and_then(Value::as_str).unwrap_or_default()}),
|
|
||||||
),
|
|
||||||
"file" => Some(json!({"type":"input_file","file_id":source.get("file_id")?})),
|
|
||||||
"url" => Some(json!({"type":"input_file","file_url":source.get("url")?})),
|
|
||||||
"base64" => Some(
|
|
||||||
json!({"type":"input_file","filename":block.get("title").and_then(Value::as_str).unwrap_or("document.pdf"),"file_data":source_url(source)?}),
|
|
||||||
),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
"search_result" => Some(
|
|
||||||
json!({"type":"input_text","text":text(block.get("content").unwrap_or(&Value::Null))}),
|
|
||||||
),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn to_messages_content(part: &Value) -> Option<Value> {
|
|
||||||
match part.get("type").and_then(Value::as_str)? {
|
|
||||||
"input_text" | "output_text" | "text" => Some(
|
|
||||||
json!({"type":"text","text":part.get("text").and_then(Value::as_str).unwrap_or_default()}),
|
|
||||||
),
|
|
||||||
"refusal" => Some(
|
|
||||||
json!({"type":"text","text":part.get("refusal").and_then(Value::as_str).unwrap_or_default()}),
|
|
||||||
),
|
|
||||||
"input_image" => {
|
|
||||||
let url = part
|
|
||||||
.get("image_url")
|
|
||||||
.and_then(|v| v.as_str().or_else(|| v.get("url").and_then(Value::as_str)))?;
|
|
||||||
Some(json!({"type":"image","source":url_source(url)}))
|
|
||||||
}
|
|
||||||
"input_file" => {
|
|
||||||
let source = if let Some(data) = part.get("file_data").and_then(Value::as_str) {
|
|
||||||
url_source(data)
|
|
||||||
} else if let Some(url) = part.get("file_url").and_then(Value::as_str) {
|
|
||||||
json!({"type":"url","url":url})
|
|
||||||
} else {
|
|
||||||
json!({"type":"file","file_id":part.get("file_id")?})
|
|
||||||
};
|
|
||||||
Some(json!({"type":"document","source":source}))
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn source_url(source: &Value) -> Option<String> {
|
|
||||||
match source.get("type").and_then(Value::as_str)? {
|
|
||||||
"url" => source.get("url").and_then(Value::as_str).map(str::to_owned),
|
|
||||||
"base64" => Some(format!(
|
|
||||||
"data:{};base64,{}",
|
|
||||||
source.get("media_type").and_then(Value::as_str)?,
|
|
||||||
source.get("data").and_then(Value::as_str)?
|
|
||||||
)),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn url_source(url: &str) -> Value {
|
|
||||||
if let Some(data) = url.strip_prefix("data:")
|
|
||||||
&& let Some((media_type, data)) = data.split_once(";base64,")
|
|
||||||
{
|
|
||||||
return json!({"type":"base64","media_type":media_type,"data":data});
|
|
||||||
}
|
|
||||||
json!({"type":"url","url":url})
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn reasoning_text(item: &Value) -> String {
|
|
||||||
let summary = text(item.get("summary").unwrap_or(&Value::Null));
|
|
||||||
if summary.is_empty() {
|
|
||||||
text(item.get("content").unwrap_or(&Value::Null))
|
|
||||||
} else {
|
|
||||||
summary
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn anthropic_carrier(block: &Value) -> String {
|
|
||||||
format!("{ANTHROPIC_CARRIER}{block}")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn openai_carrier(item: &Value) -> String {
|
|
||||||
format!("{OPENAI_CARRIER}{item}")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn is_openai_carrier(block: &Value) -> bool {
|
|
||||||
block.get("type").and_then(Value::as_str) == Some("thinking")
|
|
||||||
&& block
|
|
||||||
.get("signature")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.is_some_and(|signature| signature.starts_with(OPENAI_CARRIER))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn is_anthropic_carrier(item: &Value) -> bool {
|
|
||||||
item.get("type").and_then(Value::as_str) == Some("reasoning")
|
|
||||||
&& item
|
|
||||||
.get("encrypted_content")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.is_some_and(|carrier| carrier.starts_with(ANTHROPIC_CARRIER))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn restore_anthropic(item: &Value) -> Option<Value> {
|
|
||||||
let carrier = item.get("encrypted_content")?.as_str()?;
|
|
||||||
if let Some(raw) = carrier.strip_prefix(ANTHROPIC_CARRIER) {
|
|
||||||
return serde_json::from_str(raw).ok();
|
|
||||||
}
|
|
||||||
if let Some(data) = carrier.strip_prefix(REDACTED_CARRIER) {
|
|
||||||
return Some(json!({"type":"redacted_thinking","data":data}));
|
|
||||||
}
|
|
||||||
// CPA 识别来源后回放签名,CPR 自己发出的载荷携带完整块以保留精确回传内容
|
|
||||||
if carrier.starts_with("claude#") || carrier.starts_with("anthropic#") {
|
|
||||||
return Some(
|
|
||||||
json!({"type":"thinking","thinking":reasoning_text(item),"signature":carrier.split_once('#')?.1}),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn restore_openai(block: &Value) -> Option<Value> {
|
|
||||||
let signature = block.get("signature")?.as_str()?;
|
|
||||||
if let Some(raw) = signature.strip_prefix(OPENAI_CARRIER) {
|
|
||||||
return serde_json::from_str(raw).ok();
|
|
||||||
}
|
|
||||||
if signature.starts_with("gAAAA") {
|
|
||||||
return Some(json!({"type":"reasoning","summary":[],"encrypted_content":signature}));
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user