feat(admin/apix): 编辑改弹出卡片 + API 代理去「市场」概念 + 修示例地址拼接
1. LLM 上游 / API 代理的「新建 / 编辑」改为弹出卡片(IP.modal), 列表页只留复制地址 / 测试 / 编辑 / 启停 / 删除,体验更轻。 2. API 代理彻底去「API 市场 / 平台级凭据」概念:souyi 仅作供应商之一, 每条代理自带 base / 供应商 Key / asset_id(后端 platform 概念已移除), 源码与文档均不再出现 souyi / AIMALL 品牌与目录直拉。 3. 修 apix.js 示例地址拼接 bug:之前末尾出现 `?q=?q=`, 现 url 只拼一次 `?q=`、示例给出 `?q=关键词`(base 由后端返回纯基址)。 Co-Authored-By: 小K <[email protected]>
This commit is contained in:
1 parent
dbee9ff3fd
commit
1fb83e4dda
17 files changed
+386
-478
No files matched your search
+6
-42
@@ -94,8 +94,6 @@ fn route(method: &str, uri: &str) -> Option<(Guard, Handler)> {
|
||||
("GET", "/api/admin/apix") => (Guard::Admin, h_admin_apix),
|
||||
("POST", "/api/admin/apix/save") => (Guard::Admin, h_admin_apix_save),
|
||||
("POST", "/api/admin/apix/delete") => (Guard::Admin, h_admin_apix_delete),
|
||||
("POST", "/api/admin/apix/platform") => (Guard::Admin, h_admin_apix_platform),
|
||||
("POST", "/api/admin/apix/price") => (Guard::Admin, h_admin_apix_price),
|
||||
("POST", "/api/admin/apix/test") => (Guard::Admin, h_admin_apix_test),
|
||||
("GET", "/api/v1/apix") => (Guard::User, h_my_apix),
|
||||
("GET", "/api/v1/me") => (Guard::User, h_me),
|
||||
@@ -682,14 +680,13 @@ fn h_admin_trend(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
// API 代理管理
|
||||
// ===========================================================================
|
||||
|
||||
/// 管理员:API 代理清单 + 平台凭据状态
|
||||
/// 管理员:API 代理清单
|
||||
fn h_admin_apix(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
let port = http::host_port(r);
|
||||
let list = apix::all();
|
||||
http::ok(
|
||||
r,
|
||||
json!({
|
||||
"platform": apix::platform_view(),
|
||||
"items": apix::view_all(&list, &port),
|
||||
"count": list.len(),
|
||||
}),
|
||||
@@ -727,6 +724,9 @@ fn h_admin_apix_save(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
match apix::upsert(
|
||||
&slug,
|
||||
&asset,
|
||||
p.get("base"),
|
||||
p.get("key"),
|
||||
p.get("supplier"),
|
||||
p.get("name"),
|
||||
p.get("desc"),
|
||||
params,
|
||||
@@ -753,45 +753,9 @@ fn h_admin_apix_delete(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理员:设置市场基址与平台 Key
|
||||
fn h_admin_apix_platform(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
let p = http::params(r);
|
||||
match apix::set_platform(p.get("base"), p.get("key")) {
|
||||
Ok(data) => {
|
||||
util::log_notice(&format!(
|
||||
"[api] 更新 API 代理平台配置 base={} key_set={}",
|
||||
data.base,
|
||||
!data.key.is_empty()
|
||||
));
|
||||
http::ok(
|
||||
r,
|
||||
json!({ "base": data.base, "key_set": !data.key.is_empty() }),
|
||||
"已保存",
|
||||
)
|
||||
}
|
||||
Err(e) => http::fail(r, HTTPStatus::BAD_REQUEST, &e),
|
||||
}
|
||||
}
|
||||
|
||||
/// 管理员:回填展示用的单价快照(从市场目录同步下来的数字,不参与计费)
|
||||
fn h_admin_apix_price(r: *mut ngx_http_request_t, _actor: Actor) -> Status {
|
||||
let p = http::params(r);
|
||||
let slug = p.get("slug").cloned().unwrap_or_default();
|
||||
let num = |k: &str| -> f64 {
|
||||
p.get(k)
|
||||
.map(|v| util::trim(v).parse::<f64>().unwrap_or(0.0))
|
||||
.unwrap_or(0.0)
|
||||
};
|
||||
if apix::validate_slug(&slug).is_err() {
|
||||
return http::fail(r, HTTPStatus::BAD_REQUEST, "slug 不合法");
|
||||
}
|
||||
apix::set_price(&slug, num("price_per_call"), num("price_in"), num("price_out"));
|
||||
http::ok(r, json!({ "slug": slug }), "ok")
|
||||
}
|
||||
|
||||
/// 管理员:探测平台 Key 是否可用(管理台「测试」按钮)。
|
||||
/// 管理员:探测供应商 Key 是否可用(管理台「测试」按钮)。
|
||||
///
|
||||
/// 走市场的**免费预估**接口(`/api/v1/ai/estimate`):它不执行资产、不扣费,
|
||||
/// 走供应商的**免费预估**接口(`/api/v1/ai/estimate`):它不执行资产、不扣费,
|
||||
/// 响应里还带 `current_balance_usd` —— 一次调用同时拿到「Key 通不通」和
|
||||
/// 「还剩多少钱」。实现上内部重定向到管理 server 的 `/_apix_probe/<slug>`,
|
||||
/// 复用 `$apix_probe_*` 变量(拼体、换 Key 与真实转发同一套逻辑)。
|
||||
|
||||
+75
-110
@@ -1,17 +1,17 @@
|
||||
//! API 代理:把外部 API 市场(aimall / 搜蚁智选)的资产挂到网关下。
|
||||
//! API 代理:把外部供应商的 API 资产挂到网关下。
|
||||
//!
|
||||
//! 与 LLM 代理(`llm.rs`)是**同一套下行契约**——都认 `sk_` 那把 Key、都吃
|
||||
//! 同一份限流配额、都进同一套用量统计——差别只在上游形态:
|
||||
//!
|
||||
//! | | LLM 代理 | API 代理 |
|
||||
//! | --- | --- | --- |
|
||||
//! | 上游 | N 家厂商,各有基址与密钥 | 一个市场,共用基址与平台 Key |
|
||||
//! | 上游 | N 家厂商,各有基址与密钥 | 每条记录自带基址与供应商 Key |
|
||||
//! | URL 第一段 | `slot` → `up:` 里的 `base \n auth` | `slug` → `ax:` 里的 `base \n key \n asset_id` |
|
||||
//! | 请求体 | 客户端原样带过来 | **由网关从 query 拼**(见下) |
|
||||
//!
|
||||
//! ## 为什么请求体必须由网关拼
|
||||
//!
|
||||
//! 市场侧只有一个收口 `POST /api/v1/ai/request`,资产靠**请求体里的
|
||||
//! 供应商侧只有一个收口 `POST /api/v1/ai/request`,资产靠**请求体里的
|
||||
//! `asset_id`** 区分。如果让客户端自己带 `asset_id`,管理员就失去了
|
||||
//! 「只暴露免费资产」的控制力——任何人都能拿网关的 Key 去刷最贵的那个模型。
|
||||
//! 所以资产选择权留在服务端:`slug → asset_id` 由管理员配置,
|
||||
@@ -22,7 +22,7 @@
|
||||
//! `proxy_method POST` + `proxy_set_body $apix_body` 把 GET 变成
|
||||
//! 带体的 POST,网关不需要自己实现 upstream。
|
||||
//!
|
||||
//! `data/api-proxies.json` 含平台真 Key,**敏感级别等同 `users.json`**。
|
||||
//! `data/api-proxies.json` 含供应商真 Key,**敏感级别等同 `users.json`**。
|
||||
|
||||
use ngx::core::Status;
|
||||
use ngx::ffi::{ngx_http_request_t, ngx_http_variable_value_t, ngx_int_t};
|
||||
@@ -43,7 +43,7 @@ use crate::util;
|
||||
pub const VAR_TARGET: usize = 1;
|
||||
/// `$apix_host`:上游 Host 头
|
||||
pub const VAR_HOST: usize = 2;
|
||||
/// `$apix_key`:平台 API Key(下行那把 `sk_` 到此为止,不往上游传)
|
||||
/// `$apix_key`:供应商 API Key(下行那把 `sk_` 到此为止,不往上游传)
|
||||
pub const VAR_KEY: usize = 3;
|
||||
/// `$apix_body`:由 query 拼出的调用体
|
||||
pub const VAR_BODY: usize = 4;
|
||||
@@ -51,7 +51,7 @@ pub const VAR_BODY: usize = 4;
|
||||
pub const VAR_PROBE_TARGET: usize = 5;
|
||||
pub const VAR_PROBE_BODY: usize = 6;
|
||||
|
||||
/// shm payload 内部分隔符:base / 平台 Key / asset_id 之间。
|
||||
/// shm payload 内部分隔符:base / 供应商 Key / asset_id 之间。
|
||||
///
|
||||
/// base 是 URL、key 与 asset_id 都是 token 类字符串,都不可能含换行。
|
||||
pub const PAYLOAD_SEP: char = '\n';
|
||||
@@ -85,7 +85,7 @@ pub fn validate_slug(raw: &str) -> Result<String, String> {
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// 市场基址:`http(s)://host`,允许尾随路径(市场挂在子路径下的情况)。
|
||||
/// 供应商基址:`http(s)://host`,允许尾随路径(供应商挂在子路径下的情况)。
|
||||
pub fn validate_base(raw: &str) -> Result<String, String> {
|
||||
let s = util::trim(raw).trim_end_matches('/').to_owned();
|
||||
if s.is_empty() {
|
||||
@@ -99,7 +99,7 @@ pub fn validate_base(raw: &str) -> Result<String, String> {
|
||||
} else if let Some(r) = s.strip_prefix("http://") {
|
||||
r
|
||||
} else {
|
||||
return Err("base 必须以 http:// 或 https:// 开头,例如 https://souyi.net.cn".to_owned());
|
||||
return Err("base 必须以 http:// 或 https:// 开头,例如 https://api.example.com".to_owned());
|
||||
};
|
||||
if rest.is_empty() || rest.split('/').next().unwrap_or("").is_empty() {
|
||||
return Err("base 缺少主机名".to_owned());
|
||||
@@ -110,7 +110,7 @@ pub fn validate_base(raw: &str) -> Result<String, String> {
|
||||
Ok(s)
|
||||
}
|
||||
|
||||
/// asset_id:市场那边的资产标识。宽进——各市场的命名规则不同,
|
||||
/// asset_id:供应商那边的资产标识。宽进——各供应商的命名规则不同,
|
||||
/// 这里只挡空白与控制字符(它要出现在 JSON 与 HTML 里)。
|
||||
fn validate_asset(raw: &str) -> Result<String, String> {
|
||||
let s = util::trim(raw).to_owned();
|
||||
@@ -153,8 +153,8 @@ fn check_params(raw: &[String]) -> Result<Vec<String>, String> {
|
||||
// 共享内存同步(写穿 / 装载)
|
||||
// ===========================================================================
|
||||
|
||||
fn payload_of(base: &str, key: &str, item: &ApiProxy) -> String {
|
||||
format!("{base}{PAYLOAD_SEP}{key}{PAYLOAD_SEP}{}", item.asset_id)
|
||||
fn payload_of(item: &ApiProxy) -> String {
|
||||
format!("{}{PAYLOAD_SEP}{}{PAYLOAD_SEP}{}", item.base, item.key, item.asset_id)
|
||||
}
|
||||
|
||||
/// 拆 payload:`base \n key \n asset_id`
|
||||
@@ -179,7 +179,7 @@ pub fn sync_shm(slug: &str, store: &ApiProxyStore) {
|
||||
state::remove(config::KEY_AX_PREFIX, slug.as_bytes());
|
||||
return;
|
||||
}
|
||||
let payload = payload_of(&store.base, &store.key, item);
|
||||
let payload = payload_of(item);
|
||||
if !state::put(config::KEY_AX_PREFIX, slug.as_bytes(), payload.as_bytes(), 0) {
|
||||
util::log_err(&format!(
|
||||
"[apix] 代理配置写共享内存失败 slug={slug} —— 该代理会 404(共享内存可能已满)"
|
||||
@@ -187,7 +187,7 @@ pub fn sync_shm(slug: &str, store: &ApiProxyStore) {
|
||||
}
|
||||
}
|
||||
|
||||
/// 全量重载代理表(启动装载 / 平台凭据变更后)。返回装载条数。
|
||||
/// 全量重载代理表(启动装载 / 供应商凭据变更后)。返回装载条数。
|
||||
pub fn reload_shm() -> usize {
|
||||
state::clear_prefix(config::KEY_AX_PREFIX);
|
||||
let data = store::read_api_proxies();
|
||||
@@ -198,7 +198,7 @@ pub fn reload_shm() -> usize {
|
||||
continue;
|
||||
}
|
||||
expected += 1;
|
||||
let payload = payload_of(&data.base, &data.key, item);
|
||||
let payload = payload_of(item);
|
||||
if state::put(config::KEY_AX_PREFIX, slug.as_bytes(), payload.as_bytes(), 0) {
|
||||
loaded += 1;
|
||||
}
|
||||
@@ -211,7 +211,7 @@ pub fn reload_shm() -> usize {
|
||||
loaded
|
||||
}
|
||||
|
||||
/// 热路径查表:`slug → (base, 平台Key, asset_id)`
|
||||
/// 热路径查表:`slug → (base, 供应商Key, asset_id)`
|
||||
pub fn lookup(slug: &str) -> Option<(String, String, String)> {
|
||||
let payload = state::get(config::KEY_AX_PREFIX, slug.as_bytes())?.0;
|
||||
let (base, key, asset) = split_payload(&payload);
|
||||
@@ -241,7 +241,7 @@ pub fn slug_of(r: *mut ngx_http_request_t) -> Option<String> {
|
||||
Some(slug.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
/// 从 `https://souyi.net.cn:443` 取出 `souyi.net.cn:443`
|
||||
/// 从 `https://api.example.com:443` 取出 `api.example.com:443`
|
||||
fn host_of(base: &str) -> &str {
|
||||
let rest = match base.find("://") {
|
||||
Some(i) => &base[i + 3..],
|
||||
@@ -290,14 +290,14 @@ fn clip(v: &str) -> &str {
|
||||
&v[..end]
|
||||
}
|
||||
|
||||
/// 由 query 拼出市场的调用体。
|
||||
/// 由 query 拼出供应商的调用体。
|
||||
///
|
||||
/// ```text
|
||||
/// ?q=nginx&format=json → {"asset_id":"searxng-search","call_data":{"q":"nginx","format":"json"}}
|
||||
/// ?prompt=你好 → {"asset_id":"minimax-m3","prompt":"你好","call_data":{}}
|
||||
/// ```
|
||||
///
|
||||
/// `prompt` 单独提到顶层:市场的 model 类资产(MiniMax-M3 等)把它当必填字段,
|
||||
/// `prompt` 单独提到顶层:供应商的 model 类资产(MiniMax-M3 等)把它当必填字段,
|
||||
/// 塞进 `call_data` 会被当成未知参数。其余参数一律进 `call_data`。
|
||||
pub fn build_body(asset_id: &str, args: &[(String, String)]) -> String {
|
||||
let mut call = String::new();
|
||||
@@ -386,7 +386,7 @@ pub extern "C" fn var_get(
|
||||
VAR_BODY => build_body_from_request(r, &asset),
|
||||
VAR_PROBE_BODY => {
|
||||
// 预估是**免费**的,且不真正执行资产——用它当连通性探针,
|
||||
// 响应里的 current_balance_usd 顺带把平台余额带回来
|
||||
// 响应里的 current_balance_usd 顺带把供应商余额带回来
|
||||
format!("{{\"asset_id\":{},\"max_tokens\":1}}", json_quote(&asset))
|
||||
}
|
||||
_ => return None,
|
||||
@@ -415,26 +415,25 @@ pub fn all() -> Vec<(String, ApiProxy)> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 客户端应当使用的调用地址。端口由调用方从请求 Host 头取,**不要写死**
|
||||
/// (部署在 88 时要带 `:88`,放在 443 反代后面时不能带)。
|
||||
pub fn call_url(slug: &str, params: &[String], port: &str) -> String {
|
||||
let mut url = format!("https://{}{port}{PUB_PREFIX}{slug}", config::LLM_PUBLIC_HOST);
|
||||
let mut first = true;
|
||||
for p in params {
|
||||
url.push(if first { '?' } else { '&' });
|
||||
first = false;
|
||||
url.push_str(p);
|
||||
url.push('=');
|
||||
}
|
||||
url
|
||||
/// 客户端应当使用的调用地址(base,不带 query)。端口由调用方从请求 Host 头取,
|
||||
/// **不要写死**(部署在 88 时要带 `:88`,放在 443 反代后面时不能带)。
|
||||
/// query 参数由前端按 `params` 拼一次(避免后端与前端各拼一次导致 `?q=?q=`)。
|
||||
pub fn call_url(slug: &str, port: &str) -> String {
|
||||
format!("https://{}{port}{PUB_PREFIX}{slug}", config::LLM_PUBLIC_HOST)
|
||||
}
|
||||
|
||||
/// 新增或覆盖一个代理条目。
|
||||
///
|
||||
/// `params = None` 表示保持原值(只改名字时不必回填参数清单)。
|
||||
/// `base` / `key` / `supplier` 同理:`None` 或空串都表示「保留原值」——
|
||||
/// 这样编辑时不必把密钥再抄一遍。新建时若填了空串仍为空,则报错
|
||||
/// (没有基址与密钥无法转发)。
|
||||
pub fn upsert(
|
||||
slug_raw: &str,
|
||||
asset_raw: &str,
|
||||
base_raw: Option<&String>,
|
||||
key_raw: Option<&String>,
|
||||
supplier_raw: Option<&String>,
|
||||
name: Option<&String>,
|
||||
desc: Option<&String>,
|
||||
params: Option<Vec<String>>,
|
||||
@@ -448,9 +447,45 @@ pub fn upsert(
|
||||
None => None,
|
||||
};
|
||||
|
||||
// base / key:空串视为「保留原值」,交给下方闭包按 existing 决定
|
||||
let new_base = match base_raw {
|
||||
Some(b) => {
|
||||
let b = util::trim(b);
|
||||
if b.is_empty() { None } else { Some(validate_base(&b)?) }
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let new_key = match key_raw {
|
||||
Some(k) => {
|
||||
let k = util::trim(k).to_owned();
|
||||
if k.is_empty() {
|
||||
None
|
||||
} else {
|
||||
if k.chars().count() > config::APIX_KEY_MAX_LEN {
|
||||
return Err(format!("供应商 Key 超过 {} 个字符", config::APIX_KEY_MAX_LEN));
|
||||
}
|
||||
Some(k)
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let key = slug.clone();
|
||||
let (item, snapshot) = store::update_api_proxies(move |data| {
|
||||
let existing = data.items.get(&key).cloned();
|
||||
let base = new_base
|
||||
.or_else(|| existing.as_ref().map(|e| e.base.clone()))
|
||||
.unwrap_or_default();
|
||||
let key_val = new_key
|
||||
.or_else(|| existing.as_ref().map(|e| e.key.clone()))
|
||||
.unwrap_or_default();
|
||||
if existing.is_none() && (base.is_empty() || key_val.is_empty()) {
|
||||
return Err("新建代理必须提供供应商基址与密钥".to_owned());
|
||||
}
|
||||
let supplier = match supplier_raw {
|
||||
Some(s) => util::trim(s).chars().take(config::APIX_NAME_MAX_LEN).collect(),
|
||||
None => existing.as_ref().map(|e| e.supplier.clone()).unwrap_or_default(),
|
||||
};
|
||||
let name = match name {
|
||||
Some(n) => util::trim(n).chars().take(config::APIX_NAME_MAX_LEN).collect(),
|
||||
None => existing.as_ref().map(|e| e.name.clone()).unwrap_or_default(),
|
||||
@@ -473,7 +508,7 @@ pub fn upsert(
|
||||
.filter(|&t| t > 0)
|
||||
.unwrap_or_else(util::now);
|
||||
|
||||
let item = ApiProxy { asset_id, name, desc, params, enabled, price_per_call: 0.0, price_in: 0.0, price_out: 0.0, note, created_at };
|
||||
let item = ApiProxy { asset_id, supplier, base, key: key_val, name, desc, params, enabled, note, created_at };
|
||||
data.items.insert(key.clone(), item.clone());
|
||||
Ok((item, data.clone()))
|
||||
})?;
|
||||
@@ -482,22 +517,6 @@ pub fn upsert(
|
||||
Ok(item)
|
||||
}
|
||||
|
||||
/// 更新条目上的**价格快照**(从市场目录同步下来的展示用单价)
|
||||
pub fn set_price(slug: &str, per_call: f64, pin: f64, pout: f64) {
|
||||
let key = slug.to_owned();
|
||||
let snapshot = store::update_api_proxies(move |data| {
|
||||
if let Some(it) = data.items.get_mut(&key) {
|
||||
it.price_per_call = per_call;
|
||||
it.price_in = pin;
|
||||
it.price_out = pout;
|
||||
}
|
||||
Ok(data.clone())
|
||||
});
|
||||
if let Ok(snap) = snapshot {
|
||||
sync_shm(slug, &snap);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove(slug_raw: &str) -> Result<String, String> {
|
||||
let slug = validate_slug(slug_raw)?;
|
||||
let key = slug.clone();
|
||||
@@ -511,88 +530,34 @@ pub fn remove(slug_raw: &str) -> Result<String, String> {
|
||||
Ok(slug)
|
||||
}
|
||||
|
||||
/// 设置市场基址与平台 Key。
|
||||
///
|
||||
/// `base = None` / `key = None` 表示**保持原值**;`Some("")` 表示显式清空
|
||||
/// (与 `upstreams::upsert` 的语义一致,避免"只想改 Key 却把 base 清了")。
|
||||
/// 改 Key 必须**重新同步全部条目**——凭据是每个条目 payload 的一部分,
|
||||
/// 漏同步的表现是「面板显示已保存,调用却还是用旧 Key」。
|
||||
pub fn set_platform(base_raw: Option<&String>, key_raw: Option<&String>) -> Result<ApiProxyStore, String> {
|
||||
let new_base = match base_raw {
|
||||
Some(b) => {
|
||||
let b = util::trim(b);
|
||||
// 显式空串 = 恢复默认市场,而不是"清空基址"(没有基址无从转发)
|
||||
if b.is_empty() {
|
||||
Some(config::APIX_BASE_DEFAULT.to_owned())
|
||||
} else {
|
||||
Some(validate_base(b)?)
|
||||
}
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let new_key = match key_raw {
|
||||
Some(k) => {
|
||||
let k = util::trim(k).to_owned();
|
||||
if k.chars().count() > config::APIX_KEY_MAX_LEN {
|
||||
return Err(format!("平台 Key 超过 {} 个字符", config::APIX_KEY_MAX_LEN));
|
||||
}
|
||||
Some(k)
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
|
||||
let data = store::update_api_proxies(move |d| {
|
||||
if let Some(b) = new_base {
|
||||
d.base = b;
|
||||
}
|
||||
if let Some(k) = new_key {
|
||||
d.key = k;
|
||||
}
|
||||
Ok(d.clone())
|
||||
})?;
|
||||
|
||||
reload_shm();
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// 对外投影
|
||||
// ===========================================================================
|
||||
|
||||
/// 转成管理台可见的字段。
|
||||
///
|
||||
/// **绝不回显完整平台 Key**——与 `upstreams::view` 同一理由:管理台页面会被
|
||||
/// 截图、被浏览器插件读取,回显真 Key 等于把市场余额摆在一个 HTML 里。
|
||||
/// **绝不回显完整供应商 Key**——与 `upstreams::view` 同一理由:管理台页面会被
|
||||
/// 截图、被浏览器插件读取,回显真 Key 等于把供应商余额摆在一个 HTML 里。
|
||||
/// `url` 只给 base 路径,query 参数由前端按 `params` 拼一次。
|
||||
pub fn view(slug: &str, item: &ApiProxy, port: &str) -> Value {
|
||||
json!({
|
||||
"slug": slug,
|
||||
"asset_id": item.asset_id,
|
||||
"supplier": item.supplier,
|
||||
"base": item.base,
|
||||
"name": item.name,
|
||||
"desc": item.desc,
|
||||
"params": item.params,
|
||||
"enabled": item.enabled,
|
||||
"price_per_call": item.price_per_call,
|
||||
"price_in": item.price_in,
|
||||
"price_out": item.price_out,
|
||||
"free": item.price_per_call <= 0.0 && item.price_in <= 0.0 && item.price_out <= 0.0,
|
||||
"key_set": !item.key.is_empty(),
|
||||
"key_mask": if item.key.is_empty() { "-".to_owned() } else { util::mask_key(&item.key) },
|
||||
"note": item.note,
|
||||
"created_at": item.created_at,
|
||||
"created_at_text": util::fmt_time(item.created_at),
|
||||
"url": call_url(slug, &item.params, port),
|
||||
"url": call_url(slug, port),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn view_all(list: &[(String, ApiProxy)], port: &str) -> Vec<Value> {
|
||||
list.iter().map(|(slug, it)| view(slug, it, port)).collect()
|
||||
}
|
||||
|
||||
/// 管理台列表接口的顶层信息:基址 + Key 掩码 + 是否可用
|
||||
pub fn platform_view() -> Value {
|
||||
let data = store::read_api_proxies();
|
||||
json!({
|
||||
"base": data.base,
|
||||
"key_set": !data.key.is_empty(),
|
||||
"key_mask": if data.key.is_empty() { "-".to_owned() } else { util::mask_key(&data.key) },
|
||||
"catalog_url": format!("{}/api/v1/assets", data.base),
|
||||
})
|
||||
}
|
||||
+11
-12
@@ -152,30 +152,29 @@ pub const TREND_DAYS_MAX: i64 = 90;
|
||||
pub const KEY_UH_PREFIX: &[u8] = b"uh:";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API 代理(apix):把外部 API 市场(aimall / 搜蚁智选)的资产挂到网关下
|
||||
// API 代理(apix):把外部供应商的 API 资产挂到网关下
|
||||
// ---------------------------------------------------------------------------
|
||||
//
|
||||
// 与 LLM 代理的关系:同一把 `sk_` 下行 Key、同一套限流与统计,
|
||||
// 但上游是「一个市场 + N 个资产」而不是「N 家厂商」,所以 slug 只映射到
|
||||
// `asset_id`,基址与平台 Key 是全局一份(见 `models::ApiProxyStore`)。
|
||||
// 但每条 apix 记录自带「基址 + 供应商 Key + 资产 id」——不同供应商互不影响
|
||||
// (见 `models::ApiProxyStore`),所以 slug 只映射到 `asset_id`。
|
||||
|
||||
/// shm 键前缀:slug → `base \n 平台Key \n asset_id`。
|
||||
/// shm 键前缀:slug → `base \n 供应商Key \n asset_id`。
|
||||
///
|
||||
/// 三行塞一个键是刻意的:热路径只查一次表就拿到转发所需全部信息。
|
||||
/// 代价是改平台凭据要重新同步全部条目(条目数是个位数,无所谓)。
|
||||
/// 代价是改某条凭据要重新同步该条目(条目数是个位数,无所谓)。
|
||||
pub const KEY_AX_PREFIX: &[u8] = b"ax:";
|
||||
|
||||
/// 市场基址默认值
|
||||
pub const APIX_BASE_DEFAULT: &str = "https://souyi.net.cn";
|
||||
/// 市场「调用资产」路径(`POST {base}{path}`,body = `{"asset_id":..,"call_data":{..}}`)
|
||||
/// 供应商「调用资产」路径(`POST {base}{path}`,body = `{"asset_id":..,"call_data":{..}}`)。
|
||||
/// 每条 apix 记录都按这个路径转发——它定义了该供应商接口所遵循的协议。
|
||||
pub const APIX_REQUEST_PATH: &str = "/api/v1/ai/request";
|
||||
/// 市场「费用预估」路径。**免费**,且响应里带平台余额——管理台的
|
||||
/// 「测试」按钮走它:既能验 Key 通不通,又能看到还剩多少钱,不花一分钱。
|
||||
/// 供应商「费用预估」路径。**免费**,且响应里带余额——管理台的
|
||||
/// 「测试」按钮走它:既能验 Key 通不通,又能看到还剩多少余额,不花一分钱。
|
||||
pub const APIX_ESTIMATE_PATH: &str = "/api/v1/ai/estimate";
|
||||
|
||||
/// slug 长度上限
|
||||
pub const APIX_SLUG_MAX_LEN: usize = 32;
|
||||
/// 市场基址长度上限
|
||||
/// 供应商基址长度上限
|
||||
pub const APIX_URL_MAX_LEN: usize = 200;
|
||||
/// 展示名 / 说明长度上限
|
||||
pub const APIX_NAME_MAX_LEN: usize = 64;
|
||||
@@ -188,7 +187,7 @@ pub const APIX_PARAM_MAX: usize = 16;
|
||||
pub const APIX_ARG_MAX: usize = 32;
|
||||
/// 单个参数值长度上限(bytes)
|
||||
pub const APIX_VAL_MAX: usize = 4096;
|
||||
/// 平台 Key 长度上限
|
||||
/// 供应商 Key 长度上限
|
||||
pub const APIX_KEY_MAX_LEN: usize = 128;
|
||||
/// 用量统计里 API 代理的 slot 前缀。
|
||||
///
|
||||
|
||||
+6
-6
@@ -20,7 +20,7 @@
|
||||
//! | --- | --- | --- | --- |
|
||||
//! | `*.yourdomain.com/*` | access | `ipass_proxy` | 查 `sub:` 决定后端 |
|
||||
//! | `llm.yourdomain.com/<slot>/*` | access | `ipass_llm` | 查 `ukey:` 鉴权 + `up:` 定上游 |
|
||||
//! | `llm.yourdomain.com/apix/<slug>` | access | `ipass_apix` | 同上鉴权,查 `ax:` 定市场资产 |
|
||||
//! | `llm.yourdomain.com/apix/<slug>` | access | `ipass_apix` | 同上鉴权,查 `ax:` 定供应商资产 |
|
||||
//! | `proxy-api.yourdomain.com/api/*` | content | `ipass_api` | 管理接口,读体后分发 |
|
||||
//!
|
||||
//! ## 关键实现约束(均为实测/查证确认,详见 CLAUDE.md)
|
||||
@@ -360,7 +360,7 @@ impl HttpRequestHandler for ApiProxyHandler {
|
||||
// 代理的**可见性**由管理员的启用/停用决定,不再叠一层账号白名单:
|
||||
// 白名单是给「一家厂商一个 slot」设计的,这里再套一层会让
|
||||
// 「管理员明明启用了、某账号却 403」变得难以解释。
|
||||
let Some((_base, platform_key, _asset)) = apix::lookup(&slug) else {
|
||||
let Some((_base, supplier_key, _asset)) = apix::lookup(&slug) else {
|
||||
return http::fail(
|
||||
r,
|
||||
HTTPStatus::NOT_FOUND,
|
||||
@@ -368,14 +368,14 @@ impl HttpRequestHandler for ApiProxyHandler {
|
||||
);
|
||||
};
|
||||
|
||||
if platform_key.is_empty() {
|
||||
if supplier_key.is_empty() {
|
||||
util::log_err(&format!(
|
||||
"[apix] 平台 Key 未配置,slug={slug} 无法转发 —— 请到管理台「API 代理」填写"
|
||||
"[apix] 供应商 Key 未配置,slug={slug} 无法转发 —— 请到管理台「API 代理」填写"
|
||||
));
|
||||
return http::fail(
|
||||
r,
|
||||
HTTPStatus::SERVICE_UNAVAILABLE,
|
||||
"平台 API Key 未配置,请联系管理员",
|
||||
"供应商 API Key 未配置,请联系管理员",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -567,7 +567,7 @@ struct ModuleConfig {
|
||||
api: bool,
|
||||
/// 该 location 走 LLM 代理(`/<slot>/...` → 上游)
|
||||
llm: bool,
|
||||
/// 该 location 走 API 代理(`/apix/<slug>` → 外部市场)
|
||||
/// 该 location 走 API 代理(`/apix/<slug>` → 外部供应商)
|
||||
apix: bool,
|
||||
}
|
||||
|
||||
|
||||
+20
-28
@@ -106,42 +106,41 @@ fn default_llm_daily() -> i64 {
|
||||
crate::config::LLM_DAILY_DEFAULT
|
||||
}
|
||||
|
||||
/// API 代理表(`api-proxies.json`):**一个文件同时承载平台凭据与代理清单**。
|
||||
/// API 代理表(`api-proxies.json`)。
|
||||
///
|
||||
/// 与 `llm-upstreams.json` 的区别:上游表是「一条记录 = 一家厂商(自带基址与
|
||||
/// 密钥)」,而 API 代理面对的是**同一个市场**(aimall / 搜蚁智选)——
|
||||
/// 所有资产共用一个基址、一把平台 Key,只有 `asset_id` 不同。
|
||||
/// 所以凭据放在文件顶层(`base` + `key`),`items` 里只放资产差异。
|
||||
/// 与 `llm-upstreams.json` 同构:每条记录 = 一个供应商(自带基址与密钥),
|
||||
/// 由 `slug` 区分。调用方访问 `/apix/<slug>?参数=值`,网关用本记录里的密钥
|
||||
/// 转发到供应商、并把响应原样返回。不同供应商彼此独立、互不耦合。
|
||||
///
|
||||
/// `key` 是平台真 Key,**敏感级别等同 `users.json`**(data/ 已 gitignore)。
|
||||
/// `key` 是供应商真 Key,**敏感级别等同 `users.json`**(data/ 已 gitignore)。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ApiProxyStore {
|
||||
/// 市场基址,如 `https://souyi.net.cn`
|
||||
#[serde(default = "default_apix_base")]
|
||||
pub base: String,
|
||||
/// 平台 API Key(`ak_...`)。留空 = 未配置,热路径直接 503
|
||||
#[serde(default)]
|
||||
pub key: String,
|
||||
/// slug → 资产映射
|
||||
/// slug → 代理映射
|
||||
#[serde(default)]
|
||||
pub items: BTreeMap<String, ApiProxy>,
|
||||
}
|
||||
|
||||
impl Default for ApiProxyStore {
|
||||
fn default() -> Self {
|
||||
Self { base: default_apix_base(), key: String::new(), items: BTreeMap::new() }
|
||||
Self { items: BTreeMap::new() }
|
||||
}
|
||||
}
|
||||
|
||||
fn default_apix_base() -> String {
|
||||
crate::config::APIX_BASE_DEFAULT.to_owned()
|
||||
}
|
||||
|
||||
/// 单个 API 代理条目。
|
||||
/// 单个 API 代理条目:指向某一家供应商的一个可调用的资产。
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ApiProxy {
|
||||
/// 市场侧的资产 id(如 `searxng-search`),决定钱花在哪个资产上
|
||||
/// 供应商侧的资产 id(如 `searxng-search`),决定具体调用哪个资产
|
||||
pub asset_id: String,
|
||||
/// 供应商名称(仅展示用,管理员自填,例如 `provider-x` / 客户自定)
|
||||
#[serde(default)]
|
||||
pub supplier: String,
|
||||
/// 供应商基址,如 `https://api.example.com`
|
||||
#[serde(default)]
|
||||
pub base: String,
|
||||
/// 供应商 API Key(`ak_...`)。留空 = 未配置,热路径直接 503。
|
||||
/// **敏感**:写盘与回显都按密钥处理,管理台只回显掩码。
|
||||
#[serde(default)]
|
||||
pub key: String,
|
||||
/// 展示名(中文)
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
@@ -152,18 +151,11 @@ pub struct ApiProxy {
|
||||
///
|
||||
/// 只用于给调用方看的文档(管理台把 `?q=关键词` 拼出来、账号态接口回显),
|
||||
/// 转发时**不按它过滤**——过滤要靠读请求体,而 access 阶段读不到。
|
||||
/// 市场侧自己会拒绝不认识的参数,拦在网关意义不大。
|
||||
/// 供应商侧自己会拒绝不认识的参数,拦在网关意义不大。
|
||||
#[serde(default)]
|
||||
pub params: Vec<String>,
|
||||
#[serde(default = "default_true")]
|
||||
pub enabled: bool,
|
||||
/// 单价(USD),从市场目录同步下来的快照,只用于展示
|
||||
#[serde(default)]
|
||||
pub price_per_call: f64,
|
||||
#[serde(default)]
|
||||
pub price_in: f64,
|
||||
#[serde(default)]
|
||||
pub price_out: f64,
|
||||
#[serde(default)]
|
||||
pub note: String,
|
||||
#[serde(default)]
|
||||
|
||||
+1
-1
@@ -19,7 +19,7 @@
|
||||
//! | `users.json` | 账号、口令哈希、API Key | `ukey:` 索引进(热路径要它) |
|
||||
//! | `domains.json` | 子域名 → 后端映射 | `sub:` 进(转发热路径) |
|
||||
//! | `llm-upstreams.json` | LLM 上游基址与密钥 | `up:` 进(LLM 转发热路径) |
|
||||
//! | `api-proxies.json` | API 市场凭据 + 代理清单 | `ax:` 进(API 代理热路径) |
|
||||
//! | `api-proxies.json` | API 代理清单(每条含各自供应商凭据) | `ax:` 进(API 代理热路径) |
|
||||
//!
|
||||
//! 四个文件都在 `data/` 下,都已 `.gitignore`。**LLM 上游表含上游真 Key,
|
||||
//! 敏感级别与 `users.json` 相同**,不要再往别处复制。
|
||||
|
||||
Reference in new issue
Block a user