mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-28 16:00:41 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84e44bc000 | ||
|
|
e6def7b634 | ||
|
|
f5d3c55d75 | ||
|
|
30487dfbf1 | ||
|
|
71cfdcb33e | ||
|
|
98954aefb6 | ||
|
|
c74c570228 | ||
|
|
fbf1aa1d9b |
@@ -71,6 +71,7 @@ pub struct RuntimeSettingsValues {
|
||||
pub usage_retention_days: u32,
|
||||
pub ops_event_retention_days: u32,
|
||||
pub audit_retention_days: u32,
|
||||
pub prompt_rewrite_rules: Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>,
|
||||
pub account_error_protection: gateway_core::account::AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
|
||||
@@ -1229,6 +1229,7 @@ impl SettingsStore for StaticSettingsStore {
|
||||
usage_retention_days: 30,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
|
||||
@@ -62,6 +62,7 @@ fn runtime_settings(enabled: bool, probe_enabled: bool) -> RuntimeSettings {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 90,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection {
|
||||
enabled,
|
||||
probe_enabled,
|
||||
|
||||
@@ -366,6 +366,7 @@ impl SettingsStore for FixtureSettingsStore {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
|
||||
@@ -56,7 +56,9 @@ impl VisitMut for WireTypes {
|
||||
}
|
||||
let last = path.path.segments.last().unwrap().clone();
|
||||
*ty = match last.ident.to_string().as_str() {
|
||||
"DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" => parse_quote!(String),
|
||||
"DateTime" | "Tz" | "TokenPrice" | "AdminApiKey" | "ProviderKind" => {
|
||||
parse_quote!(String)
|
||||
}
|
||||
"Value" => parse_quote!(serde_json::Value),
|
||||
"OpaqueProviderData" => parse_quote!(serde_json::Map<String, serde_json::Value>),
|
||||
_ => Type::Path(syn::TypePath {
|
||||
@@ -80,6 +82,7 @@ fn contract_type(mut item: Item, name: &str) -> Item {
|
||||
| "ReplaceRuntimeSettings"
|
||||
| "AdminApiKeyMutation"
|
||||
| "RegeneratedAdminApiKey"
|
||||
| "PromptRewriteRule"
|
||||
| "CodexPrivacyPolicy"
|
||||
| "PrivacyRule"
|
||||
| "PrivacyStep"
|
||||
@@ -113,6 +116,15 @@ fn contract_type(mut item: Item, name: &str) -> Item {
|
||||
if let Some(fields) = fields {
|
||||
for field in fields {
|
||||
field.vis = parse_quote!(pub);
|
||||
// 非空名称与前缀由宿主在接收设置时校验,SDK 只描述字符串合同
|
||||
if name == "PromptRewriteRule"
|
||||
&& field
|
||||
.ident
|
||||
.as_ref()
|
||||
.is_some_and(|id| id == "pattern" || id == "name")
|
||||
{
|
||||
field.attrs.retain(|attr| !attr.path().is_ident("serde"));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Item::Enum(item) = &mut item {
|
||||
@@ -225,6 +237,10 @@ fn sdk_settings_contract_matches_host_declarations() {
|
||||
"AccountErrorOperator",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/prompt_rewrite.rs",
|
||||
&["PromptRewriteRule"][..],
|
||||
),
|
||||
(
|
||||
"../gateway-core/src/settings/websocket.rs",
|
||||
&["OpenAiWebSocketPoolSettings"][..],
|
||||
|
||||
@@ -376,6 +376,7 @@ async fn settings_should_reject_zero_refresh_margin_before_store_call() {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 30,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection:
|
||||
gateway_core::account::AccountErrorProtection::default(),
|
||||
account_warmup_enabled: false,
|
||||
|
||||
@@ -62,6 +62,7 @@ pub struct RuntimeSettingsFields {
|
||||
pub usage_retention_days: u64,
|
||||
pub ops_event_retention_days: u64,
|
||||
pub audit_retention_days: u64,
|
||||
pub prompt_rewrite_rules: Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>,
|
||||
pub account_error_protection: gateway_core::account::AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
@@ -744,6 +745,7 @@ impl RuntimeSettingsFields {
|
||||
.map_err(|_| WireValidationError::new("settingsOpsRetentionOverflow"))?,
|
||||
audit_retention_days: u32::try_from(self.audit_retention_days)
|
||||
.map_err(|_| WireValidationError::new("settingsAuditRetentionOverflow"))?,
|
||||
prompt_rewrite_rules: self.prompt_rewrite_rules,
|
||||
account_error_protection: self.account_error_protection,
|
||||
account_warmup_enabled: self.account_warmup_enabled,
|
||||
account_warmup_cron: self.account_warmup_cron,
|
||||
@@ -787,6 +789,7 @@ impl From<gateway_admin::model::settings::RuntimeSettingsValues> for RuntimeSett
|
||||
usage_retention_days: u64::from(settings.usage_retention_days),
|
||||
ops_event_retention_days: u64::from(settings.ops_event_retention_days),
|
||||
audit_retention_days: u64::from(settings.audit_retention_days),
|
||||
prompt_rewrite_rules: settings.prompt_rewrite_rules,
|
||||
account_error_protection: settings.account_error_protection,
|
||||
account_warmup_enabled: settings.account_warmup_enabled,
|
||||
account_warmup_cron: settings.account_warmup_cron,
|
||||
|
||||
@@ -2016,6 +2016,7 @@ fn test_runtime_settings() -> RuntimeSettings {
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 90,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: Default::default(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
|
||||
@@ -106,6 +106,7 @@ fn update_body() -> Value {
|
||||
"usageRetentionDays": 31,
|
||||
"opsEventRetentionDays": 31,
|
||||
"auditRetentionDays": 91,
|
||||
"promptRewriteRules": [],
|
||||
"accountErrorProtection": gateway_core::account::AccountErrorProtection::default(),
|
||||
"accountWarmupEnabled": false,
|
||||
"accountWarmupCron": "0 8 * * *",
|
||||
@@ -289,6 +290,21 @@ async fn error_protection_rules_round_trip_and_invalid_policy_does_not_replace_t
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_rewrite_requires_names_and_prefixes_and_rejects_unknown_fields() {
|
||||
let mut body = update_body();
|
||||
for rule in [
|
||||
json!({"name":"规则", "pattern":"prefix", "replacement":"", "unknownField":["xai"]}),
|
||||
json!({"name":"规则", "pattern":"", "replacement":""}),
|
||||
json!({"pattern":"prefix", "replacement":""}),
|
||||
json!({"name":"", "pattern":"prefix", "replacement":""}),
|
||||
json!({"name":" ", "pattern":"prefix", "replacement":""}),
|
||||
] {
|
||||
body["promptRewriteRules"] = json!([rule]);
|
||||
assert!(serde_json::from_value::<UpdateRuntimeSettingsRequest>(body.clone()).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_protection_requires_an_explicit_policy_in_settings_replacement() {
|
||||
let mut missing = update_body();
|
||||
|
||||
@@ -1201,6 +1201,7 @@ where
|
||||
.with_response_control(self.response_control.clone())
|
||||
.with_request_profile(self.request_profiles.get(candidate.provider()).cloned())
|
||||
.with_fast_mode(self.plan.fast_mode())
|
||||
.with_prompt_rewrite_rules(self.plan.prompt_rewrite_rules(candidate.provider()))
|
||||
.with_pricing(self.plan.pricing())
|
||||
.with_request_location(self.plan.request_location().cloned())
|
||||
.with_openai_websocket_pool(*self.plan.openai_websocket_pool())
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod nested;
|
||||
pub mod observation;
|
||||
pub mod policy;
|
||||
pub mod probe;
|
||||
mod prompt_rewrite;
|
||||
pub mod provider;
|
||||
pub mod response_control;
|
||||
pub mod upstream_adapter;
|
||||
@@ -324,6 +325,7 @@ pub struct RequestAttemptContext {
|
||||
request_body_limit: Option<usize>,
|
||||
lease_metadata: Option<Arc<crate::provider_ports::ProviderLeaseMetadata>>,
|
||||
response_control: Option<response_control::ResponseControl>,
|
||||
prompt_rewrite_rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
||||
pricing: Arc<crate::metering::PricingOverrides>,
|
||||
request_profile: Option<crate::account::OpaqueProviderData>,
|
||||
fast_mode: FastMode,
|
||||
@@ -396,6 +398,15 @@ impl RequestAttemptContext {
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_prompt_rewrite_rules(
|
||||
mut self,
|
||||
rules: Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>>,
|
||||
) -> Self {
|
||||
self.prompt_rewrite_rules = rules;
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub fn with_pricing(mut self, pricing: Arc<crate::metering::PricingOverrides>) -> Self {
|
||||
self.pricing = pricing;
|
||||
@@ -463,6 +474,7 @@ impl RequestAttemptContext {
|
||||
request_id,
|
||||
client_api_key_ref,
|
||||
request_profile: None,
|
||||
prompt_rewrite_rules: None,
|
||||
pricing: Arc::default(),
|
||||
fast_mode: FastMode::Default,
|
||||
openai_websocket_pool: Default::default(),
|
||||
@@ -832,6 +844,21 @@ impl AttemptContext {
|
||||
self.request.extension_scope()
|
||||
}
|
||||
|
||||
/// 计数由 Provider 解开入站封套后在现有正文上应用同一份规则
|
||||
pub fn rewrite_count_prompt(
|
||||
&self,
|
||||
protocol: &str,
|
||||
body: &mut serde_json::Map<String, serde_json::Value>,
|
||||
) {
|
||||
if let Some(rules) = &self.request.prompt_rewrite_rules
|
||||
&& let Some(edit) = gateway_protocol::prompt_rewrite::plan(protocol, body, |text| {
|
||||
rules.replace_prefix(text)
|
||||
})
|
||||
{
|
||||
edit.apply(body);
|
||||
}
|
||||
}
|
||||
|
||||
/// 在已选账号并持有其 lease 后,以 owned terminal 执行本次 retry 的中间件链
|
||||
///
|
||||
/// terminal 返回的 stream 仍须保持 cold;中间件不能取得 credential、发送状态、
|
||||
@@ -860,6 +887,12 @@ impl AttemptContext {
|
||||
} else {
|
||||
terminal
|
||||
};
|
||||
let terminal = match (&operation, &self.request.prompt_rewrite_rules) {
|
||||
(crate::operation::Operation::Generate(_), Some(rules)) => {
|
||||
prompt_rewrite::wrap(terminal, rules)
|
||||
}
|
||||
_ => terminal,
|
||||
};
|
||||
// 保护观察真正的 Provider terminal,先于 attempt 中间件的响应改写
|
||||
let terminal: provider::ProviderMiddlewareTerminal =
|
||||
if let Some(protection) = self.request.account_error_protection.clone() {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
//! 在 attempt 中间件提交后应用所选平台的生成规则
|
||||
|
||||
use super::provider::ProviderMiddlewareTerminal;
|
||||
use crate::{operation::Operation, settings::prompt_rewrite::ProviderPromptRules};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(super) fn wrap(
|
||||
terminal: ProviderMiddlewareTerminal,
|
||||
rules: &Arc<ProviderPromptRules>,
|
||||
) -> ProviderMiddlewareTerminal {
|
||||
let rules = Arc::clone(rules);
|
||||
Box::new(move |mut operation, headers| {
|
||||
if let Operation::Generate(request) = &mut operation {
|
||||
let payload = request.protocol_payload();
|
||||
if let Some(edit) =
|
||||
gateway_protocol::prompt_rewrite::plan(payload.protocol(), payload.body(), |text| {
|
||||
rules.replace_prefix(text)
|
||||
})
|
||||
{
|
||||
request.apply_prompt_edit(edit);
|
||||
}
|
||||
}
|
||||
terminal(operation, headers)
|
||||
})
|
||||
}
|
||||
@@ -462,6 +462,23 @@ impl ClientTurn {
|
||||
}
|
||||
|
||||
impl GenerateRequest {
|
||||
/// 只在命中后对共享请求执行写时复制,重试持有的原请求仍可独立使用
|
||||
pub(crate) fn apply_prompt_edit(&mut self, edit: gateway_protocol::prompt_rewrite::PromptEdit) {
|
||||
let wire = match self.protocol_payload().raw_json_body() {
|
||||
Some(body) => {
|
||||
let Some(updated) = edit.wire(body) else {
|
||||
return;
|
||||
};
|
||||
Some(Bytes::from(updated))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let payload = Arc::make_mut(&mut self.payload);
|
||||
edit.apply(&mut payload.protocol_payload.body);
|
||||
payload.protocol_payload.raw_json_body = wire;
|
||||
// 只编辑字符串内容,能力、角色与工具结构仍使用已有的 wire_facts
|
||||
}
|
||||
|
||||
/// 返回可信入口协议,直接转换只能更新当前 wire,不能改写请求来源
|
||||
#[must_use]
|
||||
pub fn source_protocol(&self) -> &str {
|
||||
|
||||
@@ -714,6 +714,7 @@ impl ProviderCandidate {
|
||||
/// 一次请求冻结的 Provider 尝试顺序
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RoutingPlan {
|
||||
prompt_rewrite: Arc<crate::settings::prompt_rewrite::CompiledPromptRewrite>,
|
||||
account_error_protection: Arc<crate::account::CompiledAccountErrorProtection>,
|
||||
account_error_protection_revision: u64,
|
||||
request_body_limit: usize,
|
||||
@@ -732,6 +733,14 @@ pub struct RoutingPlan {
|
||||
}
|
||||
|
||||
impl RoutingPlan {
|
||||
#[must_use]
|
||||
pub fn prompt_rewrite_rules(
|
||||
&self,
|
||||
provider: &ProviderKind,
|
||||
) -> Option<Arc<crate::settings::prompt_rewrite::ProviderPromptRules>> {
|
||||
self.prompt_rewrite.for_provider(provider)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn account_error_protection_revision(&self) -> u64 {
|
||||
self.account_error_protection_revision
|
||||
|
||||
@@ -2060,6 +2060,7 @@ impl RuntimeSnapshot {
|
||||
self.settings.values.max_retry_after_seconds,
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
prompt_rewrite: Arc::clone(&self.settings.prompt_rewrite),
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
openai_websocket_pool: *self.settings.values.openai_websocket_pool(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
@@ -2153,6 +2154,7 @@ impl RuntimeSnapshot {
|
||||
self.settings.values.max_retry_after_seconds,
|
||||
)),
|
||||
config_revision: self.revision,
|
||||
prompt_rewrite: Arc::clone(&self.settings.prompt_rewrite),
|
||||
pricing: Arc::clone(&self.settings.values.pricing),
|
||||
openai_websocket_pool: *self.settings.values.openai_websocket_pool(),
|
||||
openai_request_settings: self.settings.values.openai_request_settings().clone(),
|
||||
|
||||
@@ -13,6 +13,7 @@ use crate::{
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct CompiledSettings {
|
||||
pub(crate) values: SettingsValues,
|
||||
pub(crate) prompt_rewrite: std::sync::Arc<super::prompt_rewrite::CompiledPromptRewrite>,
|
||||
pub(crate) account_error_protection:
|
||||
std::sync::Arc<crate::account::CompiledAccountErrorProtection>,
|
||||
pub(crate) privacy: Option<std::sync::Arc<dyn super::privacy::CompiledPrivacyPolicy>>,
|
||||
@@ -40,6 +41,16 @@ impl CompiledSettings {
|
||||
.account_error_protection
|
||||
.validate()
|
||||
.map_err(|_| InvalidSettings)?;
|
||||
let prompt_rewrite = previous
|
||||
.filter(|prior| prior.values.prompt_rewrite_rules == settings.prompt_rewrite_rules)
|
||||
.map_or_else(
|
||||
|| {
|
||||
std::sync::Arc::new(super::prompt_rewrite::CompiledPromptRewrite::new(
|
||||
std::sync::Arc::clone(&settings.prompt_rewrite_rules),
|
||||
))
|
||||
},
|
||||
|prior| prior.prompt_rewrite.clone(),
|
||||
);
|
||||
let account_error_protection = previous
|
||||
.filter(|previous| {
|
||||
previous.values.account_error_protection == settings.account_error_protection
|
||||
@@ -130,6 +141,7 @@ impl CompiledSettings {
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
prompt_rewrite,
|
||||
account_error_protection,
|
||||
account_selection_policy,
|
||||
client_queue_policy,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
pub(crate) mod compiled;
|
||||
mod openai;
|
||||
pub mod privacy;
|
||||
pub mod prompt_rewrite;
|
||||
pub mod request_profiles;
|
||||
mod values;
|
||||
mod websocket;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! 按目标上游索引规则,共享配置原文,按配置顺序匹配前缀
|
||||
|
||||
use crate::identity::ProviderKind;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fmt,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PromptRewriteRule {
|
||||
#[serde(deserialize_with = "nonempty_name")]
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
providers: BTreeSet<ProviderKind>,
|
||||
#[serde(deserialize_with = "nonempty_pattern")]
|
||||
pattern: String,
|
||||
replacement: String,
|
||||
}
|
||||
|
||||
impl fmt::Debug for PromptRewriteRule {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("PromptRewriteRule")
|
||||
.field("providers", &self.providers)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
fn nonempty_name<'de, D: serde::Deserializer<'de>>(de: D) -> Result<String, D::Error> {
|
||||
let name = String::deserialize(de)?;
|
||||
if name.trim().is_empty() {
|
||||
return Err(serde::de::Error::custom("规则名称不能为空"));
|
||||
}
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
fn nonempty_pattern<'de, D: serde::Deserializer<'de>>(de: D) -> Result<String, D::Error> {
|
||||
let pattern = String::deserialize(de)?;
|
||||
if pattern.is_empty() {
|
||||
return Err(serde::de::Error::custom("匹配文本不能为空"));
|
||||
}
|
||||
Ok(pattern)
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ProviderPromptRules {
|
||||
rules: Arc<[PromptRewriteRule]>,
|
||||
global: Arc<BTreeSet<usize>>,
|
||||
scoped: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
impl ProviderPromptRules {
|
||||
pub fn replace_prefix(&self, text: &str) -> Option<String> {
|
||||
let (rule, suffix) = self
|
||||
.global
|
||||
.union(&self.scoped)
|
||||
.map(|&index| &self.rules[index])
|
||||
.find_map(|rule| {
|
||||
text.strip_prefix(&rule.pattern)
|
||||
.map(|suffix| (rule, suffix))
|
||||
})?;
|
||||
if rule.pattern == rule.replacement {
|
||||
return None;
|
||||
}
|
||||
let mut updated = String::with_capacity(rule.replacement.len() + suffix.len());
|
||||
updated.push_str(&rule.replacement);
|
||||
updated.push_str(suffix);
|
||||
Some(updated)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct CompiledPromptRewrite {
|
||||
all: Option<Arc<ProviderPromptRules>>,
|
||||
by_provider: BTreeMap<ProviderKind, Arc<ProviderPromptRules>>,
|
||||
}
|
||||
|
||||
impl CompiledPromptRewrite {
|
||||
pub fn new(rules: Arc<[PromptRewriteRule]>) -> Self {
|
||||
let mut global = BTreeSet::new();
|
||||
let mut scoped = BTreeMap::<_, BTreeSet<_>>::new();
|
||||
for (index, rule) in rules.iter().enumerate() {
|
||||
if rule.providers.is_empty() {
|
||||
global.insert(index);
|
||||
} else {
|
||||
for provider in &rule.providers {
|
||||
scoped.entry(provider).or_default().insert(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
let global = Arc::new(global);
|
||||
let selection = |scoped| {
|
||||
Arc::new(ProviderPromptRules {
|
||||
rules: Arc::clone(&rules),
|
||||
global: Arc::clone(&global),
|
||||
scoped,
|
||||
})
|
||||
};
|
||||
Self {
|
||||
all: (!global.is_empty()).then(|| selection(BTreeSet::new())),
|
||||
by_provider: scoped
|
||||
.into_iter()
|
||||
.map(|(id, indices)| (id.clone(), selection(indices)))
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn for_provider(&self, provider: &ProviderKind) -> Option<Arc<ProviderPromptRules>> {
|
||||
self.by_provider
|
||||
.get(provider)
|
||||
.or(self.all.as_ref())
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ use crate::identity::ProviderKind;
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SettingsValues {
|
||||
#[serde(default)]
|
||||
pub(crate) prompt_rewrite_rules: Arc<[super::prompt_rewrite::PromptRewriteRule]>,
|
||||
#[serde(default)]
|
||||
pub(crate) account_error_protection: crate::account::AccountErrorProtection,
|
||||
#[serde(skip, default = "initial_protection_revision")]
|
||||
@@ -45,6 +47,15 @@ fn initial_protection_revision() -> u64 {
|
||||
}
|
||||
|
||||
impl SettingsValues {
|
||||
#[must_use]
|
||||
pub fn with_prompt_rewrite_rules(
|
||||
mut self,
|
||||
rules: Vec<super::prompt_rewrite::PromptRewriteRule>,
|
||||
) -> Self {
|
||||
self.prompt_rewrite_rules = rules.into();
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn with_account_error_protection_revision(mut self, revision: u64) -> Self {
|
||||
self.account_error_protection_revision = revision;
|
||||
@@ -222,6 +233,7 @@ impl SettingsValues {
|
||||
min_codex_cli_version: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
prompt_rewrite_rules: Default::default(),
|
||||
account_error_protection: Default::default(),
|
||||
account_error_protection_revision: 1,
|
||||
request_profiles: Arc::default(),
|
||||
|
||||
@@ -437,3 +437,29 @@ fn chat_source_survives_the_one_authorized_wire_translation() {
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmatched_prompt_prefixes_do_not_allocate_for_large_histories() {
|
||||
use gateway_core::{identity::ProviderKind, settings::prompt_rewrite::CompiledPromptRewrite};
|
||||
use gateway_protocol::prompt_rewrite::plan;
|
||||
let body = serde_json::json!({"instructions": "Custom instructions", "input": "x".repeat(1024 * 1024)});
|
||||
let body = body.as_object().unwrap();
|
||||
let rules = CompiledPromptRewrite::new(
|
||||
serde_json::from_value(json!([{
|
||||
"name":"客户端身份", "pattern":"Unknown", "replacement":"Changed"
|
||||
}]))
|
||||
.unwrap(),
|
||||
)
|
||||
.for_provider(&ProviderKind::new("openai").unwrap())
|
||||
.unwrap();
|
||||
let stats = allocation_counter::measure(|| {
|
||||
for _ in 0..1000 {
|
||||
assert!(
|
||||
plan("openai", std::hint::black_box(body), |text| rules
|
||||
.replace_prefix(text))
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
});
|
||||
assert_eq!(stats.count_total, 0);
|
||||
}
|
||||
|
||||
@@ -1817,6 +1817,63 @@ fn withdrawn_provider_keeps_accounts_without_becoming_a_route_or_expanding_group
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompt_rules_are_selected_once_by_upstream_and_keep_global_order() {
|
||||
let snapshot = super::snapshot();
|
||||
let plan_for = |rules| {
|
||||
let configured = snapshot
|
||||
.with_settings(&snapshot.settings().clone().with_prompt_rewrite_rules(rules))
|
||||
.unwrap();
|
||||
configured
|
||||
.plan(
|
||||
&PublicModelId::new("gpt-5.4").unwrap(),
|
||||
&super::operation(),
|
||||
configured.all_account_scope(),
|
||||
&Default::default(),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let openai = ProviderKind::new("openai").unwrap();
|
||||
let agy = ProviderKind::new("antigravity").unwrap();
|
||||
let xai = ProviderKind::new("xai").unwrap();
|
||||
let scoped = |targets, prefix| {
|
||||
serde_json::from_value(
|
||||
serde_json::json!({"name": "客户端身份", "providers": targets, "pattern": prefix, "replacement": ""}),
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
let only_agy = plan_for(vec![scoped(vec!["antigravity"], "example"); 20]);
|
||||
assert!(only_agy.prompt_rewrite_rules(&openai).is_none());
|
||||
let selected = only_agy.prompt_rewrite_rules(&agy).unwrap();
|
||||
assert_eq!(
|
||||
selected.replace_prefix("example suffix").as_deref(),
|
||||
Some(" suffix")
|
||||
);
|
||||
assert!(Arc::ptr_eq(
|
||||
&selected,
|
||||
&only_agy.prompt_rewrite_rules(&agy).unwrap()
|
||||
));
|
||||
|
||||
let mixed = plan_for(vec![
|
||||
scoped(vec![], "shared first"),
|
||||
scoped(vec!["xai", "antigravity"], "shared"),
|
||||
scoped(vec![], "sh"),
|
||||
]);
|
||||
for provider in [&agy, &xai] {
|
||||
let rules = mixed.prompt_rewrite_rules(provider).unwrap();
|
||||
assert_eq!(rules.replace_prefix("shared first!").as_deref(), Some("!"));
|
||||
assert_eq!(
|
||||
rules.replace_prefix("shared second").as_deref(),
|
||||
Some(" second")
|
||||
);
|
||||
}
|
||||
let global = mixed.prompt_rewrite_rules(&openai).unwrap();
|
||||
assert_eq!(
|
||||
global.replace_prefix("shared second").as_deref(),
|
||||
Some("ared second")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routing_plans_share_frozen_pricing_after_a_new_snapshot_is_published() {
|
||||
use gateway_core::{metering::PricingOverrides, runtime::RuntimeSnapshotHandle};
|
||||
|
||||
@@ -349,7 +349,7 @@ HTTP 总入口统一包裹原生路由,`dispatch_http` 复用同一路由与
|
||||
|
||||
`Load` 返回完整运行设置与 `config_revision`。`ReplaceRuntimeSettings::from(settings)` 保留该版本并构造更新命令;
|
||||
`Replace` 接收 `(MutationContext, ReplaceRuntimeSettings)`,通过已有校验、事务、审计和快照发布保存设置。
|
||||
每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool` 和 `reset_credit_on_low_weekly_quota`。
|
||||
每次写入都必须提供 `openai_request_settings`、`openai_websocket_pool`、`reset_credit_on_low_weekly_quota` 和 `prompt_rewrite_rules`。清空提示词改写规则时提交空数组,范围与顺序见[提示词改写](../../../../../docs/api.md#提示词改写)。
|
||||
版本过期返回 `ServiceError { kind: "conflict", message }`。读取结果的普通改写不会持久化,也不会回滚已经提交的事务
|
||||
|
||||
`accounts::GetResetCreditAutomation` 接收账号 ID,返回 `ResetCreditAutomationStatus`:开关、全局提前分钟数、
|
||||
|
||||
@@ -57,6 +57,15 @@ pub enum AccountErrorOperator {
|
||||
Equals,
|
||||
Contains,
|
||||
}
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct PromptRewriteRule {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub providers: BTreeSet<String>,
|
||||
pub pattern: String,
|
||||
pub replacement: String,
|
||||
}
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct OpenAiWebSocketPoolSettings {
|
||||
@@ -188,6 +197,7 @@ pub struct RuntimeSettings {
|
||||
pub usage_retention_days: u32,
|
||||
pub ops_event_retention_days: u32,
|
||||
pub audit_retention_days: u32,
|
||||
pub prompt_rewrite_rules: Vec<PromptRewriteRule>,
|
||||
pub account_error_protection: AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
@@ -230,6 +240,7 @@ pub struct ReplaceRuntimeSettings {
|
||||
pub usage_retention_days: u32,
|
||||
pub ops_event_retention_days: u32,
|
||||
pub audit_retention_days: u32,
|
||||
pub prompt_rewrite_rules: Vec<PromptRewriteRule>,
|
||||
pub account_error_protection: AccountErrorProtection,
|
||||
pub account_warmup_enabled: bool,
|
||||
pub account_warmup_cron: String,
|
||||
@@ -444,6 +455,7 @@ impl From<RuntimeSettings> for ReplaceRuntimeSettings {
|
||||
usage_retention_days: settings.usage_retention_days,
|
||||
ops_event_retention_days: settings.ops_event_retention_days,
|
||||
audit_retention_days: settings.audit_retention_days,
|
||||
prompt_rewrite_rules: settings.prompt_rewrite_rules,
|
||||
account_error_protection: settings.account_error_protection,
|
||||
account_warmup_enabled: settings.account_warmup_enabled,
|
||||
account_warmup_cron: settings.account_warmup_cron,
|
||||
|
||||
@@ -18,7 +18,7 @@ http = "1.5.0"
|
||||
httpdate = "1.0.3"
|
||||
memchr = "2.8.3"
|
||||
serde = { version = "1.0.228", features = ["derive"] }
|
||||
serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order"] }
|
||||
serde_json = { version = "1.0.150", features = ["arbitrary_precision", "preserve_order", "raw_value"] }
|
||||
thiserror = "2.0.18"
|
||||
uuid = { version = "1.23.3", features = ["v4"] }
|
||||
|
||||
|
||||
@@ -14,4 +14,4 @@ pub use response::{
|
||||
pub const GENAI_PROTOCOL: &str = "genai";
|
||||
|
||||
mod tokens;
|
||||
pub use tokens::{CountTokensError, count_tokens_request};
|
||||
pub use tokens::{CountTokensError, count_tokens_request, into_count_tokens_request};
|
||||
|
||||
@@ -8,15 +8,31 @@ use thiserror::Error;
|
||||
#[error("generateContentRequest must be a JSON object.")]
|
||||
pub struct CountTokensError;
|
||||
|
||||
fn wrapped_field(request: &Map<String, Value>) -> Option<&'static str> {
|
||||
["generateContentRequest", "generate_content_request"]
|
||||
.into_iter()
|
||||
.find(|key| request.contains_key(*key))
|
||||
}
|
||||
|
||||
/// 完整生成请求存在时,以它作为计数输入,外层 contents 不参与计数
|
||||
pub fn count_tokens_request(
|
||||
request: &Map<String, Value>,
|
||||
) -> Result<&Map<String, Value>, CountTokensError> {
|
||||
match request
|
||||
.get("generateContentRequest")
|
||||
.or_else(|| request.get("generate_content_request"))
|
||||
{
|
||||
Some(value) => value.as_object().ok_or(CountTokensError),
|
||||
match wrapped_field(request) {
|
||||
Some(key) => request[key].as_object().ok_or(CountTokensError),
|
||||
None => Ok(request),
|
||||
}
|
||||
}
|
||||
|
||||
/// 取出计数正文供上游适配,无需复制历史和工具
|
||||
pub fn into_count_tokens_request(
|
||||
mut request: Map<String, Value>,
|
||||
) -> Result<Map<String, Value>, CountTokensError> {
|
||||
match wrapped_field(&request) {
|
||||
Some(key) => match request.remove(key) {
|
||||
Some(Value::Object(body)) => Ok(body),
|
||||
_ => Err(CountTokensError),
|
||||
},
|
||||
None => Ok(request),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,3 +24,6 @@ pub mod peer;
|
||||
|
||||
/// Chat Completions 直接转换
|
||||
pub mod chat_completions;
|
||||
|
||||
/// 原生协议与 Chat 的系统指令定位及局部替换
|
||||
pub mod prompt_rewrite;
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
//! 定位生成正文的首条系统指令,同时维护已解析正文和原始 JSON
|
||||
|
||||
mod wire;
|
||||
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
type Path = &'static [&'static str];
|
||||
|
||||
/// 已定位的文本字段及替换结果
|
||||
pub struct PromptEdit {
|
||||
content: Path,
|
||||
tail: Path,
|
||||
text: String,
|
||||
}
|
||||
|
||||
/// 未命中时仅借用系统文本,不复制会话历史
|
||||
pub fn plan(
|
||||
protocol: &str,
|
||||
body: &Map<String, Value>,
|
||||
replace: impl FnOnce(&str) -> Option<String>,
|
||||
) -> Option<PromptEdit> {
|
||||
use crate::{
|
||||
anthropic::ANTHROPIC_PROTOCOL, chat_completions::CHAT_PROTOCOL, genai::GENAI_PROTOCOL,
|
||||
openai::OPENAI_PROTOCOL,
|
||||
};
|
||||
let (content, value, types): (Path, _, &[&str]) = match protocol {
|
||||
OPENAI_PROTOCOL | CHAT_PROTOCOL => {
|
||||
if let Some(value) = body.get("instructions").filter(|v| !v.is_null()) {
|
||||
(&["instructions"], value, &["text", "input_text"])
|
||||
} else {
|
||||
let path: Path = if protocol == CHAT_PROTOCOL {
|
||||
&["messages", "0", "content"]
|
||||
} else {
|
||||
&["input", "0", "content"]
|
||||
};
|
||||
let first = body.get(path[0])?.get(0)?;
|
||||
if !matches!(first.get("role")?.as_str()?, "system" | "developer")
|
||||
|| first
|
||||
.get("type")
|
||||
.is_some_and(|v| v.as_str() != Some("message"))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
(path, first.get("content")?, &["text", "input_text"])
|
||||
}
|
||||
}
|
||||
ANTHROPIC_PROTOCOL => (&["system"], body.get("system")?, &["text"]),
|
||||
GENAI_PROTOCOL => {
|
||||
let path: Path = if body.contains_key("systemInstruction") {
|
||||
&["systemInstruction", "parts", "0", "text"]
|
||||
} else {
|
||||
&["system_instruction", "parts", "0", "text"]
|
||||
};
|
||||
let value = body.get(path[0])?.get("parts")?.get(0)?.get("text")?;
|
||||
return Some(PromptEdit {
|
||||
content: path,
|
||||
tail: &[],
|
||||
text: replace(value.as_str()?)?,
|
||||
});
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let (tail, text): (Path, _) = if let Some(parts) = value.as_array() {
|
||||
let first = parts.first()?;
|
||||
if !types.contains(&first.get("type")?.as_str()?) {
|
||||
return None;
|
||||
}
|
||||
(&["0", "text"], first.get("text")?.as_str()?)
|
||||
} else {
|
||||
(&[], value.as_str()?)
|
||||
};
|
||||
Some(PromptEdit {
|
||||
content,
|
||||
tail,
|
||||
text: replace(text)?,
|
||||
})
|
||||
}
|
||||
|
||||
impl PromptEdit {
|
||||
/// 将编辑应用于定位时使用的正文
|
||||
pub fn apply(self, body: &mut Map<String, Value>) {
|
||||
let Some(mut field) = body.get_mut(self.content[0]) else {
|
||||
return;
|
||||
};
|
||||
for &key in self.content[1..].iter().chain(self.tail) {
|
||||
let Some(child) = (if key == "0" {
|
||||
field.get_mut(0)
|
||||
} else {
|
||||
field.get_mut(key)
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
field = child;
|
||||
}
|
||||
*field = Value::String(self.text);
|
||||
}
|
||||
|
||||
/// 只编码目标字符串,保留其他字段的原始字节
|
||||
pub fn wire(&self, body: &[u8]) -> Option<Vec<u8>> {
|
||||
let mut raw = serde_json::from_slice(body).ok()?;
|
||||
for &key in self.content.iter().chain(self.tail) {
|
||||
raw = if key == "0" {
|
||||
wire::first(raw)?
|
||||
} else {
|
||||
wire::field(raw, key)?
|
||||
};
|
||||
}
|
||||
let start = raw.get().as_ptr() as usize - body.as_ptr() as usize;
|
||||
let mut out = Vec::with_capacity(body.len() - raw.get().len() + self.text.len() + 2);
|
||||
out.extend_from_slice(&body[..start]);
|
||||
serde_json::to_writer(&mut out, &self.text).ok()?;
|
||||
out.extend_from_slice(&body[start + raw.get().len()..]);
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
//! 只借用路径命中的 JSON 字段,跳过无关值,不展开工具或历史
|
||||
|
||||
use serde::{
|
||||
Deserialize, Deserializer,
|
||||
de::{IgnoredAny, MapAccess, Visitor},
|
||||
};
|
||||
use serde_json::value::RawValue;
|
||||
use std::{borrow::Cow, fmt};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Text<'a>(#[serde(borrow)] Cow<'a, str>);
|
||||
|
||||
pub(super) fn first(raw: &RawValue) -> Option<&RawValue> {
|
||||
let array = raw.get().strip_prefix('[')?;
|
||||
serde_json::Deserializer::from_str(array)
|
||||
.into_iter::<&RawValue>()
|
||||
.next()?
|
||||
.ok()
|
||||
}
|
||||
|
||||
pub(super) fn field<'a>(raw: &'a RawValue, name: &str) -> Option<&'a RawValue> {
|
||||
struct Field<'a>(&'a str);
|
||||
impl<'de> Visitor<'de> for Field<'_> {
|
||||
type Value = Option<&'de RawValue>;
|
||||
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str("a JSON object")
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut found = None;
|
||||
while let Some(key) = map.next_key::<Text<'_>>()? {
|
||||
if key.0 == self.0 {
|
||||
found = Some(map.next_value()?);
|
||||
} else {
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
}
|
||||
}
|
||||
serde_json::Deserializer::from_str(raw.get())
|
||||
.deserialize_map(Field(name))
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
@@ -32,9 +32,7 @@ pub fn token_count_observation(
|
||||
context: &Map<String, Value>,
|
||||
) -> RequestObservation {
|
||||
let body = if protocol == GENAI_PROTOCOL {
|
||||
body.get("generateContentRequest")
|
||||
.and_then(Value::as_object)
|
||||
.unwrap_or(body)
|
||||
genai::count_tokens_request(body).unwrap_or(body)
|
||||
} else {
|
||||
body
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ mod anthropic;
|
||||
mod genai;
|
||||
mod http;
|
||||
mod openai;
|
||||
mod prompt_rewrite;
|
||||
mod request;
|
||||
|
||||
mod chat_completions;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//! 各协议的系统指令位置、首条命中与其余 wire 字节保留
|
||||
|
||||
use gateway_protocol::prompt_rewrite::plan;
|
||||
mod wire;
|
||||
|
||||
#[test]
|
||||
fn unmatched_quoted_and_unknown_content_passes_through() {
|
||||
for (protocol, body) in [
|
||||
(
|
||||
"openai",
|
||||
r#"{"instructions":"quote: abc","input":[{"role":"system","content":"abc"}]}"#,
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
r#"{"input":[{"type":"function_call","role":"system","content":"abc"}]}"#,
|
||||
),
|
||||
(
|
||||
"chat_completions",
|
||||
r#"{"messages":[{"role":"user","content":"abc"},{"role":"developer","content":"abc"}]}"#,
|
||||
),
|
||||
(
|
||||
"genai",
|
||||
r#"{"contents":[{"role":"user","parts":[{"text":"abc"}]}]}"#,
|
||||
),
|
||||
(
|
||||
"genai",
|
||||
r#"{"systemInstruction":{"parts":[{"text":"untouched"}]},"generateContentRequest":{"systemInstruction":{"parts":[{"text":"abc"}]}}}"#,
|
||||
),
|
||||
(
|
||||
"anthropic",
|
||||
r#"{"system":[{"type":"custom","text":"abc"}]}"#,
|
||||
),
|
||||
("other", r#"{"instructions":"abc"}"#),
|
||||
] {
|
||||
let body = serde_json::from_str(body).unwrap();
|
||||
assert!(
|
||||
plan(protocol, &body, |text| text
|
||||
.strip_prefix("abc")
|
||||
.map(str::to_owned))
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! 各协议的系统指令位置、首条命中与其余 wire 字节保留
|
||||
|
||||
use gateway_protocol::prompt_rewrite::plan;
|
||||
use serde_json::Map;
|
||||
|
||||
#[test]
|
||||
fn rewrites_only_the_authoritative_text_and_preserves_wire_bytes() {
|
||||
for (protocol, instruction) in [
|
||||
(
|
||||
"chat_completions",
|
||||
r#""messages":[{"role":"system","content":"First\n规则"},{"role":"user","content":"First\n规则"}]"#,
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
r#""instructions":"First\n规则","input":[{"role":"developer","content":"First\n规则"}]"#,
|
||||
),
|
||||
(
|
||||
"openai",
|
||||
r#""input":[{"type":"message","role":"developer","content":[{"type":"input_text","text":"First\n规则","extra":7}]}]"#,
|
||||
),
|
||||
("anthropic", r#""system":"First\n规则""#),
|
||||
(
|
||||
"anthropic",
|
||||
r#""system":[{"type":"text","text":"First\n规则","cache_control":{"type":"ephemeral"}},{"type":"text","text":"First\n规则"}]"#,
|
||||
),
|
||||
(
|
||||
"genai",
|
||||
r#""systemInstruction":{"parts":[{"text":"First\n规则"},{"text":"First\n规则"}]}"#,
|
||||
),
|
||||
(
|
||||
"genai",
|
||||
r#""system_instruction":{"parts":[{"text":"First\n规则"}]}"#,
|
||||
),
|
||||
] {
|
||||
let body = format!(
|
||||
r#"{{"unknown":1e+08, {instruction}, "unknown":12345678901234567890123456789}}"#
|
||||
);
|
||||
let parsed: Map<_, _> = serde_json::from_str(&body).unwrap();
|
||||
let edit = plan(protocol, &parsed, |text| {
|
||||
text.strip_prefix("First\n")
|
||||
.map(|suffix| format!("Changed\n{suffix}"))
|
||||
})
|
||||
.unwrap();
|
||||
let wire = edit.wire(body.as_bytes()).unwrap();
|
||||
let mut edited = parsed;
|
||||
edit.apply(&mut edited);
|
||||
assert_eq!(edited, serde_json::from_slice::<Map<_, _>>(&wire).unwrap());
|
||||
assert_eq!(wire, body.replacen("First", "Changed", 1).as_bytes());
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,10 @@ fn token_count_observation_uses_the_nested_generation_request() {
|
||||
serde_json::json!({"generationConfig":{"thinkingConfig":{"thinkingLevel":"HIGH"}},"generateContentRequest":{"contents":[]}}),
|
||||
None,
|
||||
),
|
||||
(
|
||||
serde_json::json!({"generate_content_request":{"generation_config":{"thinking_config":{"thinking_level":"HIGH"}}}}),
|
||||
Some("high"),
|
||||
),
|
||||
] {
|
||||
let observation = gateway_protocol::request::token_count_observation(
|
||||
"genai",
|
||||
|
||||
@@ -120,6 +120,7 @@ impl SettingsStore for AdminSettingsStoreAdapter {
|
||||
"min_codex_desktop_version".to_owned(),
|
||||
"min_codex_cli_version".to_owned(),
|
||||
"retention".to_owned(),
|
||||
"prompt_rewrite_rules_json".to_owned(),
|
||||
"account_error_protection".to_owned(),
|
||||
],
|
||||
),
|
||||
|
||||
@@ -156,7 +156,7 @@ pub(crate) async fn load_runtime_settings_from_pool(pool: &PgPool) -> StoreResul
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
account_error_protection_json, account_error_protection_revision,
|
||||
prompt_rewrite_rules_json, account_error_protection_json, account_error_protection_revision,
|
||||
account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota
|
||||
from runtime_settings where id = 1",
|
||||
)
|
||||
@@ -359,7 +359,7 @@ pub(crate) async fn load_runtime_settings_in_transaction(
|
||||
rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, usage_retention_days, ops_event_retention_days,
|
||||
audit_retention_days, min_codex_desktop_version,
|
||||
min_codex_cli_version, updated_at, responses_max_decompressed_body_bytes, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours,
|
||||
account_error_protection_json, account_error_protection_revision,
|
||||
prompt_rewrite_rules_json, account_error_protection_json, account_error_protection_revision,
|
||||
account_warmup_enabled, account_warmup_cron, account_warmup_model, reset_credit_lead_minutes, reset_credit_max_weekly_remaining_percent, reset_credit_on_low_weekly_quota
|
||||
from runtime_settings where id = 1",
|
||||
)
|
||||
@@ -446,6 +446,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
quota_reset_window_weights_json = $35,
|
||||
openai_request_settings_json = $36,
|
||||
openai_websocket_pool_json = $37,
|
||||
prompt_rewrite_rules_json = $38,
|
||||
updated_at = now()
|
||||
where id = 1
|
||||
returning config_revision",
|
||||
@@ -495,6 +496,7 @@ pub(crate) async fn update_runtime_settings_in_transaction(
|
||||
.bind(sqlx::types::Json(update.values.quota_reset_window_weights))
|
||||
.bind(sqlx::types::Json(&update.values.openai_request_settings))
|
||||
.bind(sqlx::types::Json(&update.values.openai_websocket_pool))
|
||||
.bind(sqlx::types::Json(&update.values.prompt_rewrite_rules))
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("update runtime settings in transaction", source))?
|
||||
@@ -596,6 +598,8 @@ struct RuntimeSettingsRow {
|
||||
session_affinity_ttl_hours: i64,
|
||||
responses_max_decompressed_body_bytes: i64,
|
||||
account_error_protection_revision: i64,
|
||||
prompt_rewrite_rules_json:
|
||||
sqlx::types::Json<Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>>,
|
||||
account_error_protection_json: sqlx::types::Json<gateway_core::account::AccountErrorProtection>,
|
||||
account_warmup_enabled: bool,
|
||||
account_warmup_cron: String,
|
||||
@@ -667,6 +671,7 @@ fn runtime_settings_from_row(row: RuntimeSettingsRow) -> StoreResult<RuntimeSett
|
||||
responses_max_decompressed_body_bytes: to_u64(
|
||||
row.responses_max_decompressed_body_bytes,
|
||||
)?,
|
||||
prompt_rewrite_rules: row.prompt_rewrite_rules_json.0,
|
||||
account_error_protection: row.account_error_protection_json.0,
|
||||
account_warmup_enabled: row.account_warmup_enabled,
|
||||
account_warmup_cron: row.account_warmup_cron,
|
||||
|
||||
@@ -223,6 +223,8 @@ struct SnapshotSettingsRow {
|
||||
pricing_overrides_json: sqlx::types::Json<gateway_core::metering::PricingOverrides>,
|
||||
config_revision: i64,
|
||||
account_error_protection_revision: i64,
|
||||
prompt_rewrite_rules_json:
|
||||
sqlx::types::Json<Vec<gateway_core::settings::prompt_rewrite::PromptRewriteRule>>,
|
||||
account_error_protection_json: sqlx::types::Json<gateway_core::account::AccountErrorProtection>,
|
||||
max_concurrent_per_account: i64,
|
||||
smart_scheduling_json: sqlx::types::Json<gateway_core::account::SmartSchedulingConfig>,
|
||||
@@ -257,7 +259,7 @@ async fn load_settings(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
) -> StoreResult<(Revision, SettingsValues)> {
|
||||
let row = sqlx::query_as::<_, SnapshotSettingsRow>(
|
||||
"select config_revision, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1",
|
||||
"select config_revision, prompt_rewrite_rules_json, account_error_protection_revision, account_error_protection_json, max_concurrent_per_account, rotation_strategy, smart_scheduling_json, quota_reset_window_weights_json, model_mappings_json, min_codex_desktop_version, min_codex_cli_version, max_waiting_per_key, max_waiting_per_account, key_queue_timeout_seconds, account_queue_timeout_seconds, switch_account_on_queue_failure, max_retry_after_seconds, openai_guardian_reserved_concurrency, openai_request_settings_json, openai_websocket_pool_json, account_affinity, max_account_rotations, session_affinity_ttl_hours, request_location_json, request_location_enabled, codex_privacy_policy_json, responses_max_decompressed_body_bytes, provider_request_profiles_json, pricing_overrides_json, pricing_synced_json from runtime_settings where id = 1",
|
||||
)
|
||||
.fetch_optional(&mut **transaction)
|
||||
.await
|
||||
@@ -306,6 +308,7 @@ async fn load_settings(
|
||||
})
|
||||
.with_request_location(row.request_location_json.0, row.request_location_enabled)
|
||||
.with_codex_privacy_policy(row.codex_privacy_policy_json.0)
|
||||
.with_prompt_rewrite_rules(row.prompt_rewrite_rules_json.0)
|
||||
.with_account_error_protection(row.account_error_protection_json.0)
|
||||
.with_account_error_protection_revision(to_u64(row.account_error_protection_revision)?)
|
||||
.with_concurrency_queues(
|
||||
|
||||
@@ -48,6 +48,7 @@ pub(super) fn settings_with_margin(refresh_margin_seconds: u64) -> RuntimeSettin
|
||||
usage_retention_days: 31,
|
||||
ops_event_retention_days: 30,
|
||||
audit_retention_days: 90,
|
||||
prompt_rewrite_rules: Vec::new(),
|
||||
account_error_protection: enabled_protection(),
|
||||
account_warmup_enabled: false,
|
||||
account_warmup_cron: "0 8 * * *".to_owned(),
|
||||
@@ -65,6 +66,38 @@ fn runtime_settings_keep_account_rotation_global() {
|
||||
assert!(settings.validate().is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn prompt_rewrite_order_and_scope_round_trip_into_the_runtime_snapshot() {
|
||||
use gateway_store::postgres::{PgRuntimeSnapshotRepository, RuntimeSnapshotRepository};
|
||||
let Some(database) = TestDatabase::create("prompt_rewrite").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgRuntimeSettingsRepository::new(database.pool.clone());
|
||||
let before = repository.load_runtime_settings().await.unwrap();
|
||||
assert!(before.values.prompt_rewrite_rules.is_empty());
|
||||
let expected = serde_json::json!([
|
||||
{"name":"客户端身份","providers":["antigravity","xai"],"pattern":"example","replacement":"first"},
|
||||
{"name":"全局身份","providers":[],"pattern":"example","replacement":"second"}
|
||||
]);
|
||||
let mut update = settings_with_margin(300);
|
||||
update.values.prompt_rewrite_rules = serde_json::from_value(expected.clone()).unwrap();
|
||||
repository.update_runtime_settings(update).await.unwrap();
|
||||
let after = repository.load_runtime_settings().await.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(after.values.prompt_rewrite_rules).unwrap(),
|
||||
expected
|
||||
);
|
||||
let snapshot = PgRuntimeSnapshotRepository::new(database.pool.clone())
|
||||
.load_runtime_snapshot()
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(snapshot.settings).unwrap()["prompt_rewrite_rules"],
|
||||
expected
|
||||
);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn privacy_policy_defaults_off_and_round_trips_in_snapshot() {
|
||||
use gateway_core::settings::privacy::*;
|
||||
|
||||
@@ -2,16 +2,17 @@
|
||||
|
||||
use crate::transport::{sent, unsent};
|
||||
use gateway_core::{
|
||||
engine::provider::NativeResponseTranslator,
|
||||
engine::{AttemptContext, provider::NativeResponseTranslator},
|
||||
error::{ProviderError, ProviderErrorKind},
|
||||
event::ProtocolWireEvent,
|
||||
operation::Operation,
|
||||
};
|
||||
use gateway_protocol::genai::{GENAI_PROTOCOL, count_tokens_request};
|
||||
use gateway_protocol::genai::{GENAI_PROTOCOL, into_count_tokens_request};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(super) fn prepare(
|
||||
operation: Operation,
|
||||
context: &AttemptContext,
|
||||
) -> Result<(Operation, Option<Translator>), ProviderError> {
|
||||
let Operation::CountTokens(request) = &operation else {
|
||||
return Err(unsent(ProviderErrorKind::Unsupported));
|
||||
@@ -22,9 +23,10 @@ pub(super) fn prepare(
|
||||
}
|
||||
let body: Map<String, Value> = serde_json::from_slice(request.payload().body())
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
let body = count_tokens_request(&body)
|
||||
let mut body = into_count_tokens_request(body)
|
||||
.map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))?;
|
||||
let bytes = serde_json::to_vec(body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
context.rewrite_count_prompt(GENAI_PROTOCOL, &mut body);
|
||||
let bytes = serde_json::to_vec(&body).map_err(|_| unsent(ProviderErrorKind::InvalidRequest))?;
|
||||
let translated = source == "token-count";
|
||||
let operation = if translated {
|
||||
operation.translate_protocol_wire(GENAI_PROTOCOL, bytes.into())
|
||||
|
||||
@@ -94,7 +94,7 @@ impl AntigravityProvider {
|
||||
return Err(ProviderError::invalid_request("Middleware changed the required web search after model selection."));
|
||||
}
|
||||
let (operation, translator, count_translator) = if matches!(operation, Operation::CountTokens(_)) {
|
||||
let (operation, translator) = super::count::prepare(operation)?;
|
||||
let (operation, translator) = super::count::prepare(operation, &terminal_context)?;
|
||||
(operation, None, translator)
|
||||
} else {
|
||||
let (operation, translator) = super::chat::prepare(operation, &terminal_context, affinity.as_ref())?;
|
||||
@@ -114,6 +114,7 @@ impl AntigravityProvider {
|
||||
_ => return Err(unsent(Kind::Unsupported)),
|
||||
};
|
||||
let body = operation.middleware_body().map_err(|_| unsent(Kind::InvalidRequest))?;
|
||||
let translated_chat = translator.is_some();
|
||||
let events = async_stream::try_stream! {
|
||||
if cancellation.is_cancelled() {
|
||||
Err(unsent(Kind::Cancelled))?;
|
||||
@@ -138,7 +139,13 @@ impl AntigravityProvider {
|
||||
// 固定探测使用该账号实际授权的项目,包括尚无公开目录的停用账号
|
||||
Project::Discover => resource.account_info(token).await?.project,
|
||||
};
|
||||
let mode = if search { crate::transport::GenerateMode::WebSearch } else { crate::transport::GenerateMode::from(stream) };
|
||||
let mode = if search {
|
||||
crate::transport::GenerateMode::WebSearch
|
||||
} else if translated_chat {
|
||||
crate::transport::GenerateMode::Chat { stream }
|
||||
} else {
|
||||
crate::transport::GenerateMode::from(stream)
|
||||
};
|
||||
resource.generate(&project, model.as_str(), token, &body, mode, &headers).await
|
||||
} => response,
|
||||
};
|
||||
|
||||
@@ -100,6 +100,7 @@ pub(crate) enum GenerateMode {
|
||||
Json,
|
||||
Stream,
|
||||
WebSearch,
|
||||
Chat { stream: bool },
|
||||
}
|
||||
|
||||
impl From<bool> for GenerateMode {
|
||||
@@ -229,13 +230,16 @@ impl CloudCodeClient {
|
||||
enabled_credit_types: Option<[&'static str; 1]>,
|
||||
request: &'a RawValue,
|
||||
}
|
||||
let instruction = if mode == GenerateMode::WebSearch {
|
||||
*SEARCH_INSTRUCTION
|
||||
} else {
|
||||
&self.system_instruction
|
||||
let instruction = match mode {
|
||||
GenerateMode::WebSearch => Some(*SEARCH_INSTRUCTION),
|
||||
GenerateMode::Chat { .. } => None,
|
||||
GenerateMode::Json | GenerateMode::Stream => Some(self.system_instruction.as_ref()),
|
||||
};
|
||||
let request = super::request::request_body(body, instruction, false)?;
|
||||
let (send, media) = if mode == GenerateMode::Stream {
|
||||
let (send, media) = if matches!(
|
||||
mode,
|
||||
GenerateMode::Stream | GenerateMode::Chat { stream: true }
|
||||
) {
|
||||
(
|
||||
self.post("streamGenerateContent", token)
|
||||
.query(&[("alt", "sse")]),
|
||||
@@ -277,7 +281,7 @@ impl CloudCodeClient {
|
||||
headers: &[MiddlewareHeader],
|
||||
) -> Result<Response, ProviderError> {
|
||||
// Desktop 的计数封套只接受 Vertex CountTokensRequest,没有项目和生成控制字段
|
||||
let request = super::request::request_body(body, &self.system_instruction, true)?;
|
||||
let request = super::request::request_body(body, Some(&self.system_instruction), true)?;
|
||||
#[derive(Serialize)]
|
||||
struct Envelope<'a> {
|
||||
request: &'a RawValue,
|
||||
|
||||
@@ -11,16 +11,19 @@ use gateway_core::error::{ProviderError, ProviderErrorKind};
|
||||
|
||||
pub(super) fn request_body(
|
||||
body: &[u8],
|
||||
instruction: &RawValue,
|
||||
instruction: Option<&RawValue>,
|
||||
count: bool,
|
||||
) -> Result<Box<RawValue>, ProviderError> {
|
||||
let rewrite = || {
|
||||
let raw: &RawValue = serde_json::from_slice(body)?;
|
||||
let instruction = prepend_system_prompt(raw, instruction)?;
|
||||
let instruction = instruction
|
||||
.map(|prompt| prepend_system_prompt(raw, prompt))
|
||||
.transpose()?;
|
||||
edit_object(
|
||||
raw,
|
||||
|name, value| {
|
||||
if matches!(name, "systemInstruction" | "system_instruction")
|
||||
if (instruction.is_some()
|
||||
&& matches!(name, "systemInstruction" | "system_instruction"))
|
||||
|| (count
|
||||
&& matches!(
|
||||
name,
|
||||
@@ -60,7 +63,9 @@ pub(super) fn request_body(
|
||||
}
|
||||
Ok(Edit::Keep)
|
||||
},
|
||||
Some(("systemInstruction", &instruction)),
|
||||
instruction
|
||||
.as_deref()
|
||||
.map(|value| ("systemInstruction", value)),
|
||||
)
|
||||
};
|
||||
rewrite().map_err(|error| unsent(ProviderErrorKind::InvalidRequest).with_source(error))
|
||||
|
||||
@@ -717,13 +717,28 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
ProtocolPayload::json_object("chat_completions", body.as_object().unwrap().clone())
|
||||
.unwrap(),
|
||||
));
|
||||
let mut profile = crate::profile::ClientProfile::from_frozen(&frozen_profile()).unwrap();
|
||||
profile.system_prompt = "Frozen AGY prompt".into();
|
||||
let selection = Selection {
|
||||
system_prompt: Some("Frozen AGY prompt".into()),
|
||||
..Default::default()
|
||||
};
|
||||
let profile = fixture
|
||||
.provider
|
||||
.resolve_request_profile(&selection.configuration())
|
||||
.unwrap();
|
||||
let request_context = RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_chat").unwrap(),
|
||||
ClientApiKeyId::new("key_fixture").unwrap(),
|
||||
)
|
||||
.with_request_profile(Some(profile.frozen()))
|
||||
.with_request_profile(Some(profile))
|
||||
.with_prompt_rewrite_rules(if streaming {
|
||||
gateway_core::settings::prompt_rewrite::CompiledPromptRewrite::new(
|
||||
serde_json::from_value(json!([{"pattern":"Preserve","replacement":"Apply"}]))
|
||||
.unwrap(),
|
||||
)
|
||||
.for_provider(&ProviderKind::new("antigravity").unwrap())
|
||||
} else {
|
||||
None
|
||||
})
|
||||
.with_middleware(
|
||||
None,
|
||||
Default::default(),
|
||||
@@ -786,12 +801,8 @@ async fn chat_direct_genai_keeps_json_sse_usage_and_releases_the_native_lease()
|
||||
let body: serde_json::Value = serde_json::from_slice(&sent.last().unwrap().body).unwrap();
|
||||
assert!(body["request"].get("input").is_none());
|
||||
assert_eq!(
|
||||
body["request"]["systemInstruction"]["parts"][0]["text"],
|
||||
"Frozen AGY prompt"
|
||||
);
|
||||
assert_eq!(
|
||||
body["request"]["systemInstruction"]["parts"][1]["text"],
|
||||
"Preserve the caller's project rules."
|
||||
body["request"]["systemInstruction"]["parts"],
|
||||
json!([{"text": if streaming { "Apply the caller's project rules." } else { "Preserve the caller's project rules." }}])
|
||||
);
|
||||
assert_eq!(body["request"]["generationConfig"]["maxOutputTokens"], 100);
|
||||
assert_eq!(
|
||||
|
||||
@@ -45,6 +45,19 @@ async fn released(fixture: &Fixture) {
|
||||
|
||||
#[tokio::test]
|
||||
async fn native_and_provider_count_share_identity_and_never_generate_usage() {
|
||||
use gateway_core::{
|
||||
engine::{ModelRequestId, RequestAttemptContext},
|
||||
identity::ProviderKind,
|
||||
policy::ClientApiKeyId,
|
||||
settings::prompt_rewrite::CompiledPromptRewrite,
|
||||
};
|
||||
let rules = CompiledPromptRewrite::new(
|
||||
serde_json::from_value(json!([
|
||||
{"pattern":"client", "replacement":"client updated"}
|
||||
]))
|
||||
.unwrap(),
|
||||
)
|
||||
.for_provider(&ProviderKind::new("antigravity").unwrap());
|
||||
for (protocol, body, expected) in [
|
||||
(
|
||||
"genai",
|
||||
@@ -73,7 +86,15 @@ async fn native_and_provider_count_share_identity_and_never_generate_usage() {
|
||||
.clone()
|
||||
.execute(
|
||||
counted(protocol, body),
|
||||
context(profile(), CancellationToken::new()),
|
||||
crate::support::context_with_request(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_count").unwrap(),
|
||||
ClientApiKeyId::new("key_fixture").unwrap(),
|
||||
)
|
||||
.with_request_profile(Some(profile()))
|
||||
.with_prompt_rewrite_rules(rules.clone()),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -116,7 +137,7 @@ async fn native_and_provider_count_share_identity_and_never_generate_usage() {
|
||||
);
|
||||
assert_eq!(
|
||||
sent["request"]["systemInstruction"]["parts"][1]["text"],
|
||||
"client identity"
|
||||
"client updated identity"
|
||||
);
|
||||
assert_eq!(sent["request"]["contents"][0]["parts"][0]["text"], "hello");
|
||||
assert_eq!(
|
||||
|
||||
@@ -56,6 +56,7 @@ impl CodexProvider {
|
||||
let mut body: Map<String, Value> =
|
||||
serde_json::from_slice(count.payload().body())
|
||||
.map_err(|_| invalid_request())?;
|
||||
terminal_context.rewrite_count_prompt(ANTHROPIC_PROTOCOL, &mut body);
|
||||
// 通用 Provider 计数入口的模型来自路径,正文仍使用 Messages 输入合同
|
||||
body.insert("model".to_owned(), Value::String(model.as_str().to_owned()));
|
||||
gateway_protocol::anthropic::validate_count_request(&body)
|
||||
|
||||
@@ -391,21 +391,38 @@ async fn chat_service_tiers_follow_the_selected_responses_upstream() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn custom_messages_count_locally_without_billable_usage() {
|
||||
for (target, source) in [
|
||||
(ApiKeyProtocol::Messages, "anthropic"),
|
||||
(ApiKeyProtocol::Messages, "token-count"),
|
||||
let rules = gateway_core::settings::prompt_rewrite::CompiledPromptRewrite::new(
|
||||
serde_json::from_value(json!([{"pattern":"repeated prefix", "replacement":""}])).unwrap(),
|
||||
)
|
||||
.for_provider(&ProviderKind::new("openai").unwrap());
|
||||
let mut baseline = None;
|
||||
for (source, configured, system) in [
|
||||
("anthropic", None, "rule"),
|
||||
("anthropic", rules.clone(), "repeated prefixrule"),
|
||||
("token-count", rules, "repeated prefixrule"),
|
||||
] {
|
||||
let server = MockServer::start().await;
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
seed(&store, &server, target).await;
|
||||
let body = Bytes::from_static(br#"{"messages":[{"role":"user","content":"hello world"}]}"#);
|
||||
seed(&store, &server, ApiKeyProtocol::Messages).await;
|
||||
let body = serde_json::to_vec(
|
||||
&json!({"system":system,"messages":[{"role":"user","content":"hello world"}]}),
|
||||
)
|
||||
.unwrap()
|
||||
.into();
|
||||
let operation = Operation::CountTokens(TokenCountRequest::from_raw_json(
|
||||
RawJsonPayload::new(source, body).unwrap(),
|
||||
));
|
||||
let mut stream = provider(&store)
|
||||
.execute(
|
||||
planned_request("openai", operation),
|
||||
context("req_messages_count", CancellationToken::new()),
|
||||
context_for_request(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_messages_count").unwrap(),
|
||||
ClientApiKeyId::new("key_openai_contract").unwrap(),
|
||||
)
|
||||
.with_prompt_rewrite_rules(configured),
|
||||
CancellationToken::new(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -422,7 +439,9 @@ async fn custom_messages_count_locally_without_billable_usage() {
|
||||
count = body.get("input_tokens").and_then(Value::as_u64);
|
||||
}
|
||||
}
|
||||
assert!(count.is_some_and(|count| count > 0));
|
||||
let count = count.unwrap();
|
||||
assert!(count > 0);
|
||||
assert_eq!(count, *baseline.get_or_insert(count));
|
||||
assert!(server.received_requests().await.unwrap().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2864,7 +2864,14 @@ async fn configured_request_profile_reaches_inference_headers() {
|
||||
ModelRequestId::new("req_profile").unwrap(),
|
||||
ClientApiKeyId::new("key_profile").unwrap(),
|
||||
)
|
||||
.with_request_profile(Some(resolved)),
|
||||
.with_request_profile(Some(resolved))
|
||||
.with_prompt_rewrite_rules(
|
||||
gateway_core::settings::prompt_rewrite::CompiledPromptRewrite::new(
|
||||
serde_json::from_value(json!([{"pattern":"Old", "replacement":"Updated"}]))
|
||||
.unwrap(),
|
||||
)
|
||||
.for_provider(&ProviderKind::new("xai").unwrap()),
|
||||
),
|
||||
NonZeroU32::new(1).unwrap(),
|
||||
SystemTime::now() + Duration::from_secs(30),
|
||||
selection_policy(),
|
||||
@@ -2872,14 +2879,24 @@ async fn configured_request_profile_reaches_inference_headers() {
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let payload = ProtocolPayload::from_json_bytes(
|
||||
"openai",
|
||||
bytes::Bytes::from_static(
|
||||
br#"{"model":"client-model","instructions":"Old rule","input":"hello"}"#,
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(payload));
|
||||
let events = provider
|
||||
.execute(provider_request("xai"), context)
|
||||
.execute(provider_request_with_operation("xai", operation), context)
|
||||
.await
|
||||
.unwrap()
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
assert!(events.iter().all(Result::is_ok));
|
||||
let requests = transport.requests.lock().unwrap();
|
||||
let sent: Value = serde_json::from_slice(requests[0].body()).unwrap();
|
||||
assert_eq!(sent["instructions"], "Updated rule");
|
||||
let headers = requests[0].headers();
|
||||
let header = |name| {
|
||||
std::str::from_utf8(
|
||||
|
||||
@@ -47,3 +47,4 @@ e115a71b80faa08be4cf4f8747eec01e7b855ad3d8aa9622ca70b57300847b54 0046_account_a
|
||||
98070edbfc34e71e403810fbb8db3bd18e7e241caeda2e952af022cd98ecdb6b 0047_request_plan_display.sql
|
||||
709df48f4dd067332177fb8bee15c5e75d4666a0dc9c7a8e48f8480a01a99908 0048_openai_runtime_settings.sql
|
||||
44a24ba1bab7630881b4eeac66806231d3a7040dd72a99b0475e1a0f20cfc540 0049_client_key_validity_and_proxy_test_targets.sql
|
||||
c62495a0aff26b149381370fe1eea656091ab8d9d7d55aee27be4f56d5885fd3 0050_prompt_rewrite_rules.sql
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
ALTER TABLE runtime_settings
|
||||
ADD COLUMN prompt_rewrite_rules_json jsonb NOT NULL DEFAULT '[]'::jsonb
|
||||
CHECK (jsonb_typeof(prompt_rewrite_rules_json) = 'array');
|
||||
+11
-2
@@ -270,7 +270,7 @@ AGY 在 API Key 模式下使用 `gemini-3.1-flash-lite-preview` 发起同样的
|
||||
|
||||
CPR 在 AGY 的原生与转换入口透传未被过滤的 HTTP 扩展头,保留同名多值的原始字节。下游鉴权、Cookie、账号身份、客户端画像和 HTTP 传输头不透传;认证、项目和 UA 由所选 OAuth 账号与冻结画像生成。`X-Goog-Api-Client` 与 Gateway 的 `X-Goog-Ext-525006001-Bin` 不进入 Cloud Code 请求。`X-Goog-User-Project` 属于调用方指定的计费项目,不能覆盖所选账号的项目,见 [Google 系统参数](https://docs.cloud.google.com/apis/docs/system-parameters)
|
||||
|
||||
Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文在 `systemInstruction.parts` 前添加配置的提示词,保留客户端原有 parts 及系统指令的其他字段,并移除 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。系统指令也接受 `system_instruction`,两者同时提供时以 `systemInstruction` 为准,出站统一使用驼峰名称。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建
|
||||
Cloud Code 生成封套使用 `userAgent: "antigravity"` 与 `requestType: "agent"`,独立搜索使用 `web_search`。原生正文在 `systemInstruction.parts` 前添加画像提示词。普通 Chat 转换只发送调用方系统指令及其配置的改写结果。网关移除 `labels` 中 Gateway 添加的 `client`、`goog-originating-logical-product-id`、`goog-originating-service-id`。系统指令也接受 `system_instruction`,两者同时提供时以 `systemInstruction` 为准,出站统一使用驼峰名称。其余字段保留原始 JSON 表达与顺序,不经 Chat 或 canonical 请求重建
|
||||
|
||||
同账号及归属未知时保留追踪头;会话绑定或本次执行的已有账号归属明确发生切换时,CPR 清理入站或中间件带入的 `traceparent`、`tracestate`、`sentry-trace`、`baggage`。该清理作用于本次出站请求,不修改工具结果、思考签名或业务正文
|
||||
|
||||
@@ -1820,7 +1820,7 @@ OAuth start 使用:
|
||||
|
||||
Antigravity 的全局客户端设置保存在 `providerRequestProfiles.antigravity`,Key 可用 `providerRequestProfileOverrides.antigravity` 覆盖。配置使用 `client`(`desktop` 或 `cli`)、`platform`(`macos`、`linux` 或 `windows`)、`versionMode`、`clientVersion` 和 `arch`。`arch: null` 使用预设架构:macOS 为 `arm64`,Linux 与 Windows 为 `amd64`;也可显式选择 `arm64` 或 `amd64`
|
||||
|
||||
`systemPrompt` 可在 AGY 设置中编辑,省略、`null` 或空白值使用内置默认,最长 16 KiB。默认取自已核对的 AGY CLI 1.5.15 身份模板,不包含客户端专属工具和工作区模板;选项接口返回 `defaultSystemPrompt` 与 `systemPromptSource`,客户端版本轮询不会改写它。提示词随请求画像一起冻结,原生和转换入口均将它放在客户端系统指令之前。客户端的全局规则、项目规则、工具说明及其他系统指令保持原样;未提供客户端系统指令时只使用配置提示词
|
||||
AGY 请求画像的 `systemPrompt` 最长 16 KiB,省略、`null` 或空白值使用内置默认。选项接口通过 `defaultSystemPrompt` 和 `systemPromptSource` 返回 AGY CLI 1.5.15 身份模板及其来源。原生生成与计数在客户端系统指令之前加入画像提示词。普通 Chat 转发只应用[提示词改写规则](#提示词改写)
|
||||
|
||||
自动版本示例:
|
||||
|
||||
@@ -2344,6 +2344,7 @@ HTTP 返回 `429`,`error.code` 为 `key_daily_budget_exceeded` 或 `key_weekly
|
||||
| 用途 | 字段 |
|
||||
| --- | --- |
|
||||
| 并发控制版本 | `configRevision` |
|
||||
| [提示词改写](#提示词改写) | `promptRewriteRules` |
|
||||
| [客户端身份](#provider-客户端身份) | `providerRequestProfiles` |
|
||||
| [请求位置](#请求位置) | `requestLocationEnabled`、`requestLocation` |
|
||||
| [OpenAI 请求设置](#openai-请求设置) | `openaiRequestSettings` |
|
||||
@@ -2716,6 +2717,14 @@ models.dev 同步只导入可表示为当前文本 Token 计价的 OpenAI/xAI
|
||||
及所有人工单价与倍率保持不变。选中的已同步模型若不再出现在来源价目中,则移除其来源层,恢复内置价格;
|
||||
没有内置价目的模型变为未配置
|
||||
|
||||
### 提示词改写
|
||||
|
||||
更新通用设置时须提交有序数组 `promptRewriteRules`,初始值为 `[]`。每条包含适用上游 `providers`、非空字面前缀 `pattern` 和替换文本 `replacement`。`name` 为必填规则名称,用作列表标题,不参与匹配。省略 `providers` 或使用空数组代表全部上游,指定多个平台时共用同一条规则。匹配与替换文本可含换行,空替换文本删除前缀
|
||||
|
||||
设置快照按目标上游索引规则,公共规则和限定平台的规则均按原始顺序生效,仅替换首个匹配前缀。上游没有适用规则时直接转发。API Key 使用同一套通用规则
|
||||
|
||||
Chat 和 Responses 优先取显式 `instructions`。否则只检查 `messages[0]` 或 `input[0]`,角色为 `system` 或 `developer` 时才匹配。Messages 取 `system`,GenAI 取 `systemInstruction` 或 `system_instruction`。分块内容仅在第一块为文本时改写该块。输入计数使用相同规则,GenAI 完整计数封套以其内层生成请求为准
|
||||
|
||||
### Provider 客户端身份
|
||||
|
||||
`providerRequestProfiles` 是按 Provider ID 索引的通用配置对象,最多 256 项、每项最多 64 KiB。
|
||||
|
||||
@@ -398,7 +398,7 @@ views/<页面>/
|
||||
|
||||
账号页管理分组、模型限制、并发、代理与导入任务。行操作与批量导出读取服务端返回的账号能力。OpenAI 的 API Key、OAuth 传输与逐条 token 导入归 `providers/openai/accounts`,Provider 表单持有凭据草稿与校验规则。新增时向页面提交导入文档,编辑时仅提供变更的连接配置
|
||||
|
||||
运行设置由同一份草稿和配置版本原子保存。通用和平台设置分区组合 `views/settings/components/` 中的控件,备份、定价、客户端版本及隐私规则等多文件组件各自封装私有实现。平台分区按 Provider 展示专属配置,通用分区承载调度、并发与排队、重试、错误保护、凭据刷新、历史保留、全局模型映射及安全与访问设置
|
||||
运行设置由同一份草稿和配置版本原子保存。通用和平台设置分区组合 `views/settings/components/` 中的控件,备份、定价、客户端版本及隐私规则等多文件组件各自封装私有实现。平台分区按 Provider 展示专属配置,通用分区承载提示词改写、调度、并发与排队、重试、错误保护、凭据刷新、历史保留、全局模型映射及安全与访问设置
|
||||
|
||||
全局配置和 Key 覆盖共用 `components/request-profile/index.vue` 的身份编辑流程,各 Provider 在 `providers/<id>/request-profile/` 解释自己的配置字段。定价页按查询接口返回的档位编辑
|
||||
|
||||
@@ -513,6 +513,8 @@ Core 独占路由、重试、交付事实与结算;Provider 独占上游身份
|
||||
API 的 `chat_completions/` 负责入口和 Chat 交付校验,复用 `generation/` 的提交、取消与终结生命周期。
|
||||
Chat 的 finish 与 usage 等待执行终态确认,终结失败不得先交付成功结果
|
||||
|
||||
运行设置快照共享提示词改写规则原文,按配置顺序索引全局规则和各上游规则。路由计划冻结快照,每次尝试只取所选平台的适用规则。attempt 中间件提交后,协议层定位系统文本,Core 匹配前缀。生成请求命中后同步更新已解析正文和原始 wire 中的目标字符串。计数由 Provider 解开封套,在已解析的计数正文上应用同一套规则
|
||||
|
||||
原始入口协议独立于转换后的正文协议,转换时保留来源与原始能力事实,不能从客户端头、User-Agent 或目标正文推断转换资格。
|
||||
内置转换只能从 Chat 来源调用;显式插件仍按现有能力声明与中间件合同运行。
|
||||
字段合同见 [Chat Completions](api.md#chat-completions-请求)和 [Messages](api.md#messages-请求),插件视图见 [SDK 请求中间件](../backend/crates/gateway-plugin/sdk/docs/capabilities.md#模型请求与-attempt)
|
||||
@@ -598,7 +600,7 @@ GenAI 模型目录复用 `ExecutionService::client_model_catalog`,由 Antigrav
|
||||
|
||||
Antigravity 目录声明原生 GenAI 和 Chat 转换能力,Responses、Messages 不借用 Chat 能力进入该平台。
|
||||
`provider/chat.rs` 装配 Chat ↔ GenAI 直接转换;`transport` 负责 Cloud Code 封装、原生 wire 与调用事实,
|
||||
并将冻结画像的提示词前置到客户端系统指令,保留客户端规则、工具说明和工作区上下文。默认提示和可编辑配置归 Provider 的 `profile`,纯协议层不持有 AGY 身份规则
|
||||
原生生成与计数前置冻结画像的系统提示,普通 Chat 使用转换后的系统指令
|
||||
|
||||
Antigravity 的业务头使用 API 保留的不透明多值字节,transport 统一执行账号身份、HTTP 传输及切号追踪头过滤。选号阶段从原会话绑定和 Core 的账号归属冻结切号事实,认领冲突后重新读取,不从重试排除集合推测归属
|
||||
|
||||
|
||||
+4
-2
@@ -191,7 +191,9 @@ Preset 的实心色使用 P6,普通 Container、Strong Container 与边界按
|
||||
默认浅色采用中性锚点,默认深色使用 HSL 色调派生;自定义中性色按外观距离平滑过渡到背景和文字 Seed 的 RGB 混色结果。
|
||||
Input、阴影与其他 Component Token 从 Fill、Surface、Primary 和 Semantic 派生,不在常量文件维护整套颜色表
|
||||
|
||||
正常文字同时检查 Layout、Container、Elevated、文字交互背景、三级 Fill,以及控件透明填充在各宿主上的合成色
|
||||
Surface 中的三级 Fill 表示不透明的背景层级,Control Fill 与实际宿主叠加,分别描述控件默认、Hover、Active 与内部条目的底色。内部条目使用文本 Seed 的 6% 透明填充,明暗主题共用规则,组件通过对应 Token 消费
|
||||
|
||||
正常文字同时检查 Layout、Container、Elevated、文字交互背景、三级 Fill,以及控件透明填充和内部条目在各宿主上的合成色
|
||||
和浅色的选中 / 选中 Hover 背景。正文、标题和 Secondary 至少 7:1,
|
||||
Tertiary 至少 5.5:1,Quaternary 至少 4.5:1。
|
||||
Disabled 使用独立的弱化颜色,不承担正常信息。控件填充由文字 Seed 和透明度派生,placeholder 使用 Quaternary。主按钮白字与功能色文字遵循各自的容器配对规则
|
||||
@@ -224,7 +226,7 @@ Token 直接覆盖时不会自动重算同组件的其他状态;需要保持
|
||||
| --- | --- |
|
||||
| Button | `--z-button-primary-color / bg / hover-bg / active-bg`、`--z-button-secondary-bg / hover-bg / active-bg` |
|
||||
| IconButton | `--z-icon-button-secondary-bg / hover-bg / active-bg` |
|
||||
| Input | `--z-input-bg / hover-bg / active-bg / error-active-bg` 与对应 Shadow |
|
||||
| Input | `--z-input-bg / hover-bg / active-bg / error-active-bg` 与对应 Shadow,`--z-input-tag-bg` 供 Select、InputTag 和折叠标签使用 |
|
||||
| Menu | `--z-menu-item-selected-bg / bg-image / shadow` |
|
||||
| Popover | `--z-popover-header-bg`、`--z-popover-shadow` |
|
||||
| Table | `--z-table-row-bg / stripe-bg / hover-bg / selected-bg / selected-hover-bg / height` |
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@boxicons/vue": "1.0.1",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.5",
|
||||
"@codex-proxy/ui": "github:zyycn/codex-proxy-ui#v0.13.6",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@lucide/vue": "^1.77.0",
|
||||
|
||||
Generated
+6
-6
@@ -195,8 +195,8 @@ importers:
|
||||
specifier: 1.0.1
|
||||
version: 1.0.1(vue@3.5.46(typescript@6.0.3))
|
||||
'@codex-proxy/ui':
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.13.5
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
specifier: github:zyycn/codex-proxy-ui#v0.13.6
|
||||
version: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/0a24a90657b6c7957e736c24f37911e87576aa7c(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)
|
||||
'@fontsource-variable/inter':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
@@ -456,9 +456,9 @@ packages:
|
||||
resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}
|
||||
engines: {node: '>= 20.12.0'}
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581':
|
||||
resolution: {gitHosted: true, integrity: sha512-LtGKbhViL9fixVJSCtEUZHDx+/13VOOUK1PMJHl6tlrxyNm8OR7s0tcMpmb3se+/v/F2gfZ0He/3n4a6fanUUA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581}
|
||||
version: 0.13.5
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/0a24a90657b6c7957e736c24f37911e87576aa7c':
|
||||
resolution: {gitHosted: true, integrity: sha512-Xv/1yz01IBSJK098vSrWPqg/gJoxd3H7Y8lS9wHTIGKyQ3FpOHyXxgbXGGc9GMw9fmAwELr50I5Yfg9zLA/PqA==, tarball: https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/0a24a90657b6c7957e736c24f37911e87576aa7c}
|
||||
version: 0.13.6
|
||||
engines: {node: '>=24'}
|
||||
peerDependencies:
|
||||
vite: ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0
|
||||
@@ -3590,7 +3590,7 @@ snapshots:
|
||||
fast-wrap-ansi: 0.2.2
|
||||
sisteransi: 1.0.5
|
||||
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/8228b10d8f4b02bda468a075f7f87358630c0581(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
'@codex-proxy/ui@https://codeload.github.com/zyycn/codex-proxy-ui/tar.gz/0a24a90657b6c7957e736c24f37911e87576aa7c(axios@1.21.1(debug@4.4.3))(change-case@5.4.4)(jiti@2.7.0)(postcss@8.5.30)(vite@8.3.8(@types/node@26.6.6)(jiti@2.7.0)(yaml@2.9.0))(vue@3.5.46(typescript@6.0.3))(yaml@2.9.0)':
|
||||
dependencies:
|
||||
'@ant-design/colors': 8.0.1
|
||||
'@ant-design/fast-color': 3.0.1
|
||||
|
||||
@@ -52,6 +52,13 @@ export interface OpenAiWebSocketPoolSettings {
|
||||
streamIdleTimeoutMs: number
|
||||
}
|
||||
|
||||
export interface PromptRewriteRule {
|
||||
name: string
|
||||
providers: string[]
|
||||
pattern: string
|
||||
replacement: string
|
||||
}
|
||||
|
||||
export interface RuntimeSettings {
|
||||
openaiWebsocketPool: OpenAiWebSocketPoolSettings
|
||||
configRevision: number
|
||||
@@ -91,6 +98,7 @@ export interface RuntimeSettings {
|
||||
usageRetentionDays: number
|
||||
opsEventRetentionDays: number
|
||||
auditRetentionDays: number
|
||||
promptRewriteRules: PromptRewriteRule[]
|
||||
accountErrorProtection: AccountErrorProtection
|
||||
accountWarmupEnabled: boolean
|
||||
accountWarmupCron: string
|
||||
|
||||
@@ -7,7 +7,7 @@ import { formatProviderLabel, PROVIDER_IDS, providerIcon } from '@/providers/cat
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
providers?: readonly Value[]
|
||||
leadingOption?: SegmentedOption
|
||||
leadingOption?: SegmentedOption | SegmentedOption[]
|
||||
display?: 'icon' | 'label'
|
||||
size?: 'small' | 'default' | 'large'
|
||||
disabled?: boolean
|
||||
@@ -19,9 +19,7 @@ const props = withDefaults(defineProps<{
|
||||
const provider = defineModel<Value>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const options = computed(() => [
|
||||
...(props.leadingOption
|
||||
? [props.leadingOption]
|
||||
: []),
|
||||
...[props.leadingOption ?? []].flat(),
|
||||
...(props.providers ?? PROVIDER_IDS).map(value => ({
|
||||
value,
|
||||
label: formatProviderLabel(value),
|
||||
|
||||
@@ -4,7 +4,7 @@ import { ZPopover, ZScrollbar } from '@codex-proxy/ui'
|
||||
import { CheckCheck, CircleHelp, Network, Server, Unplug } from '@lucide/vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { usageErrorOrigin, usageErrorReason, usageErrorTitle } from './errors'
|
||||
import { usageErrorOrigin, usageErrorSummary, usageErrorTitle } from './errors'
|
||||
|
||||
const props = defineProps<{ record: UsageListRecord }>()
|
||||
|
||||
@@ -20,14 +20,7 @@ const code = computed(() => props.record.errorCode || props.record.errorKind)
|
||||
const errorType = computed(() => props.record.errorKind || props.record.errorCode)
|
||||
const origin = computed(() => usageErrorOrigin(props.record))
|
||||
const outcome = computed(() => usageErrorTitle(props.record))
|
||||
const summary = computed(() => {
|
||||
const reason = props.record.errorMessage || usageErrorReason(code.value) || code.value
|
||||
if (reason)
|
||||
return reason
|
||||
return props.record.websocketCloseCode != null
|
||||
? `WS ${props.record.websocketCloseCode}`
|
||||
: t('usage.error.noDetails')
|
||||
})
|
||||
const summary = computed(() => usageErrorSummary(props.record))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { UsageErrorFacts } from '@/api'
|
||||
import type { UsageErrorFacts, UsageListRecord } from '@/api'
|
||||
import { t } from '@/i18n'
|
||||
|
||||
export type UsageErrorRecord = UsageErrorFacts & {
|
||||
@@ -56,12 +56,33 @@ export function usageSendStateText(state: string) {
|
||||
}
|
||||
}
|
||||
|
||||
export function usageErrorReason(code: string | null): string | undefined {
|
||||
export function usageErrorSummary(record: UsageListRecord): string {
|
||||
const reason = usageErrorReason(record.errorKind) || usageErrorReason(record.errorCode)
|
||||
if (reason)
|
||||
return reason
|
||||
|
||||
// 历史限流分类也包含额度耗尽,只有记录了具体原因才能进一步区分
|
||||
if (record.errorKind === 'rate_limited' || record.errorCode === 'rate_limited')
|
||||
return t('usage.error.requestLimited')
|
||||
|
||||
const upstreamClosed = record.websocketCloseCode != null
|
||||
|| record.upstreamConnectionExitReason === 'upstream_close'
|
||||
|| record.upstreamConnectionExitReason === 'normal_close'
|
||||
if (record.errorKind === 'upstream_unavailable' && upstreamClosed)
|
||||
return t('usage.error.upstreamConnectionClosed')
|
||||
|
||||
return record.errorMessage || record.errorCode || record.errorKind
|
||||
|| (record.websocketCloseCode != null
|
||||
? `WS ${record.websocketCloseCode}`
|
||||
: t('usage.error.noDetails'))
|
||||
}
|
||||
|
||||
function usageErrorReason(code: string | null): string | undefined {
|
||||
switch (code) {
|
||||
case 'no_available_provider': return t('usage.error.noAvailableProvider')
|
||||
case 'account_pool_quota_exhausted':
|
||||
case 'quota_exhausted': return t('accounts.fields.quotaExhausted')
|
||||
case 'rate_limited':
|
||||
case 'upstream_capacity_unavailable': return t('usage.error.upstreamCapacityUnavailable')
|
||||
case 'rate_limit_exceeded': return t('common.errors.rateLimited')
|
||||
case 'invalid_request': return t('common.errors.invalidParameters')
|
||||
case 'upstream_connection_closed': return t('usage.error.upstreamConnectionClosed')
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
{
|
||||
"settings": {
|
||||
"promptRewrite": {
|
||||
"addRule": "Add rule",
|
||||
"editRule": "Edit rule",
|
||||
"editNamedRule": "Edit rule {name}",
|
||||
"deleteRule": "Delete rule {name}",
|
||||
"ruleName": "Rule name",
|
||||
"namePlaceholder": "e.g. DSH prompt adaptation",
|
||||
"nameRequired": "Enter a rule name",
|
||||
"title": "Prompt rewriting",
|
||||
"description": "Replace the first matching system instruction prefix in rule order. Leave the replacement empty to remove the prefix.",
|
||||
"empty": "No rewrite rules",
|
||||
"providers": "Upstream platforms",
|
||||
"matchPrefix": "Match prefix",
|
||||
"replacement": "Replacement text",
|
||||
"required": "Enter a prefix to match"
|
||||
},
|
||||
"clientProfile": {
|
||||
"systemPrompt": "System prompt",
|
||||
"systemPromptHint": "Prepended to client system instructions · Default from {source}",
|
||||
"restoreSystemPrompt": "Restore default",
|
||||
"userAgent": "User agent",
|
||||
"clientIdentitySource": "Client identity source",
|
||||
"globalConfiguration": "Global configuration",
|
||||
|
||||
@@ -267,6 +267,8 @@
|
||||
"error": {
|
||||
"noDetails": "No detailed error message was recorded",
|
||||
"noAvailableProvider": "No upstream provider is available for this request.",
|
||||
"requestLimited": "Request limited",
|
||||
"upstreamCapacityUnavailable": "Upstream model is at capacity",
|
||||
"upstreamConnectionClosed": "Upstream connection closed",
|
||||
"queueTimeout": "Request queue wait timed out",
|
||||
"queueFull": "Request queue is full",
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
{
|
||||
"settings": {
|
||||
"promptRewrite": {
|
||||
"addRule": "添加规则",
|
||||
"editRule": "编辑规则",
|
||||
"editNamedRule": "编辑规则 {name}",
|
||||
"deleteRule": "删除规则 {name}",
|
||||
"ruleName": "规则名称",
|
||||
"namePlaceholder": "例如 DSH 提示词适配",
|
||||
"nameRequired": "请输入规则名称",
|
||||
"title": "提示词改写",
|
||||
"description": "按顺序匹配系统指令的前缀,首条命中后替换。替换文本留空可删除前缀",
|
||||
"empty": "暂无改写规则",
|
||||
"providers": "适用上游",
|
||||
"matchPrefix": "匹配前缀",
|
||||
"replacement": "替换文本",
|
||||
"required": "请输入匹配前缀"
|
||||
},
|
||||
"clientProfile": {
|
||||
"systemPrompt": "系统提示词",
|
||||
"systemPromptHint": "前置系统提示,保留客户端指令,默认来自 {source}",
|
||||
"restoreSystemPrompt": "恢复默认",
|
||||
"userAgent": "用户代理",
|
||||
"clientIdentitySource": "客户端身份来源",
|
||||
"globalConfiguration": "全局配置",
|
||||
|
||||
@@ -267,6 +267,8 @@
|
||||
"error": {
|
||||
"noDetails": "未记录具体错误消息",
|
||||
"noAvailableProvider": "此请求没有可用的上游服务",
|
||||
"requestLimited": "请求受限",
|
||||
"upstreamCapacityUnavailable": "上游模型容量不足",
|
||||
"upstreamConnectionClosed": "上游连接已关闭",
|
||||
"queueTimeout": "请求排队超时",
|
||||
"queueFull": "请求队列已满",
|
||||
|
||||
@@ -1,9 +1,22 @@
|
||||
{
|
||||
"settings": {
|
||||
"promptRewrite": {
|
||||
"addRule": "添加規則",
|
||||
"editRule": "編輯規則",
|
||||
"editNamedRule": "編輯規則 {name}",
|
||||
"deleteRule": "刪除規則 {name}",
|
||||
"ruleName": "規則名稱",
|
||||
"namePlaceholder": "例如 DSH 提示詞適配",
|
||||
"nameRequired": "請輸入規則名稱",
|
||||
"title": "提示詞改寫",
|
||||
"description": "依序比對系統指令的前綴,替換首個符合的前綴。替換文字留空可刪除前綴",
|
||||
"empty": "暫無改寫規則",
|
||||
"providers": "適用上游",
|
||||
"matchPrefix": "比對前綴",
|
||||
"replacement": "替換文字",
|
||||
"required": "請輸入比對前綴"
|
||||
},
|
||||
"clientProfile": {
|
||||
"systemPrompt": "系統提示詞",
|
||||
"systemPromptHint": "前置系統提示,保留客戶端指令,預設來自 {source}",
|
||||
"restoreSystemPrompt": "恢復預設",
|
||||
"userAgent": "用戶代理",
|
||||
"clientIdentitySource": "客戶端身份來源",
|
||||
"globalConfiguration": "全局配置",
|
||||
|
||||
@@ -267,6 +267,8 @@
|
||||
"error": {
|
||||
"noDetails": "未記錄具體錯誤消息",
|
||||
"noAvailableProvider": "此請求沒有可用的上游服務",
|
||||
"requestLimited": "請求受限",
|
||||
"upstreamCapacityUnavailable": "上游模型容量不足",
|
||||
"upstreamConnectionClosed": "上游連線已關閉",
|
||||
"queueTimeout": "請求排隊超時",
|
||||
"queueFull": "請求隊列已滿",
|
||||
|
||||
+1
-31
@@ -1,10 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import type { ProfileOptions, ProfilePreview, ProfileSelection } from './profile'
|
||||
import type { ProfileEditorProps } from '@/components/request-profile/useProfileEditor'
|
||||
import { ZButton, ZFormItem, ZInput, ZSelect, ZTextarea } from '@codex-proxy/ui'
|
||||
import { ZFormItem, ZInput, ZSelect } from '@codex-proxy/ui'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import HelpPopover from '@/components/HelpPopover.vue'
|
||||
import ProfileEditorFrame from '@/components/request-profile/ProfileEditorFrame.vue'
|
||||
import { useProfileEditor } from '@/components/request-profile/useProfileEditor'
|
||||
|
||||
@@ -62,15 +61,6 @@ function updateVersion(value: string) {
|
||||
if (effective.value)
|
||||
model.value = { ...effective.value, clientVersion: value.trim() || null }
|
||||
}
|
||||
|
||||
const systemPrompt = computed({
|
||||
get: () => effective.value?.systemPrompt ?? options.value?.defaultSystemPrompt ?? '',
|
||||
set: (value: string) => updateSystemPrompt(value),
|
||||
})
|
||||
function updateSystemPrompt(value: string | null) {
|
||||
if (effective.value)
|
||||
model.value = { ...effective.value, systemPrompt: value }
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -107,25 +97,5 @@ function updateSystemPrompt(value: string | null) {
|
||||
/>
|
||||
</ZFormItem>
|
||||
</div>
|
||||
<ZFormItem :label="t('settings.clientProfile.systemPrompt')">
|
||||
<template #label-extra>
|
||||
<HelpPopover
|
||||
:label="t('settings.clientProfile.systemPrompt')"
|
||||
:content="t('settings.clientProfile.systemPromptHint', { source: options?.systemPromptSource ?? '' })"
|
||||
/>
|
||||
</template>
|
||||
<div class="grid gap-2">
|
||||
<ZTextarea
|
||||
v-model="systemPrompt"
|
||||
:aria-label="t('settings.clientProfile.systemPrompt')"
|
||||
:disabled="disabled || loading"
|
||||
:rows="5"
|
||||
resize="vertical"
|
||||
/>
|
||||
<ZButton variant="link" size="small" class="justify-self-end" :disabled="disabled || loading || effective?.systemPrompt == null" @click="updateSystemPrompt(null)">
|
||||
{{ t('settings.clientProfile.restoreSystemPrompt') }}
|
||||
</ZButton>
|
||||
</div>
|
||||
</ZFormItem>
|
||||
</ProfileEditorFrame>
|
||||
</template>
|
||||
|
||||
@@ -10,8 +10,6 @@ export interface ProfileSelection {
|
||||
}
|
||||
|
||||
export interface ProfileOptions {
|
||||
defaultSystemPrompt: string
|
||||
systemPromptSource: string
|
||||
defaults: ProfileSelection
|
||||
presets: {
|
||||
configuration: ProfileSelection
|
||||
|
||||
@@ -5,6 +5,7 @@ import { computed, shallowRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { getBudgetReferenceAccounts } from '@/api'
|
||||
import { useRequestState } from '@/composables/useRequestState'
|
||||
import { accountIdentityLabel } from '@/views/accounts/utils/accountIdentity'
|
||||
|
||||
const props = defineProps<{ keyId: string, disabled: boolean }>()
|
||||
const accountId = defineModel<string>()
|
||||
@@ -32,11 +33,17 @@ async function load() {
|
||||
try {
|
||||
const page = await getBudgetReferenceAccounts(props.keyId, search.value.trim(), cursor.value, { signal: request.signal, silent: true })
|
||||
if (request.isCurrent(id)) {
|
||||
items.value = items.value.concat(page.items.map(account => ({
|
||||
value: account.id,
|
||||
label: account.name,
|
||||
description: account.email || account.provider,
|
||||
})))
|
||||
items.value = items.value.concat(page.items.map((account) => {
|
||||
const label = accountIdentityLabel(account)
|
||||
const email = account.email?.trim()
|
||||
return {
|
||||
value: account.id,
|
||||
label,
|
||||
description: email && email !== label
|
||||
? email
|
||||
: account.provider,
|
||||
}
|
||||
}))
|
||||
cursor.value = page.nextCursor ?? undefined
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
<script setup lang="ts">
|
||||
import type { PromptRewriteRule } from '@/api'
|
||||
import { ZButton, ZDialog, ZForm, ZFormItem, ZInput, ZTextarea } from '@codex-proxy/ui'
|
||||
import { Layers, LayoutGrid } from '@lucide/vue'
|
||||
import { computed, ref, useId, useTemplateRef, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ProviderSelect from '@/components/ProviderSelect.vue'
|
||||
import { formatProviderLabel, isBuiltinProvider } from '@/providers/catalog'
|
||||
|
||||
const props = defineProps<{ rule?: PromptRewriteRule, disabled: boolean }>()
|
||||
const emit = defineEmits<{ confirm: [rule: PromptRewriteRule] }>()
|
||||
const open = defineModel<boolean>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const formId = useId()
|
||||
const formRef = useTemplateRef<InstanceType<typeof ZForm>>('formElement')
|
||||
const draft = ref<PromptRewriteRule>({
|
||||
name: '',
|
||||
providers: [],
|
||||
pattern: '',
|
||||
replacement: '',
|
||||
})
|
||||
const leadingOptions = computed(() => {
|
||||
const all = {
|
||||
value: '',
|
||||
label: t('common.providers.all'),
|
||||
icon: LayoutGrid,
|
||||
}
|
||||
const providers = draft.value.providers
|
||||
if (!providers.length || (providers.length === 1 && isBuiltinProvider(providers[0])))
|
||||
return all
|
||||
// 已保存的组合或自定义上游继续使用原范围
|
||||
return [
|
||||
all,
|
||||
{
|
||||
value: providers.join(', '),
|
||||
label: providers.map(provider => formatProviderLabel(provider)).join(' + '),
|
||||
icon: Layers,
|
||||
},
|
||||
]
|
||||
})
|
||||
|
||||
watch(open, (value) => {
|
||||
if (value) {
|
||||
draft.value = {
|
||||
name: props.rule?.name ?? '',
|
||||
providers: [
|
||||
...(props.rule?.providers ?? []),
|
||||
],
|
||||
pattern: props.rule?.pattern ?? '',
|
||||
replacement: props.rule?.replacement ?? '',
|
||||
}
|
||||
formRef.value?.clearValidate()
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
async function confirm() {
|
||||
if (props.disabled || !await formRef.value?.validate().catch(() => false) || !open.value)
|
||||
return
|
||||
emit('confirm', {
|
||||
...draft.value,
|
||||
name: draft.value.name.trim(),
|
||||
})
|
||||
open.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZDialog v-model="open" destroy-on-close :title="rule ? t('settings.promptRewrite.editRule') : t('settings.promptRewrite.addRule')" width="52rem">
|
||||
<ZForm :id="formId" ref="formElement" :model="draft" novalidate @submit.stop.prevent="confirm">
|
||||
<ZFormItem :label="t('settings.promptRewrite.ruleName')" prop="name" :show-message="false" :rules="{ required: true, whitespace: true, message: t('settings.promptRewrite.nameRequired') }" required>
|
||||
<ZInput v-model="draft.name" :aria-label="t('settings.promptRewrite.ruleName')" :placeholder="t('settings.promptRewrite.namePlaceholder')" :disabled="disabled" />
|
||||
</ZFormItem>
|
||||
<ZFormItem :label="t('settings.promptRewrite.providers')">
|
||||
<ProviderSelect
|
||||
:model-value="draft.providers.join(', ')" :leading-option="leadingOptions"
|
||||
:aria-label="t('settings.promptRewrite.providers')" :disabled="disabled"
|
||||
@update:model-value="draft.providers = $event ? [$event] : []"
|
||||
/>
|
||||
</ZFormItem>
|
||||
<div class="grid min-w-0 gap-4 sm:grid-cols-2">
|
||||
<ZFormItem :label="t('settings.promptRewrite.matchPrefix')" prop="pattern" :show-message="false" :rules="{ required: true, message: t('settings.promptRewrite.required') }" required>
|
||||
<ZTextarea v-model="draft.pattern" :aria-label="t('settings.promptRewrite.matchPrefix')" :disabled="disabled" :rows="8" resize="vertical" />
|
||||
</ZFormItem>
|
||||
<ZFormItem :label="t('settings.promptRewrite.replacement')">
|
||||
<ZTextarea v-model="draft.replacement" :aria-label="t('settings.promptRewrite.replacement')" :disabled="disabled" :rows="8" resize="vertical" />
|
||||
</ZFormItem>
|
||||
</div>
|
||||
</ZForm>
|
||||
<template #footer>
|
||||
<ZButton @click="open = false">
|
||||
{{ t('common.actions.cancel') }}
|
||||
</ZButton>
|
||||
<ZButton native-type="submit" :form="formId" type="primary" :disabled="disabled">
|
||||
{{ t('common.actions.confirm') }}
|
||||
</ZButton>
|
||||
</template>
|
||||
</ZDialog>
|
||||
</template>
|
||||
@@ -0,0 +1,80 @@
|
||||
<script setup lang="ts">
|
||||
import type { PromptRewriteRule } from '@/api'
|
||||
import { ZButton, ZCard, ZEmpty, ZIconButton } from '@codex-proxy/ui'
|
||||
import { LayoutGrid, Pencil, Plus, Trash2 } from '@lucide/vue'
|
||||
import { computed, shallowRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import ProviderIconGroup from '@/components/ProviderIconGroup.vue'
|
||||
import { formatProviderLabel } from '@/providers/catalog'
|
||||
import RuleEditor from './RuleEditor.vue'
|
||||
|
||||
const props = defineProps<{ disabled: boolean, ready: boolean }>()
|
||||
const rules = defineModel<PromptRewriteRule[]>({ required: true })
|
||||
const { t } = useI18n({ useScope: 'global' })
|
||||
const editorOpen = shallowRef(false)
|
||||
const editingIndex = shallowRef<number | null>(null)
|
||||
const selectedRule = computed(() => editingIndex.value === null
|
||||
? undefined
|
||||
: rules.value[editingIndex.value])
|
||||
const rows = computed(() => rules.value.map(rule => ({
|
||||
rule,
|
||||
title: rule.name,
|
||||
providers: rule.providers.length
|
||||
? rule.providers.map(provider => formatProviderLabel(provider)).join(' + ')
|
||||
: t('common.providers.all'),
|
||||
})))
|
||||
|
||||
function edit(index: number | null) {
|
||||
editingIndex.value = index
|
||||
editorOpen.value = true
|
||||
}
|
||||
|
||||
function apply(rule: PromptRewriteRule) {
|
||||
if (props.disabled)
|
||||
return
|
||||
rules.value = editingIndex.value === null
|
||||
? [...rules.value, rule]
|
||||
: rules.value.map((item, index) => index === editingIndex.value
|
||||
? rule
|
||||
: item)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ZCard :title="t('settings.promptRewrite.title')" :description="t('settings.promptRewrite.description')">
|
||||
<template #actions>
|
||||
<ZButton :disabled="disabled" @click="edit(null)">
|
||||
<template #icon>
|
||||
<Plus class="size-4" />
|
||||
</template>
|
||||
{{ t('settings.promptRewrite.addRule') }}
|
||||
</ZButton>
|
||||
</template>
|
||||
<template #body>
|
||||
<ZEmpty v-if="ready && !rules.length" :title="t('settings.promptRewrite.empty')" size="small" surface="none" role="status" class="flex-1 content-center py-3!" />
|
||||
<ul v-if="rules.length" class="m-0 grid list-none gap-2 p-0">
|
||||
<li v-for="(row, index) in rows" :key="index" class="flex min-w-0 items-center gap-3 rounded-z-lg bg-z-fill-quaternary px-3 py-2">
|
||||
<div class="grid min-w-0 flex-1 gap-1 sm:grid-cols-[10rem_minmax(0,1fr)] sm:items-center sm:gap-4">
|
||||
<span class="flex min-w-0 items-center gap-2 text-z-sm text-z-text-secondary" :title="row.providers">
|
||||
<span class="flex shrink-0 items-center gap-1" aria-hidden="true">
|
||||
<ProviderIconGroup v-for="provider in row.rule.providers" :key="provider" :provider="provider" size="sm" />
|
||||
<LayoutGrid v-if="!row.rule.providers.length" class="size-4" />
|
||||
</span>
|
||||
<span class="truncate">{{ row.providers }}</span>
|
||||
</span>
|
||||
<span class="truncate text-z-sm font-emphasis text-z-text" :title="row.title">{{ row.title }}</span>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-1">
|
||||
<ZIconButton :disabled="disabled" :aria-label="t('settings.promptRewrite.editNamedRule', { name: row.title })" @click="edit(index)">
|
||||
<Pencil class="size-4" />
|
||||
</ZIconButton>
|
||||
<ZIconButton :disabled="disabled" :aria-label="t('settings.promptRewrite.deleteRule', { name: row.title })" @click="rules = rules.filter((_, i) => i !== index)">
|
||||
<Trash2 class="size-4 text-z-error" />
|
||||
</ZIconButton>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<RuleEditor v-model="editorOpen" :rule="selectedRule" :disabled="disabled" @confirm="apply" />
|
||||
</template>
|
||||
</ZCard>
|
||||
</template>
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ProtectionDraft } from '../components/error-protection/policy'
|
||||
import type { rotationOptions } from '../constants'
|
||||
import type { AccountAffinity, CodexPrivacyPolicy, OpenAiRequestCountry, ProviderRequestProfiles, ResetWindowWeights, SmartSchedulingConfig } from '@/api'
|
||||
import type { AccountAffinity, CodexPrivacyPolicy, OpenAiRequestCountry, PromptRewriteRule, ProviderRequestProfiles, ResetWindowWeights, SmartSchedulingConfig } from '@/api'
|
||||
import { cloneDeep, isEqual } from 'es-toolkit'
|
||||
import { computed, reactive, ref, shallowRef } from 'vue'
|
||||
import { detectRequestLocation, getSettings, updateSettings } from '@/api'
|
||||
@@ -76,6 +76,7 @@ export function useSettingsForm() {
|
||||
opsEventRetentionDays: 30,
|
||||
auditRetentionDays: 90,
|
||||
|
||||
promptRewriteRules: [] as PromptRewriteRule[],
|
||||
accountErrorProtection: {
|
||||
enabled: false,
|
||||
rules: [],
|
||||
@@ -180,6 +181,7 @@ export function useSettingsForm() {
|
||||
form.usageRetentionDays = data.usageRetentionDays
|
||||
form.opsEventRetentionDays = data.opsEventRetentionDays
|
||||
form.auditRetentionDays = data.auditRetentionDays
|
||||
form.promptRewriteRules = cloneDeep(data.promptRewriteRules ?? [])
|
||||
form.accountErrorProtection = {
|
||||
...cloneDeep(data.accountErrorProtection),
|
||||
probeModel: data.accountErrorProtection.probeModel ?? '',
|
||||
@@ -332,6 +334,7 @@ export function useSettingsForm() {
|
||||
usageRetentionDays: usageRetentionDays!,
|
||||
opsEventRetentionDays: form.opsEventRetentionDays,
|
||||
auditRetentionDays: form.auditRetentionDays,
|
||||
promptRewriteRules: form.promptRewriteRules,
|
||||
accountErrorProtection: {
|
||||
...cloneDeep(form.accountErrorProtection),
|
||||
threshold: form.accountErrorProtection.threshold!,
|
||||
|
||||
@@ -22,6 +22,7 @@ import ModelAliasesCard from './components/ModelAliasesCard.vue'
|
||||
import OpenAiRequestCard from './components/OpenAiRequestCard.vue'
|
||||
import PricingSection from './components/pricing/index.vue'
|
||||
import PrivacyPolicyCard from './components/privacy/index.vue'
|
||||
import PromptRewriteRulesCard from './components/prompt-rewrite/index.vue'
|
||||
import RequestHistoryCard from './components/RequestHistoryCard.vue'
|
||||
import RequestLocationCard from './components/RequestLocationCard.vue'
|
||||
import RequestProfileCard from './components/RequestProfileCard.vue'
|
||||
@@ -252,6 +253,7 @@ watch(() => !loading.value && route.hash === '#reset-credits', async (ready) =>
|
||||
/>
|
||||
<TokenRefreshCard v-model:refresh-margin-seconds="refreshMarginSecondsValue" v-model:refresh-concurrency="refreshConcurrencyValue" />
|
||||
<AccountErrorProtectionCard v-model="form.accountErrorProtection" class="col-span-full" :disabled="disabled" />
|
||||
<PromptRewriteRulesCard v-model="form.promptRewriteRules" :ready="!loading && !error" :disabled="disabled" class="col-span-full" />
|
||||
<ModelAliasesCard
|
||||
:mappings="mappings"
|
||||
:loading="loading"
|
||||
|
||||
+1
-1
Submodule modules/ui updated: 8228b10d8f...0a24a90657
+9
-11
@@ -1,23 +1,21 @@
|
||||
# v3.58.0
|
||||
# v3.59.0
|
||||
|
||||
## 新增功能
|
||||
|
||||
- API 密钥可设置生效和到期时间,已有密钥和未设置有效期的新密钥默认长期有效
|
||||
- 代理管理支持保存自定义 HTTPS 测试目标,可批量查看各代理访问同一站点的状态码和延迟
|
||||
- 密钥管理页和用量页可生成 OpenAI、xAI 和 Antigravity 的客户端配置,并支持导入 CC Switch
|
||||
- 提示词改写以平台和规则名称列表管理,支持弹窗编辑、按上游限定首个前缀替换,空替换可删除前缀,输入计数同步应用规则
|
||||
|
||||
## 优化改进
|
||||
|
||||
- 手动重置密钥额度后立即开始新的计费窗口,日额度从重置时起算 24 小时,周额度起算 7 天
|
||||
- CPR 互联按使用情况刷新上游额度,耗尽账号按重置时间复查
|
||||
- 账号连接测试支持搜索模型,账号列表可查看被截断的邮箱和备注全文
|
||||
- 请求记录优先显示错误码,并按界面语言展示常见错误原因,区分上游容量不足、连接关闭与请求受限
|
||||
- 管理端升级至 UI v0.13.6,改善深色分段选择器的选中状态、多选标签底色,以及可搜索单选框的对齐、字重和加载提示
|
||||
- 密钥额度对齐的参考账号统一显示账号名称或邮箱,避免重复展示邮箱
|
||||
|
||||
## 问题修复
|
||||
|
||||
- OpenAI 原生续写在原账号排队超时后,若有其他账号可立即接入,网关会提示客户端携带完整历史重发
|
||||
- Antigravity CLI 独立网页搜索可使用 OAuth 账号目录声明的搜索模型,修复因找不到辅助型号而返回 404 的问题
|
||||
- 请求记录区分网关选号时的额度耗尽、上游限流及密钥自身的频率和并发限制,便于定位失败原因
|
||||
- 多行输入框自动高度正确遵循最小和最大行数,内容减少后可收缩
|
||||
- 多个弹窗同时打开时,关闭或卸载较早打开的弹窗不会提前解除页面滚动锁
|
||||
|
||||
## 升级须知
|
||||
|
||||
- 已在 PostgreSQL 18 上验证从 v3.57.2 升级。源码部署若执行过开发版的 `0049_client_key_validity.sql` 或 `0050_proxy_test_targets.sql`,直接升级会在启动时迁移校验失败
|
||||
- Antigravity 普通 Chat 转发不再自动前置客户端画像提示词;需要改写系统指令时使用通用设置中的提示词改写规则,原生生成与计数仍前置画像提示词
|
||||
- 已在 PostgreSQL 18 上验证从 v3.58.0 的数据库结构升级,现有运行设置保持不变,提示词改写规则默认为空
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
version: 3.58.0
|
||||
version: 3.59.0
|
||||
published:
|
||||
'3':
|
||||
stable: 3.57.2
|
||||
rc: 3.57.2
|
||||
beta: 3.57.2
|
||||
alpha: 3.57.2
|
||||
stable: 3.58.0
|
||||
rc: 3.58.0
|
||||
beta: 3.58.0
|
||||
alpha: 3.58.0
|
||||
|
||||
Reference in New Issue
Block a user