From 9d9ac08968095b2f0de0bbd9a3e09ea7ac3bb9ef Mon Sep 17 00:00:00 2001 From: Robbs Luo Date: Wed, 2 Dec 2026 14:14:24 +0800 Subject: [PATCH 1/3] =?UTF-8?q?feat=20COD-32=EF=BC=9A=E6=96=B0=E5=A2=9E=20?= =?UTF-8?q?OpenAI=20=E5=85=BC=E5=AE=B9=20/v1/embeddings=20=E5=87=BA?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- PROPOSAL.md | 3 +- README.en.md | 19 +- README.md | 19 +- TECHNICAL.md | 6 +- src/api/embeddings.py | 52 +++++ src/api/model_merge.py | 11 +- src/compat/openai/embeddings.py | 118 +++++++++++ src/engine/executor.py | 127 ++++++++++++ src/main.py | 2 + src/provider/base.py | 11 + src/provider/zen/client.py | 101 ++++++++- tests/api/test_embeddings.py | 242 ++++++++++++++++++++++ tests/compat/test_openai_embeddings.py | 81 ++++++++ tests/engine/test_embeddings.py | 194 +++++++++++++++++ tests/provider/zen/test_client.py | 10 +- tests/provider/zen/test_console_parity.py | 24 ++- tests/provider/zen/test_embeddings.py | 76 +++++++ tests/provider/zen/test_provider.py | 21 ++ 18 files changed, 1094 insertions(+), 23 deletions(-) create mode 100644 src/api/embeddings.py create mode 100644 src/compat/openai/embeddings.py create mode 100644 tests/api/test_embeddings.py create mode 100644 tests/compat/test_openai_embeddings.py create mode 100644 tests/engine/test_embeddings.py create mode 100644 tests/provider/zen/test_embeddings.py diff --git a/PROPOSAL.md b/PROPOSAL.md index c1484020..41ebbaa0 100644 --- a/PROPOSAL.md +++ b/PROPOSAL.md @@ -14,6 +14,7 @@ - 不做通用 provider 网关——硬编码十渠道 + 一个可选的通用标准端点渠道 `generic`(部署者填 base_url);窄的海外 / IDE 系渠道按 §8 的优先级**逐条显式接入**,不做「任意 provider」抽象,也不引入 gRPC / protobuf / 客户端侧车。 - 不做**上游积分 → 货币**换算——各渠道积分互不通用,分开记流水;成本只按刊例价估算,USD 落库并按可配汇率另记 CNY 展示值。 - 不做数据迁移、自更新、mTLS;不做管理台与端口的 IP 限制(交给反向代理);不做全量请求审计。 +- 不做 **images / audio / rerank / video / realtime** 出口——本轮只补 `/v1/embeddings`(RAG / 知识库客户端的第一个必需端点),其余模态的模型即使在上游清单里也不注册、不展示,留给后续 issue。 ## 2. 上游事实与协议要点 @@ -44,7 +45,7 @@ 一个 FastAPI 进程内三平面,共享同一份 SQLite(WAL + `busy_timeout=5000`)与 Provider 客户端: -- **请求面**(API Key 鉴权):`/v1/chat/completions` · `/v1/completions` · `/v1/responses` · `/v1/messages` · `/v1/models` · `/v1/user/balance` → 协议层 → 执行引擎 → 中立事件流 → 十渠道 Provider。 +- **请求面**(API Key 鉴权):`/v1/chat/completions` · `/v1/completions` · `/v1/responses` · `/v1/messages` · `/v1/embeddings` · `/v1/models` · `/v1/user/balance` → 协议层 → 执行引擎 → 中立事件流 → 十渠道 Provider(向量只走实现了 `create_embeddings` 的渠道)。 - **管理面**(会话 Cookie + RBAC):React 管理台 → `/api/*`。 - **后台面**(无 HTTP 入口,`TaskRunner` 起 12 类循环):额度探测、token 预刷新、签到、成长、活跃上报、明细清理、备份、模型列表兜底刷新、模型探活、OpenRouter 目录刷新、运维告警、上游状态聚合。 diff --git a/README.en.md b/README.en.md index 817a2cd2..d39072fc 100644 --- a/README.en.md +++ b/README.en.md @@ -12,7 +12,7 @@ Ten upstream channels — **CodeBuddy** (China + international, two separate cha ## Features -- **Multi-protocol outbound**: `/v1/chat/completions` (stream / non-stream), `/v1/responses` (Codex CLI), `/v1/messages` (Claude Code), `/v1beta/models/{m}:generateContent` (Gemini SDK), `/v1/models`, `/v1/user/balance`, built-in retrieval `/v1/tools/search` + `/v1/fetch`. +- **Multi-protocol outbound**: `/v1/chat/completions` (stream / non-stream), `/v1/completions` (legacy text completion, routed through chat), `/v1/responses` (Codex CLI), `/v1/messages` (Claude Code), `/v1beta/models/{m}:generateContent` (Gemini SDK), `/v1/embeddings` (OpenAI Embeddings, non-stream, usable directly by RAG / knowledge-base clients), `/v1/models`, `/v1/user/balance`, built-in retrieval `/v1/tools/search` + `/v1/fetch`. - **Unified scheduling**: flat names pick a credential by health, `model@channel` forces one. Order: free channels → fewest in-flight → expiring quota → health + tiered cooldown → higher balance. Credential **weight** (`-1000..1000`) only reorders within the same health tier; catalog `x0` entries are calibrated by real charges from the last 24h. Model-level rate limits avoid only that model; multi-turn conversations stick to one credential until an error. - **Expiring quota first**: the primary window (default 36h) burns quota about to expire, ties broken by the 7-day window; units are credits throughout. - **Model list loaded from credentials**: only channels with a usable credential appear → no ghost models. The catalog is snapshotted to disk and ready on restart. @@ -134,13 +134,28 @@ curl http://127.0.0.1:8000/v1/chat/completions \ `model@channel` forces an upstream (`glm-5.2@trae`, `mimo-v2.5-free@zen`); omit it to auto-select. Any OpenAI-compatible client works (Base URL `http://127.0.0.1:8000/v1`). *Playground* uses your login session, no API key needed. +### Embeddings (`POST /v1/embeddings`) + +```bash +curl http://127.0.0.1:8000/v1/embeddings \ + -H "Authorization: Bearer sk-your-key" \ + -H "Content-Type: application/json" \ + -d '{"model":"text-embedding-3-small","input":["first","second"]}' +``` + +- `input` accepts a single string or an array of strings (a single string is normalized to an array at the edge); the response is `object=list` + `data[{index, embedding}]` + `usage.prompt_tokens`, same shape as OpenAI Embeddings. +- `encoding_format` (float only), `dimensions` and `user` are forwarded; `stream=true` and `encoding_format=base64` → 400 `invalid_request`. +- Auth, key / user quota layers, rate limiting, the credential pool and health scheduling, `model@channel` forcing and key→channel binding are all shared with the chat endpoints. One call counts as exactly one request per user / channel / model with tokens and list-price cost recorded; **inputs and vectors are never persisted**, and it takes no part in conversation affinity or response caching. +- Only channels that implement the upstream vector endpoint (currently Zen) are candidates; embedding models of other channels are not listed, so there are no "listed but always 400" entries. Zen's **anonymous free tier** does not list embeddings either (the upstream vector endpoint answers 401 without a key) — put an `api_key` in the credential to use the paid tier. +- **Explicitly out of scope this round**: images / audio / rerank / video / realtime (see the PROPOSAL non-goals). + ### Three model-name fields 1. **Raw id**: the key the channel actually sends, never rewritten (Qoder `kmodel_latest` = TRAE `kimi-k3-1`; Kilo may carry `kilo-auto/free`). 2. **Normalized key**: free-tier markers (`-free` / `free` path segment) and namespace prefixes (incl. Raccoon's `sn-`) stripped, then slugified. The list merges models by it. 3. **Display name**: human-readable (`LongCat 2.5 Preview`); used when upstream provides one, otherwise derived from the raw id with official brand casing. -`GET /v1/models` returns normalized keys as `id`; forwarding maps back to the raw id, visible as `by_provider.{channel}.raw_id`. **All three forms are requestable**; duplicates within one channel fall back to the raw id. Channels whose upstream exposes only snapshot-dated ids (CodeArts `deepseek-v4.1-flash-1017`) collapse the display name to the generic one at discovery time: the list shows a single `deepseek-v4.1-flash`, while forwarding still sends the snapshot id. Entries may carry `cost {input, output, cache_read}` (USD per million tokens) and `reasoning_efforts`. +`GET /v1/models` returns normalized keys as `id`; forwarding maps back to the raw id, visible as `by_provider.{channel}.raw_id`. **All three forms are requestable**; duplicates within one channel fall back to the raw id. Channels whose upstream exposes only snapshot-dated ids (CodeArts `deepseek-v4.1-flash-1017`) collapse the display name to the generic one at discovery time: the list shows a single `deepseek-v4.1-flash`, while forwarding still sends the snapshot id. Embedding entries additionally carry `type: "embedding"` (chat entries omit the field, so their historical shape is byte-identical), letting RAG clients filter for vector models. Entries may carry `cost {input, output, cache_read}` (USD per million tokens) and `reasoning_efforts`. - **Custom aliases** (`MODEL_ALIASES`, hot-reloadable): `alias=model@channel;alias2=model`, `@channel` optional. One shared table for listing and routing; entries carry `custom_alias: true`; collisions / missing targets / channels that don't hold the model are skipped with an ERROR. No alias chains. - **Single-model lookup** (`GET /v1/models/{id}`): accepts all three forms plus aliases, case-insensitive. Missing or not in the key allowlist → 404 (`model_not_found`) without leaking the pool. Both models routes accept `x-api-key` and `Authorization: Bearer`. diff --git a/README.md b/README.md index 3f025ff0..614f0098 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ ## 特性 -- **多协议出口**:`/v1/chat/completions`(流式 / 非流式)、`/v1/completions`(legacy 文本补全,内部转 chat)、`/v1/responses`(Codex CLI)、`/v1/messages`(Claude Code)、`/v1beta/models/{m}:generateContent`(Gemini SDK)、`/v1/models`、`/v1/user/balance`、内置检索 `/v1/tools/search` + `/v1/fetch`。 +- **多协议出口**:`/v1/chat/completions`(流式 / 非流式)、`/v1/completions`(legacy 文本补全,内部转 chat)、`/v1/responses`(Codex CLI)、`/v1/messages`(Claude Code)、`/v1beta/models/{m}:generateContent`(Gemini SDK)、`/v1/embeddings`(OpenAI Embeddings,非流式,RAG / 知识库客户端直接可用)、`/v1/models`、`/v1/user/balance`、内置检索 `/v1/tools/search` + `/v1/fetch`。 - **统一调度**:扁平名按健康度选号,`模型@渠道` 强制。优先级:免费渠道 → 在途最少 → 到期额度 → 健康度 + 分级冷却 → 余额多者。凭证**权重**(`-1000..1000`)只在同一健康档内重排;目录里的 x0 会被最近 24h 实测扣费校准。模型级限流只避让该模型;多轮对话粘同一凭证,出错才轮换。 - **到期额度优先**:主窗口(默认 36h)先烧将过期额度,打平再比 7 天窗口;单位统一积分。 - **模型列表按凭证加载**:只列有可用凭证的渠道 → 无幽灵模型。目录落盘,重启即用。 @@ -135,13 +135,28 @@ curl http://127.0.0.1:8000/v1/chat/completions \ `模型@渠道` 强制上游(`glm-5.2@trae`、`mimo-v2.5-free@zen`);不写自动选。任意 OpenAI 兼容客户端直连(Base URL `http://127.0.0.1:8000/v1`)。「Playground」用登录会话测,无需 API Key。 +### 向量化(`POST /v1/embeddings`) + +```bash +curl http://127.0.0.1:8000/v1/embeddings \ + -H "Authorization: Bearer sk-你的key" \ + -H "Content-Type: application/json" \ + -d '{"model":"text-embedding-3-small","input":["第一段","第二段"]}' +``` + +- `input` 收单个字符串或字符串数组(单字符串在入口归一成数组);返回 `object=list` + `data[{index, embedding}]` + `usage.prompt_tokens`,与 OpenAI Embeddings 同形。 +- 透传 `encoding_format`(只支持 `float`)、`dimensions`、`user`;`stream=true` 与 `encoding_format=base64` → 400 `invalid_request`。 +- 鉴权、Key / 用户双层配额、限流、凭证池与健康度调度、`模型@渠道` 强制与 Key 的渠道绑定完全复用 chat 出口;一次调用在按人 / 渠道 / 模型统计里各计 1 次请求并累加 token 与刊例价成本,**不落库输入文本与向量**,不参与对话粘性与响应缓存。 +- 只有实现了上游向量接口的渠道(当前 Zen)参与路由;其他渠道的 embedding 模型不会被列出来,避免「列表里有、调用必 400」。Zen 的**匿名免费档**也不列 embedding(上游向量端点对匿名档回 401),需在凭证里填 `api_key` 走付费档。 +- **本轮明确不做** images / audio / rerank / video / realtime(见 PROPOSAL 非目标)。 + ### 模型名三字段 1. **原代号**(`raw_id`):渠道真发的 key,永不改动(Qoder `kmodel_latest` = TRAE `kimi-k3-1`;Kilo 可带 `kilo-auto/free`)。 2. **归一键**:剥免费档标记(`-free` / `free` 路径段)与命名空间前缀(含小浣熊 `sn-`)→ slug 化。列表按它判同模型、合并;聚合身份键再**删掉多余的分隔符**(`-` / `_` / `.` / 空白)比较(`hy4flash` = `hy4-flash`、`kimi-k3-1-pro` = `kimi-k3.1-pro`),对外 id 仍保留原写法。 3. **展示名**:可读文本(`LongCat 2.5 Preview`);上游给就用,否则从原代号派生,品牌写法从官方。 -`GET /v1/models` 的 `id` 全是归一键;转发自动换回原代号,`by_provider.{渠道}.raw_id` 可见。**三种写法都能请求**(少写 / 多写 / 换分隔符也行,`hy4flash` ↔ `hy4-flash`、`kimi-k3-1-pro` ↔ `kimi-k3.1-pro`);同渠道内归一键重复 → 退回原代号。上游按快照日挂 id 的渠道(CodeArts 的 `deepseek-v4.1-flash-1017`)在发现阶段就把展示名收敛到通用名,列表里只有 `deepseek-v4.1-flash` 一条,转发仍发上游那条 id。条目可选带 `cost {input, output, cache_read}`(USD / 百万 token)与 `reasoning_efforts`。上下文 / 输出上限同值双发:本仓字段 `max_input_tokens` / `max_output_tokens` + OpenRouter 风格别名 `context_length` / `max_completion_tokens`(源字段缺省时不发别名)。 +`GET /v1/models` 的 `id` 全是归一键;转发自动换回原代号,`by_provider.{渠道}.raw_id` 可见。**三种写法都能请求**(少写 / 多写 / 换分隔符也行,`hy4flash` ↔ `hy4-flash`、`kimi-k3-1-pro` ↔ `kimi-k3.1-pro`);同渠道内归一键重复 → 退回原代号。上游按快照日挂 id 的渠道(CodeArts 的 `deepseek-v4.1-flash-1017`)在发现阶段就把展示名收敛到通用名,列表里只有 `deepseek-v4.1-flash` 一条,转发仍发上游那条 id。embedding 条目额外带 `type: "embedding"`(chat 条目不发该字段,历史形状逐字节不变),RAG 客户端可据此筛出向量模型。条目可选带 `cost {input, output, cache_read}`(USD / 百万 token)与 `reasoning_efforts`。上下文 / 输出上限同值双发:本仓字段 `max_input_tokens` / `max_output_tokens` + OpenRouter 风格别名 `context_length` / `max_completion_tokens`(源字段缺省时不发别名)。 - **自定义别名**(`MODEL_ALIASES`,可热更):`对外名=模型@渠道;对外名2=模型`,`@渠道` 可省。列表与请求解析共用一份,条目带 `custom_alias: true`;撞名 / 目标不存在 / 渠道不持有 → 该段 ERROR 跳过。无别名链。 - **按请求特征分档选模型**(`MODEL_TIER_RULES`,可热更):`档位[:参数]=模型;…`,档位 `background:512`(`max_tokens` ≤ 512 的标题 / 摘要类请求)、`think`(客户端显式要求思考)、`long_context:64000`(估算 prompt token 达阈值)。命中即把该请求解析到档位指定的模型(可带 `@渠道`),再照常走原选号流程——一次会话里的小请求不再与主推理吃同一档额度。目标模型在本部署无**可选**凭证(硬禁用 / 暂停 / 账号级模型白名单排除,与选号同口径)时回落原模型并记 warning;留空 = 不分档,行为与改动前逐请求一致。 diff --git a/TECHNICAL.md b/TECHNICAL.md index dc7dd295..5785b507 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -241,7 +241,7 @@ class Provider(Protocol): ``` - 与 `src/provider/base.py` 严格一致;凭证以 dict 传递(解密后的 `data_enc`),provider 不接触 sqlite。 -- **可选能力不实现即不定义**:调用方 `getattr` 探测,缺失 → 400「该凭证不支持此操作」。当前可选集:`start_auth`/`poll_auth`、`complete_callback`(仅 TRAE)、`list_accounts`/`switch_account`(仅 CB)、`credential_from`/`checkin_scope`、`checkin`/`checkin_status`、`growth`(仅 CB)、`host`、`model_list_source`(自带静态兜底表的渠道申报「本次是否降级 + 原因」)。 +- **可选能力不实现即不定义**:调用方 `getattr` 探测,缺失 → 400「该凭证不支持此操作」。当前可选集:`start_auth`/`poll_auth`、`complete_callback`(仅 TRAE)、`list_accounts`/`switch_account`(仅 CB)、`credential_from`/`checkin_scope`、`checkin`/`checkin_status`、`growth`(仅 CB)、`host`、`model_list_source`(自带静态兜底表的渠道申报「本次是否降级 + 原因」)、`create_embeddings`(仅 Zen:`POST /v1/embeddings` 的候选渠道判据,未实现的渠道不参与向量路由)。 - CodeBuddy / TRAE / Zen / Kilo / Qoder / OfficeAce 共用 `engine/sse.py`;CodeArts 自实现 `iter_data_lines`,只复用 `MAX_SSE_LINE_BYTES` / `SSEFrameTooLarge`。 ## 5. 各渠道协议实现 @@ -260,7 +260,7 @@ class Provider(Protocol): - 会话前缀照 `Identifier.create`:`ms * 0x1000 + 1`,按位取反,低 48 位写 12 位小写 hex。配置:`ZEN_OPENCODE_VERSION`、`ZEN_API_ENDPOINT`(受 `ZEN_ALLOWED_ENDPOINTS` 校验)、`ZEN_CLIENT_PROFILE`(`legacy` 默认 / `v2`)、`ZEN_MODELS_ROOT` / `ZEN_API_ROOT`(空 = 跟随对话根)、`ZEN_USER_AGENT`、`ZEN_GATE_TOOLS`(默认 `bash,read`)、`ZEN_PROBE_ENABLED`(默认 `false`);`v2` 额外发 client/project/session 副本与 b3/traceparent,并注入 `` system 块。 - **会话 id 稳定化**:`x-opencode-session` 由 `conversation_session_id(payload)` 生成——线索取 `engine.affinity.resolve_explicit`(`conversation_id` / `conversationId` / `prompt_cache_key` / 会话头),SHA-256 后 14 字节映射到 base62 作后缀,时间前缀按 `SESSION_TIME_BUCKET_SECONDS`(300s)取整。无线索返回 None → 回落每次新建(历史行为)。403 抖动重试显式换新 session(旧连接可能已被记住)。 -- **清单口径(2026-12-01 修订)**:`/zen/v1` 与 `/inference` 是同一网关,`/zen/v1` 只是别名根(`/zen/v1/openai/...` → 404)。清单是多模态目录,只留 `type=chat`;免费判定 = `-free` 后缀 **或** 零价(`big-pickle` 零价无后缀);展示名优先上游 `name`。付费档摘 `-free` + 零价,不探活。401 按正文分流:`Missing API key` → INVALID(匿名档模型要付费 key)、`Invalid credential` → DEAD(付费 key 失效)。`usage.cost` → `Usage.credit`,`opencode.estimated` → `credit_estimated`。 +- **清单口径(2026-12-01 修订)**:`/zen/v1` 与 `/inference` 是同一网关,`/zen/v1` 只是别名根(`/zen/v1/openai/...` → 404)。清单是多模态目录,只留 `type=chat` **与** `type=embedding`(后者供 `/v1/embeddings`,条目带 `model_type=embedding` → `/v1/models` 的 `type`),其余类型(decision / image / video / realtime / transcription)本轮无出口,一律剔除;免费判定 = `-free` 后缀 **或** 零价(`big-pickle` 零价无后缀);展示名优先上游 `name`。付费档摘 `-free` + 零价,不探活。401 按正文分流:`Missing API key` → INVALID(匿名档模型要付费 key)、`Invalid credential` → DEAD(付费 key 失效)。`usage.cost` → `Usage.credit`,`opencode.estimated` → `credit_estimated`。 - 实测 2026-12-01:匿名额度耗尽时 `429 FreeUsageLimitError` 在**身份校验之前**返回,缺失门禁头也一样——门禁伪装当前不是瓶颈,仍保留以兼容额度恢复后的形态要求。详见 `docs/zen-console-scan-2026-12-01.md`。 - **403 FreeTierError 客户端内消化**:退避 `GATE_403_RETRY_DELAY`(1s)换新 session id 重发,`GATE_403_RETRIES=1`,仍 403 才上抛。**注入空壳 + 改写 / 过滤**:有同义工具(`bash`→`shell`/`execute`、`read`→`read_file`)→ 注入名改写透传;无同义工具 → 整块丢弃 + WARNING;按 `index` 跟踪分片。 - **免费清单口径 + 探活默认关**:清单本身带 `type`/`cost`,`type=chat` + 零价/`-free` 即权威,默认按目录直接返回(`ZEN_PROBE_ENABLED=false`)。探活会对每个免费模型真发一次推理,而上游免费额度**按请求计**——每次刷新清单就把额度打光,真实对话因此恒 429(2026-12-01 实测:官方 CLI 直连 200,本仓同 key 同请求 429)。需要验真时才开;开启后只剔除 `PROBE_DEAD_STATUSES`(400/401/403/404),429 / 5xx / 超时保留,判活缓存 30 分钟。 @@ -518,7 +518,7 @@ PRAGMA foreign_keys = ON; -- 库里没有外键,关系全在应用层校验 ### 11.0 端点总览 -**外部(API Key)**:`POST /v1/chat/completions`(`n` 只接受 1)、`POST /v1/responses`、`POST /v1/messages` + `POST /v1/messages/count_tokens`、`POST /v1beta/models/{model}:{generateContent|streamGenerateContent|countTokens}` + `GET /v1beta/models`、`GET /v1/models` + `GET /v1/models/{id}`(对外 id / 展示名 / 任一渠道原 id 三种写法,不存在或不在 Key 白名单 → 404 `model_not_found`)、`GET /v1/usage?days=1|7|30`(只查本 Key 明细)、`GET /v1/user/balance`、`GET /health`、`GET /healthz`、`GET /metrics`。 +**外部(API Key)**:`POST /v1/chat/completions`(`n` 只接受 1)、`POST /v1/embeddings`(非流式,`input` 收字符串或字符串数组,仅 `encoding_format=float`)、`POST /v1/responses`、`POST /v1/messages` + `POST /v1/messages/count_tokens`、`POST /v1beta/models/{model}:{generateContent|streamGenerateContent|countTokens}` + `GET /v1beta/models`、`GET /v1/models` + `GET /v1/models/{id}`(对外 id / 展示名 / 任一渠道原 id 三种写法,不存在或不在 Key 白名单 → 404 `model_not_found`)、`GET /v1/usage?days=1|7|30`(只查本 Key 明细)、`GET /v1/user/balance`、`GET /health`、`GET /healthz`、`GET /metrics`。 **管理台(Cookie + RBAC)**:`/api/credentials`(`checkin` / `toggle` / `revive` / `probe` / `activity` / `pin` / `accounts/select` / `export` / `batch` / `batch-import` / `limits` / `tags` / `weight` / `login-secret` / `web-cookie`)、`/api/api-keys`、`/api/users`(`policy` / `disable` / `enable` / `reset-password`,**无 DELETE**)、`/api/model-catalog`、`/api/models/availability`、`/api/settings`、`/api/tasks` + `POST /api/tasks/{key}/run`、`/api/alerts` + `POST /api/alerts/{id}/resolve`、`/api/upstream-status`、`/api/stats/*`、`/api/billing`、`/api/logs` + `/api/logs/stream`、`/api/backups` + `/api/backups/restore`、`/api/nav-badges`、`/api/auth/*`、`/api/audit`、`GET /authorize`。列表端点统一 `sort` + `order`,未知键回落默认。 diff --git a/src/api/embeddings.py b/src/api/embeddings.py new file mode 100644 index 00000000..d11409bf --- /dev/null +++ b/src/api/embeddings.py @@ -0,0 +1,52 @@ +"""OpenAI 兼容出口:`POST /v1/embeddings`(非流式,RAG / 知识库客户端的第一步)。 + +与 chat 四协议共用**全部**治理面:API Key 鉴权、Key / 用户双层配额与限流、 +公共凭证池、健康度调度、`模型@渠道` 强制指定、Key 的渠道绑定与模型白名单、 +统计与成本估算。本出口只做三件自己的事: + +1. 形状校验(`compat.openai.embeddings`):`input` 单字符串 / 字符串数组, + 拒绝 `stream=true` 与 `encoding_format=base64`; +2. 白名单与配额准入(与 chat 同判据); +3. 把上游响应**原样**回给客户端(OpenAI Embeddings 形状)。 + +不做流式、不落库输入文本与向量、不参与对话粘性与响应缓存。 +""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends, Request +from fastapi.responses import JSONResponse + +from ..compat.openai.embeddings import parse_embedding_request +from ..key_quota import QuotaExceeded +from .deps import ApiKeyPrincipal, Services, api_key_user, read_json_body +from .endpoints import _admit_quota, ensure_model_allowed, quota_exceeded_response + + +def create_router(services: Services) -> APIRouter: + router = APIRouter() + executor = services.executor + settings = services.settings + + @router.post("/v1/embeddings") + async def embeddings(request: Request, + principal: ApiKeyPrincipal = Depends(api_key_user)): + body = await read_json_body(request) + embedding_request = parse_embedding_request(body) + # 投影成 ChatRequest 只为复用白名单与配额判据(TPM 按输入文本估算) + chat_request = embedding_request.as_chat_request() + ensure_model_allowed(chat_request, principal, settings) + # 配额准入在调用上游之前:超限返回 429 且不消耗任何上游额度 + try: + lease = _admit_quota(request, principal, chat_request) + except QuotaExceeded as error: + return quota_exceeded_response(error) + try: + result = await executor.create_embeddings( + chat_request, provider_binding=principal.provider_binding, + username=principal.username) + finally: + lease.release() + return JSONResponse(result) + + return router diff --git a/src/api/model_merge.py b/src/api/model_merge.py index 1b8c0dda..44f0d293 100644 --- a/src/api/model_merge.py +++ b/src/api/model_merge.py @@ -82,7 +82,7 @@ # 上游人类可读名(Qoder 的 `Qwen3.8-Max`),前端优先展示它而非内部代号。 _META_FIELDS = ("name", "credit_rate", "max_input_tokens", "max_output_tokens", "supports_images", "supports_tool_call", - "supports_reasoning", "default_effort") + "supports_reasoning", "default_effort", "model_type") # OpenRouter 风格别名 → 本仓字段(同值双发,内部模型不变)。OpenRouter 生态的 # 客户端(Claude Code 的 auto-compact 窗口、各家 SDK 的 max_completion_tokens) @@ -631,6 +631,13 @@ def _entry_response(entry: dict[str, Any], # 透传空串会让前端显示空模型名或多余的 `default_effort: ""`。 meta = {field: value for field, value in entry["meta"].items() if value is not None and value != ""} + # 能力类型对外用 OpenAI 习惯的 `type`:**只给 embedding 条目带上**, + # `chat` 不发。这样 chat 客户端(按 id / 名称筛选、或对未知字段零容忍的 + # 严格解析器)看到的历史条目与加这个字段前逐字节相同,而 RAG 客户端能 + # 靠 `type == "embedding"` 一眼挑出向量模型。多渠道条目任一渠道声明 + # embedding 即算 embedding(不让 chat 渠道把向量模型伪装成对话模型)。 + types = {detail.get("model_type") for detail in entry["provider_meta"].values()} + meta.pop("model_type", None) result: dict[str, Any] = { "id": entry["id"], "object": "model", "owned_by": "Coding2API", "providers": sorted(entry["providers"]), @@ -639,6 +646,8 @@ def _entry_response(entry: dict[str, Any], **{alias: meta[field] for alias, field in _META_ALIASES.items() if field in meta}, } + if "embedding" in types: + result["type"] = "embedding" if entry.get("custom_alias"): result["custom_alias"] = True result["alias_target"] = entry.get("alias_target", "") diff --git a/src/compat/openai/embeddings.py b/src/compat/openai/embeddings.py new file mode 100644 index 00000000..0cc474c0 --- /dev/null +++ b/src/compat/openai/embeddings.py @@ -0,0 +1,118 @@ +"""OpenAI Embeddings 入站解析(`POST /v1/embeddings`,非流式)。 + +只做**形状校验与归一**,不发请求:`input` 单字符串归一成单元素列表、显式 +拒绝 `stream=true` 与 `encoding_format=base64`(上游本仓只透传 float 向量, +接了 base64 等于把「上游可能不支持」变成运行期 500)。与 chat 出口同一套 +错误口径:任何不合规都抛 `InvalidRequest` → 400 `invalid_request`。 +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any + +from .request import ChatRequest, InvalidRequest + +# 上游 embeddings 的 `encoding_format` 取值。只放通 float:本项目透传上游 +# JSON,base64 需要额外的编解码契约,而上游是否支持并不统一(Zen 未声明)。 +SUPPORTED_ENCODING_FORMATS = frozenset({"float"}) + + +@dataclass(slots=True) +class EmbeddingRequest: + """归一后的 embedding 请求(`inputs` 恒为非空字符串列表)。""" + + model: str + inputs: list[str] + encoding_format: str + dimensions: int | None + user: str | None + # 转发给上游的原始体(已剔除本仓不支持的键,如 `stream`) + raw: dict[str, Any] + + def as_chat_request(self) -> ChatRequest: + """投影成 `ChatRequest`,复用白名单 / 配额 / 路由的既有判据。 + + `messages` 只用来做 TPM 预估(embedding 的输入就是待向量化的文本), + `stream` 恒 False——本出口不支持流式。 + """ + return ChatRequest(model=self.model, + messages=[{"role": "user", "content": text} + for text in self.inputs], + stream=False, raw=self.raw) + + +def parse_embedding_request(body: Any) -> EmbeddingRequest: + """校验并归一 `/v1/embeddings` 请求体。 + + 拒绝的形状与理由: + - `model` 缺失 / 非字符串 / 空串:embedding 没有「默认模型」可回退 + (默认模型是对话模型,拿它打 embeddings 必 400),入口显式报错; + - `input` 不是字符串或字符串数组、空数组、含空串:上游对空串的处置不 + 统一(有的 400、有的返回零向量),入口统一拒绝; + - `stream=true`:本出口非流式,接了也只能忽略,不如明确 400; + - `encoding_format` 非 `float`:见模块 docstring。 + """ + if not isinstance(body, dict): + raise InvalidRequest("request body must be a JSON object") + model = body.get("model") + if not isinstance(model, str) or not model.strip(): + raise InvalidRequest("model is required and must be a non-empty string") + inputs = _parse_input(body.get("input")) + if body.get("stream"): + raise InvalidRequest("stream is not supported for embeddings") + encoding_format = body.get("encoding_format") + if encoding_format is None: + encoding_format = "float" + if not isinstance(encoding_format, str) \ + or encoding_format not in SUPPORTED_ENCODING_FORMATS: + raise InvalidRequest( + f"encoding_format {encoding_format!r} is not supported " + f"(only {', '.join(sorted(SUPPORTED_ENCODING_FORMATS))})") + dimensions = _parse_dimensions(body.get("dimensions")) + user = body.get("user") + if user is not None and not isinstance(user, str): + raise InvalidRequest("user must be a string") + # 其余键原样透传(`user` / 厂商扩展),但丢掉本出口不支持的 `stream`。 + # NaN / ±Inf / `1e999` 已在 `read_json_body` 的 JSON 层拦下,这里不必重做。 + raw = {key: value for key, value in body.items() if key != "stream"} + # `input` 一并归一成数组:上游按条数回等长向量,单个字符串原样转发时 + # 上游要么 400、要么把字符串当字符序列(一条一条算),两种都不能要。 + raw["input"] = inputs + if dimensions is not None: + raw["dimensions"] = dimensions + raw["encoding_format"] = encoding_format + return EmbeddingRequest(model=model.strip(), inputs=inputs, + encoding_format=encoding_format, + dimensions=dimensions, user=user, raw=raw) + + +def _parse_input(value: Any) -> list[str]: + """`input` → 非空字符串列表(单字符串归一成单元素)。""" + if isinstance(value, str): + items: list[Any] = [value] + elif isinstance(value, list): + if not value: + raise InvalidRequest("input must not be an empty array") + items = value + else: + raise InvalidRequest("input must be a string or an array of strings") + texts: list[str] = [] + for index, item in enumerate(items): + if not isinstance(item, str): + raise InvalidRequest(f"input[{index}] must be a string") + if not item: + raise InvalidRequest(f"input[{index}] must not be an empty string") + texts.append(item) + return texts + + +def _parse_dimensions(value: Any) -> int | None: + """`dimensions` 可选;给了就必须是正整数(0 / 负数上游必拒)。""" + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int): + raise InvalidRequest("dimensions must be a positive integer") + if value <= 0: + raise InvalidRequest("dimensions must be a positive integer") + return value diff --git a/src/engine/executor.py b/src/engine/executor.py index 58f47bb6..2a88cba5 100644 --- a/src/engine/executor.py +++ b/src/engine/executor.py @@ -2124,6 +2124,133 @@ async def complete(self, request: ChatRequest, *, username: str = "unknown", raise NoHealthyCredential(self._unavailable_text(chain[0], None)) raise last_error + async def create_embeddings(self, request: ChatRequest, *, + provider_binding: str | None = None, + username: str = "unknown") -> dict[str, Any]: + """`POST /v1/embeddings` 的非流式执行(单一模型,不走回退链)。 + + 与 `complete` 共用选号 / 冷却 / 轮换 / 统计(一次调用恰好一行), + 区别只在出站调用与候选范围: + + - 候选只含声明了 `create_embeddings` 的渠道(`_embedding_providers`): + 向量与对话是不同的上游接口,没实现它的渠道一律不当候选,避免「拿 + chat 端点打 embedding 模型」白打一轮并误伤凭证健康度; + - 不参与对话粘性 / 精确响应缓存:embedding 请求不带会话,命中缓存会 + 凭空造出一次没发生的上游调用; + - 响应体原样返回(OpenAI 形状),用量取上游 `usage.prompt_tokens`, + 据此算成本;不落库输入文本与向量。 + + 错误口径与 chat 一致:所有上游都拒绝该模型 → 400,候选全在冷却 → 503。 + """ + target = self.resolve_target(request, provider_binding) + model = target.model + providers = self._embedding_providers(target) + if not providers: + raise InvalidRequest( + f"model {model!r} is not available for embeddings") + # 收窄到向量能力集后再走既有选号:`_select` 的 `_registered` 会与已注册 + # 渠道取交,故等价于「在支持向量的渠道里选号」,冷却 / 限额 / 在途判定 + # 全部复用,不另写一份。 + narrowed = replace(target, providers=providers) + tried: set[str] = set() + attempts = 0 + started = time.monotonic() + last_error: Exception | None = None + last_kind: ErrKind | None = None + attributed = False + last_provider = "-" + last_credential: str | None = None + with self._request_scope(model): + while True: + picked = await self._pick(narrowed, tried) + if picked is None: + if last_kind in REJECT_KINDS: + raise InvalidRequest(_reject_message(model, last_error)) + if not attributed: + self._deps.record( + username=username, + provider=self._attribution_provider(target, last_provider), + credential_id=last_credential, model=model, ok=False, + error_type=_failure_type(last_kind, last_error), + latency_ms=_elapsed_ms(started)) + raise NoHealthyCredential( + self._unavailable_text(target, last_error), + retry_after=self._recovery_seconds(target)) + credential_id, credential_data = picked + provider_id = self._deps.credentials.provider_of(credential_id) or "-" + last_provider, last_credential = provider_id, credential_id + attempts += 1 + # 引擎注入的「模型名 → 上游原 id」映射对 embedding 同样成立 + upstream_model = self._upstream_model(provider_id, model) + payload = dict(request.raw) + payload["model"] = upstream_model + self._lease(credential_id) + try: + result = await self._deps.providers[provider_id].create_embeddings( + credential_data, payload, upstream_model) + except Exception as error: # noqa: BLE001 + kind = _classify(error) + logger.warning("上游 %s embedding 失败(凭证 %s,kind=%s): %s", + provider_id, credential_id, kind, + _error_detail(error)) + last_error, last_kind = error, kind + if kind in REJECT_KINDS: + # 该上游不认这个模型:跳过**整个上游**(把所有凭证记进 + # tried),与 chat 路径的 `_skip_provider` 同口径。 + self._record_invalid(username, provider_id, credential_id, + model, started, error, kind) + tried.update(row.credential_id + for row in self._scope().all_rows([provider_id])) + if not self._deps.scheduler.should_rotate(attempts): + raise InvalidRequest( + _reject_message(model, error)) from error + continue + attributed = self._note_upstream_error( + credential_id, kind or ErrKind.OTHER, provider_id, model, + error, username=username, started=started) or attributed + if not self._deps.scheduler.should_rotate(attempts): + if not attributed: + self._deps.record( + username=username, provider=provider_id, + credential_id=credential_id, model=model, ok=False, + error_type=_failure_type(kind, error), + latency_ms=_elapsed_ms(started)) + raise NoHealthyCredential( + self._unavailable_text(target, error), + retry_after=self._recovery_seconds(target)) from error + continue + finally: + self._release(credential_id) + self._deps.credentials.save_success( + credential_id, model=self._model_scope(provider_id, model)) + self._confirm_probe(credential_id) + usage = result.get("usage") + usage = usage if isinstance(usage, dict) else {} + prompt_tokens = usage.get("prompt_tokens") + prompt_tokens = (prompt_tokens + if isinstance(prompt_tokens, int) + and not isinstance(prompt_tokens, bool) else None) + self._deps.record( + username=username, provider=provider_id, + credential_id=credential_id, model=model, ok=True, + input_tokens=prompt_tokens, + # 向量化没有「输出 token」:`total_tokens` 与输入的差额也 + # 不能记成 completion(会污染对话统计的产出比),统一记 0。 + output_tokens=0 if prompt_tokens is not None else None, + latency_ms=_elapsed_ms(started)) + return result + + def _embedding_providers(self, target: ModelTarget) -> tuple[str, ...]: + """当前可服务该模型向量的渠道(声明了 `create_embeddings` 的那些)。 + + 能力探测用 `getattr`:本仓十二个渠道里只有 zen 有向量接口,把方法改成 + `Provider` 协议的必选项就要给其余渠道补桩,而「补了但一调就 400」比 + 「没有这个能力」更难排查。 + """ + return tuple(pid for pid in target.providers + if callable(getattr(self._deps.providers.get(pid), + "create_embeddings", None))) + async def _complete_model(self, request: ChatRequest, target: ModelTarget, username: str, *, is_disconnected: Callable[[], Any] | None = None, diff --git a/src/main.py b/src/main.py index 9e0611fa..327b2ed0 100644 --- a/src/main.py +++ b/src/main.py @@ -39,6 +39,7 @@ balance, chat, completions, + embeddings, gemini, logs, messages, @@ -1216,6 +1217,7 @@ async def healthz(): app.include_router(activate.create_router(services)) app.include_router(chat.create_router(services)) app.include_router(completions.create_router(services)) + app.include_router(embeddings.create_router(services)) app.include_router(responses.create_router(services)) app.include_router(messages.create_router(services)) app.include_router(gemini.create_router(services)) diff --git a/src/provider/base.py b/src/provider/base.py index f2cf72ad..cc3028d1 100644 --- a/src/provider/base.py +++ b/src/provider/base.py @@ -949,6 +949,9 @@ class Model: supports_tool_call: bool | None = None # 推理元数据:两边上游的模型配置接口都直接给出,有则透传 supports_reasoning: bool | None = None + # 条目能力类型:缺省 `chat`;`embedding` 让 `/v1/models` 把它与对话模型 + # 区分开(RAG 客户端按 `type` 挑模型,chat 客户端也不会误选)。 + model_type: str = "chat" # 上游为该模型配置的默认档位(CB: reasoning.effort ∈ {high, medium}; # TRAE 的 reasoning_effort_config 只有 support_thinking 布尔,无档位,为 None) default_effort: str | None = None @@ -1016,6 +1019,14 @@ def classify(self, status: int, body: bytes) -> ErrKind: ... def list_models(self, credential_data: dict) -> list[Model]: ... async def aclose(self) -> None: ... + # 可选:`POST /v1/embeddings` 的转发(**不是**协议要求)。缺这个方法 + # 的渠道不参与 embedding 路由——`/v1/embeddings` 据此判断「这个模型能 + # 不能做向量化」,与 `list_models` 的 `model_type` 一起构成出口白名单。 + # 入参 `payload` 已由兼容层归一(`input` 恒为字符串数组),返回上游 + # OpenAI 形状的响应体,由出口原样透传。 + # async def create_embeddings(self, credential_data: dict, payload: dict, + # model: str) -> dict: ... + # 可选:`list_models` 的表来源申报(**不是**协议要求,缺省按上游真值处理)。 # 有静态兜底表的渠道(TRAE / CodeBuddy)实现它,返回 # `(是否降级, 一行原因)`;服务层据此把「这次拉到的其实是静态表」记成失败并 diff --git a/src/provider/zen/client.py b/src/provider/zen/client.py index c6acc0a0..15c9625b 100644 --- a/src/provider/zen/client.py +++ b/src/provider/zen/client.py @@ -66,6 +66,7 @@ ZEN_HOST = "https://opencode.ai" EP_CHAT = "/zen/v1/chat/completions" EP_MODELS = "/zen/v1/models" +EP_EMBEDDINGS = "/zen/v1/embeddings" # 门禁要求的 UA 版本下限;实测 1.18.0 及以上通过,1.17.9 返回 426 MIN_OPENCODE_VERSION = "1.18.0" # 门禁要求 tools 里必须出现的工具名(大小写敏感)。列表可经 @@ -352,9 +353,10 @@ def is_chat_model(item: dict[str, Any]) -> bool: """条目是否是对话模型(`type == "chat"`)。 清单是**多模态目录**:chat 之外还有 decision / embedding / image / video / - realtime / transcription。本项目出口只有 chat 四协议,其余模型选进来只会 - 400。`type` 缺失**或为空串**时按 chat 处理(旧清单没有这个字段,不能因此 - 清空渠道;空白值同样是「没声明」,不该当成「声明了非 chat」)。 + realtime / transcription。本项目出口只有 chat 四协议与 `/v1/embeddings`, + 其余模型选进来只会 400。`type` 缺失**或为空串**时按 chat 处理(旧清单 + 没有这个字段,不能因此清空渠道;空白值同样是「没声明」,不该当成 + 「声明了非 chat」)。 """ kind = item.get("type") if not isinstance(kind, str) or not kind.strip(): @@ -362,6 +364,32 @@ def is_chat_model(item: dict[str, Any]) -> bool: return kind.strip().lower() == "chat" +def model_type(item: dict[str, Any]) -> str: + """条目能力类型(本仓对外值只有 `chat` / `embedding`)。 + + 只认上游声明的 `type == "embedding"`,其余(chat / decision / image / + 缺失 / 空白)一律当 `chat`:入口只按 `embedding` 单独分流,未声明的旧 + 清单仍按历史口径当对话模型。 + """ + kind = item.get("type") + if isinstance(kind, str) and kind.strip().lower() == "embedding": + return "embedding" + return "chat" + + +def is_supported_model(item: dict[str, Any], *, embeddings: bool = True) -> bool: + """条目是否属于本仓**有出口**的类型(chat 四协议 + `/v1/embeddings`)。 + + decision / image / video / realtime / transcription 本轮不做,留在清单里 + 只会让 Playground 出现选了必 400 的条目。 + + `embeddings=False` 用于**匿名免费档**:向量端点不认匿名档(实测 + `/zen/v1/embeddings` 回 401 `Missing API key`),把 embedding 条目列进免费 + 清单就是幽灵模型——选得中、一调用必失败。带 Key 的付费档才放通。 + """ + return is_chat_model(item) or (embeddings and model_type(item) == "embedding") + + def is_free_model(item: dict[str, Any], free_suffix: str = FREE_MODEL_SUFFIX) -> bool: """条目在匿名免费层是否可用:`-free` 后缀**或**零价。 @@ -688,6 +716,15 @@ def _models_url(self, api_key: str = "") -> str: root = PAID_MODELS_ROOT if api_key else self.models_root return f"{self.host}{root}/models" + def _embeddings_url(self, api_key: str = "") -> str: + """向量端点:与对话同一根(付费 `/inference/openai/v1`,免费 `/zen/v1`)。 + + 免费层**不走 bridge**:侧车只实现了对话与清单两条路径,嵌一个不存在的 + `/v1/embeddings` 只会把「渠道不支持」变成 404 假象。 + """ + root = PAID_API_ROOT if api_key else self.api_root + return f"{self.host}{root}/embeddings" + def _gate_headers(self, api_key: str = "", *, session_id: str | None = None) -> dict[str, str]: """请求头:免费层门禁头 + 认证。 @@ -765,6 +802,37 @@ async def stream_chat(self, payload: dict[str, Any], model: str, yield event return + async def create_embeddings(self, payload: dict[str, Any], model: str, + api_key: str = "") -> dict[str, Any]: + """POST embeddings 并原样返回上游响应体(非流式)。 + + `payload` 的 `input` 已归一成字符串数组(`compat.openai.embeddings`), + 这里只管转发:模型名换成调用方要求的(兼容层已校验),其余键( + `encoding_format` / `dimensions` / `user`)透传。 + + 非 2xx 抛 `UpstreamHTTPError`,由 executor 按 `classify` 的分类冷却 / + 轮换——与 chat 出口同一套 429 / 5xx 映射。 + """ + body = dict(payload) + body["model"] = model + body.pop("stream", None) + response = await self._short.post( + self._embeddings_url(api_key), json=body, + headers=self._gate_headers(api_key)) + if response.status_code >= 400: + raise UpstreamHTTPError(response.status_code, + await base.read_body_bounded(response), + **base.retry_hints(response.headers)) + try: + data = response.json() + except ValueError as error: + raise zen_events.UpstreamProtocolViolation( + "non-JSON embeddings response") from error + if not isinstance(data, dict) or not isinstance(data.get("data"), list): + raise zen_events.UpstreamProtocolViolation( + "embeddings response missing data list") + return data + async def fetch_models(self, api_key: str = "") -> list[Model]: """GET 模型清单,只返回**免费候选**(探活确认不可用的才剔除)。 @@ -813,10 +881,11 @@ async def fetch_models(self, api_key: str = "") -> list[Model]: model_id = item.get("id") if not (isinstance(model_id, str) and model_id): continue - if not is_chat_model(item): + if not is_supported_model(item, embeddings=False): # 清单同时含 decision / embedding / image / video / realtime / - # transcription:本项目只做 chat 出口,混进来只会让 Playground - # 出现选了必 400 的条目(2026-12-01 实测 109 条里 27 条非 chat)。 + # transcription:免费档只有 chat 四协议可用(向量端点对匿名档 + # 回 401),其余类型混进来只会让 Playground 出现选了必 400 的 + # 条目(2026-12-01 实测 109 条里 27 条非 chat)。 continue if not is_free_model(item, self.free_suffix): continue @@ -826,7 +895,8 @@ async def fetch_models(self, api_key: str = "") -> list[Model]: # 排序时也天然排在最省的一档。 candidates.append(Model(id=model_id, name=model_name(item, self.free_suffix), - credit_rate=0.0)) + credit_rate=0.0, + model_type=model_type(item))) if not candidates: raise zen_events.UpstreamProtocolViolation("models api returned no free candidates") if not self.probe_enabled: @@ -912,13 +982,19 @@ async def _fetch_paid_models(self, api_key: str) -> list[Model]: continue if input_price(item) == 0: continue + if not is_supported_model(item): + # 付费档同样只注册本仓有出口的类型:image / video / rerank 等 + # 本轮不做(见 PROPOSAL 非目标),列进来只会误导客户端。 + continue # 上游付费清单带 `name`(免费清单也带),有就用;没有则从 id 派生, - # 保持与免费档同一套展示规则。 + # 保持与免费档同一套展示规则。`model_type` 让 `/v1/models` 给 + # embedding 条目带上 `type`,chat 客户端按原口径筛选不受影响。 name = item.get("name") models.append(Model( id=model_id, name=name.strip() if isinstance(name, str) and name.strip() - else pretty_model_name(model_id))) + else pretty_model_name(model_id), + model_type=model_type(item))) if not models: logger.info("zen 付费档无可用模型(账号未开通付费模型访问或余额为 0)") self._paid_models_cache = (time.monotonic(), list(models)) @@ -1048,6 +1124,13 @@ async def probe_quota(self, credential_data: dict) -> Quota: async def list_models(self, credential_data: dict) -> list[Model]: return await self.client.fetch_models(_api_key(credential_data)) + async def create_embeddings(self, credential_data: dict, payload: dict, + model: str) -> dict: + """`POST /v1/embeddings` 透传(`/inference/openai/v1/embeddings`)。""" + api_key = _api_key(credential_data) + async with paced(self.pacer, "zen"): + return await self.client.create_embeddings(payload, model, api_key) + async def stream_chat(self, credential_data: dict, payload: dict, model: str) -> AsyncIterator[Event]: api_key = _api_key(credential_data) diff --git a/tests/api/test_embeddings.py b/tests/api/test_embeddings.py new file mode 100644 index 00000000..04982b98 --- /dev/null +++ b/tests/api/test_embeddings.py @@ -0,0 +1,242 @@ +"""`POST /v1/embeddings` 端到端:鉴权、形状、错误口径、统计与模型目录。 + +上游替身(`EmbeddingProvider`)只实现向量接口;chat 替身照旧只有 +`stream_chat`——用来验证「没声明 create_embeddings 的渠道不当候选」。 +""" + +from __future__ import annotations + +import pytest +from fastapi.testclient import TestClient + +from src.config import Settings +from src.main import build_app +from src.provider.base import ErrKind, Model +from src.provider.trae.events import UpstreamProtocolViolation +from tests.helpers.constants import SECRET + +VECTOR = [0.1, -0.2, 0.3] + + +class RejectedModel(Exception): + """上游「不认识这个模型」的替身:`kind()` → INVALID(与真渠道同口径)。""" + + def kind(self): + return ErrKind.INVALID + + +class EmbeddingProvider: + """向量替身:`fail_with` 非空时抛它,否则按 `input` 条数回等长向量。""" + + id = "zen" + + def __init__(self) -> None: + self.calls: list[tuple[dict, dict, str]] = [] + self.fail_with: Exception | None = None + self.payload: list[dict] | None = None + + async def create_embeddings(self, credential_data, payload, model): + self.calls.append((credential_data, payload, model)) + if self.fail_with is not None: + raise self.fail_with + self.payload = payload + return { + "object": "list", + "data": [{"object": "embedding", "index": index, "embedding": VECTOR} + for index, _ in enumerate(payload["input"])], + "model": model, + "usage": {"prompt_tokens": 3, "total_tokens": 3}, + } + + async def list_models(self, _credential_data): + return [Model(id="emb", name="Emb", model_type="embedding"), + Model(id="glm-5.3", name="GLM 5.3")] + + def import_credential(self, raw): + if not raw.get("accessToken"): + raise UpstreamProtocolViolation("credential missing accessToken") + return dict(raw) + + def classify(self, status, body=b""): + return ErrKind.OTHER + + +@pytest.fixture() +def client(tmp_path): + settings = Settings(_env_file=None, APP_SECRET=SECRET, DATA_DIR=str(tmp_path), + ADMIN_USERNAMES="root") + provider = EmbeddingProvider() + app = build_app(settings, providers={"zen": provider}) + with TestClient(app) as test_client: + test_client.provider = provider + yield test_client + + +def _key(app, *, quota: str = "") -> dict[str, str]: + app.state.credentials.add(provider="zen", credential_data={"accessToken": "a"}) + created = app.state.api_keys.create("root", "test", quota=quota) + return {"Authorization": f"Bearer {created['api_key']}"} + + +def _events(app) -> list[dict]: + """直接读明细表(绕开 StatsQuery 的聚合口径,只断言落库的行)。""" + rows = app.state.services.key_usage._db.connect().execute( # noqa: SLF001 + "SELECT model, ok, error_type, input_tokens, output_tokens FROM usage_events " + "ORDER BY ts, rowid").fetchall() + return [dict(row) for row in rows] + + +def _body(**overrides): + payload = {"model": "emb", "input": ["a", "b"]} + payload.update(overrides) + return payload + + +def test_embeddings_requires_key(client): + response = client.post("/v1/embeddings", json=_body()) + assert response.status_code == 401 + assert response.json()["error"]["code"] == "invalid_api_key" + + +def test_embeddings_returns_vectors(client): + headers = _key(client.app) + response = client.post("/v1/embeddings", headers=headers, json=_body()) + assert response.status_code == 200, response.text + body = response.json() + assert body["object"] == "list" + assert len(body["data"]) == 2 + for index, item in enumerate(body["data"]): + assert item["index"] == index + assert isinstance(item["embedding"], list) + assert all(isinstance(value, float) for value in item["embedding"]) + assert body["usage"]["prompt_tokens"] > 0 + + +def test_embeddings_single_string_input(client): + headers = _key(client.app) + response = client.post("/v1/embeddings", headers=headers, + json=_body(input="solo")) + assert response.status_code == 200, response.text + assert len(response.json()["data"]) == 1 + # 上游收到的已归一成数组(单字符串在入口就归一,不让各渠道各写一份) + assert client.provider.payload["input"] == ["solo"] + + +def test_embeddings_records_usage_once(client): + headers = _key(client.app) + assert client.post("/v1/embeddings", headers=headers, + json=_body()).status_code == 200 + rows = [row for row in _events(client.app) if row["model"] == "emb"] + assert len(rows) == 1 + assert rows[0]["input_tokens"] == 3 + assert rows[0]["ok"] == 1 + assert rows[0]["error_type"] is None + + +@pytest.mark.parametrize(("payload", "fragment"), [ + ({"input": ["a"]}, "model is required"), + ({"model": "emb"}, "input must be a string"), + ({"model": "emb", "input": []}, "must not be an empty array"), + ({"model": "emb", "input": ["a", ""]}, "must not be an empty string"), + ({"model": "emb", "input": [1]}, "input[0] must be a string"), + ({"model": "emb", "input": "a", "stream": True}, "stream is not supported"), + ({"model": "emb", "input": "a", "encoding_format": "base64"}, + "encoding_format"), + ({"model": "emb", "input": "a", "dimensions": 0}, "positive integer"), + ({"model": "emb", "input": "a", "dimensions": "8"}, "positive integer"), + ({"model": " ", "input": "a"}, "model is required"), +]) +def test_embeddings_rejects_bad_shape(client, payload, fragment): + headers = _key(client.app) + response = client.post("/v1/embeddings", headers=headers, json=payload) + assert response.status_code == 400, response.text + error = response.json()["error"] + assert error["code"] == "invalid_request" + assert fragment in error["message"] + assert client.provider.calls == [] + + +def test_embeddings_rejects_uncovered_model(client): + """渠道没声明向量能力 → 400(不是 500,也不是白打一轮上游)。""" + headers = _key(client.app) + + class ChatOnly: + id = "kilo" + + async def stream_chat(self, *_args, **_kwargs): + yield None + + client.app.state.services.executor._deps.providers["kilo"] = ChatOnly() + response = client.post("/v1/embeddings", headers=headers, + json=_body(model="emb@kilo")) + assert response.status_code == 400, response.text + assert "not available for embeddings" in response.json()["error"]["message"] + assert client.provider.calls == [] + + +def test_embeddings_unknown_model_is_400(client): + headers = _key(client.app) + response = client.post("/v1/embeddings", headers=headers, + json=_body(model="emb@nope")) + assert response.status_code == 400 + assert response.json()["error"]["code"] == "invalid_request" + + +def test_embeddings_upstream_rejection_maps_to_400(client): + """上游拒绝该模型(INVALID)→ 400,且不冷却凭证。""" + headers = _key(client.app) + client.provider.fail_with = RejectedModel("model not found") + response = client.post("/v1/embeddings", headers=headers, json=_body()) + assert response.status_code == 400, response.text + assert response.json()["error"]["code"] == "invalid_request" + rows = _events(client.app) + assert [row["error_type"] for row in rows] == ["invalid_request"] + + +def test_embeddings_exhausted_credentials_is_503(client): + """不可分类的上游故障 → 轮换耗尽后 503(不出现裸 500 栈)。""" + headers = _key(client.app) + client.provider.fail_with = RuntimeError("boom") + response = client.post("/v1/embeddings", headers=headers, json=_body()) + assert response.status_code == 503, response.text + assert response.json()["error"]["code"] == "no_healthy_credential" + + +def test_embeddings_quota_exceeded_is_429(client): + """Key 配额超限 → 429,且不消耗任何上游调用。""" + headers = _key(client.app, quota='{"daily_requests": 1}') + assert client.post("/v1/embeddings", headers=headers, + json=_body()).status_code == 200 + client.provider.calls.clear() + response = client.post("/v1/embeddings", headers=headers, json=_body()) + assert response.status_code == 429 + assert response.json()["error"]["type"] == "quota_exceeded" + assert client.provider.calls == [] + + +def test_models_marks_embedding_type(client): + """`/v1/models` 给 embedding 条目带 `type`,chat 条目不带(保持原形状)。""" + headers = _key(client.app) + client.app.state.model_list_cache["zen"] = { + "emb": Model(id="emb", name="Emb", model_type="embedding"), + "glm-5.3": Model(id="glm-5.3", name="GLM 5.3"), + } + response = client.get("/v1/models", headers=headers) + assert response.status_code == 200, response.text + entries = {item["id"]: item for item in response.json()["data"]} + assert entries["emb"]["type"] == "embedding" + chat_entry = next(item for item in entries.values() if item["id"] != "emb") + assert "type" not in chat_entry + + +def test_models_hides_embedding_of_channel_without_credentials(client): + """幽灵模型 0 条:没可用凭证的渠道不出现它的 embedding 模型。""" + headers = _key(client.app) + client.app.state.model_list_cache["ghost"] = { + "ghost-emb": Model(id="ghost-emb", name="Ghost Emb", + model_type="embedding"), + } + response = client.get("/v1/models", headers=headers) + assert response.status_code == 200, response.text + ids = [item["id"] for item in response.json()["data"]] + assert "ghost-emb" not in ids diff --git a/tests/compat/test_openai_embeddings.py b/tests/compat/test_openai_embeddings.py new file mode 100644 index 00000000..a3de39e1 --- /dev/null +++ b/tests/compat/test_openai_embeddings.py @@ -0,0 +1,81 @@ +"""`/v1/embeddings` 入站解析:归一与拒绝口径(纯函数,不建 app)。""" + +from __future__ import annotations + +import pytest + +from src.compat.openai.embeddings import parse_embedding_request +from src.compat.openai.request import InvalidRequest + + +def _parse(**overrides): + body = {"model": "text-embedding-3-small", "input": ["a"]} + body.update(overrides) + return parse_embedding_request(body) + + +def test_single_string_input_is_normalized_to_array(): + """单字符串在入口就归一成数组(上游按条数回收,不能让它逐字符算)。""" + parsed = _parse(input="solo") + assert parsed.inputs == ["solo"] + assert parsed.raw["input"] == ["solo"] + assert parsed.encoding_format == "float" + assert parsed.raw["encoding_format"] == "float" + assert parsed.dimensions is None and parsed.user is None + + +def test_optional_fields_pass_through(): + parsed = _parse(dimensions=8, user="u1") + assert parsed.dimensions == 8 + assert parsed.raw["dimensions"] == 8 + assert parsed.raw["user"] == "u1" + + +def test_stream_and_base64_are_rejected(): + with pytest.raises(InvalidRequest, match="stream is not supported"): + _parse(stream=True) + with pytest.raises(InvalidRequest, match="encoding_format"): + _parse(encoding_format="base64") + with pytest.raises(InvalidRequest, match="encoding_format"): + _parse(encoding_format=1) + + +def test_user_must_be_string(): + with pytest.raises(InvalidRequest, match="user must be a string"): + _parse(user=3) + + +def test_dimensions_must_be_positive_int(): + with pytest.raises(InvalidRequest, match="positive integer"): + _parse(dimensions=True) + with pytest.raises(InvalidRequest, match="positive integer"): + _parse(dimensions=-3) + + +@pytest.mark.parametrize(("value", "fragment"), [ + (None, "must be a string or an array of strings"), + ([], "must not be an empty array"), + ([1], r"input\[0\] must be a string"), + ([""], r"input\[0\] must not be an empty string"), +]) +def test_input_shape_errors(value, fragment): + with pytest.raises(InvalidRequest, match=fragment): + _parse(input=value) + + +@pytest.mark.parametrize("model", [None, "", " ", 7]) +def test_model_is_required(model): + with pytest.raises(InvalidRequest, match="model is required"): + _parse(model=model) + + +def test_body_must_be_object(): + with pytest.raises(InvalidRequest, match="JSON object"): + parse_embedding_request(["nope"]) + + +def test_chat_projection_uses_inputs_as_user_turns(): + """投影成 ChatRequest 只为复用白名单与 TPM 预估。""" + chat = _parse(input=["a", "b"]).as_chat_request() + assert chat.stream is False + assert [m["content"] for m in chat.messages] == ["a", "b"] diff --git a/tests/engine/test_embeddings.py b/tests/engine/test_embeddings.py new file mode 100644 index 00000000..ff086f53 --- /dev/null +++ b/tests/engine/test_embeddings.py @@ -0,0 +1,194 @@ +"""`Executor.create_embeddings` 的分支:无向量渠道、轮换耗尽、上游拒绝。 + +端到端形状已由 `tests/api/test_embeddings.py` 覆盖,这里专测执行层里那些 +**API 层走不到**的分支(多凭证轮换、`NoProviderForModel` 兜底、DEAD 尝试行 +已落则不重复记账)。 +""" + +from __future__ import annotations + +import pytest + +from src.compat.openai.request import InvalidRequest +from src.db.conn import Database +from src.db.crypto import CredentialCipher +from src.db.migrate import apply_schema +from src.db.repo import CredentialRepository +from src.engine.executor import ( + Executor, + ExecutorDeps, + NoHealthyCredential, +) +from src.engine.scheduler import Scheduler +from src.provider.base import ErrKind +from tests.helpers.chat import chat_request as _request +from tests.helpers.constants import SECRET + + +class Rejected(Exception): + def kind(self) -> ErrKind: + return ErrKind.INVALID + + +class Dead(Exception): + def kind(self) -> ErrKind: + return ErrKind.DEAD + + +class EmbeddingProvider: + """向量替身:脚本里每项是异常类或响应 dict(越界重复最后一项)。""" + + id = "zen" + + def __init__(self, script) -> None: + self.script = script + self.calls = 0 + + async def create_embeddings(self, _credential_data, payload, model): + index = min(self.calls, len(self.script) - 1) + self.calls += 1 + item = self.script[index] + if isinstance(item, Exception): + raise item + return item + + def list_models(self, _credential_data): + return [] + + +class ChatOnlyProvider: + id = "trae" + + async def stream_chat(self, *_args, **_kwargs): + yield None + + +OK = {"object": "list", "data": [], "usage": {"prompt_tokens": 0}} + + +@pytest.fixture() +def credentials(tmp_path): + db = Database(tmp_path / "emb.sqlite3") + apply_schema(db.connect()) + repository = CredentialRepository(db, CredentialCipher(SECRET)) + yield repository + db.close() + + +def _executor(credentials, providers, **kwargs): + kwargs.setdefault("scheduler", Scheduler()) + return Executor(ExecutorDeps(providers=providers, credentials=credentials, + default_model="glm-5.2", **kwargs)) + + +async def test_create_embeddings_requires_vector_channel(credentials): + """一个声明了向量的渠道都没有 → 400,不落在「无可用凭证」的 503 上。""" + credentials.add(provider="trae", credential_data={"accessToken": "a"}) + executor = _executor(credentials, {"trae": ChatOnlyProvider()}) + with pytest.raises(InvalidRequest, match="not available for embeddings"): + await executor.create_embeddings(_request(model="glm-5.2")) + + +async def test_create_embeddings_binding_to_chat_only_channel_is_400(credentials): + """Key 绑定到没有向量能力的渠道 → 400(`@渠道` 同理,见 API 层用例)。""" + credentials.add(provider="trae", credential_data={"accessToken": "a"}) + executor = _executor(credentials, {"trae": ChatOnlyProvider()}) + with pytest.raises(InvalidRequest, match="not available for embeddings"): + await executor.create_embeddings(_request(model="glm-5.2"), + provider_binding="trae") + + +async def test_create_embeddings_rotates_to_second_credential(credentials): + """第一个号判死 → 换号后成功,且只有成功那一次落统计行。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + credentials.add(provider="zen", credential_data={"api_key": "b"}) + records: list[dict] = [] + executor = _executor(credentials, {"zen": EmbeddingProvider([Dead(), OK])}, + stats=type("S", (), {"record": lambda _self, **kw: + records.append(kw)})()) + result = await executor.create_embeddings(_request(model="emb")) + assert result == OK + # DEAD 先落一条尝试行(ok=False),成功后落成功行——共两条,分属两个号 + assert [row["ok"] for row in records] == [False, True] + assert records[-1]["input_tokens"] == 0 + + +async def test_create_embeddings_exhausted_rotation_raises_503(credentials): + """唯一可用号持续失败(轮换预算耗尽)→ 503,只落一条收尾行。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + records: list[dict] = [] + executor = _executor(credentials, {"zen": EmbeddingProvider([RuntimeError("x")])}, + stats=type("S", (), {"record": lambda _self, **kw: + records.append(kw)})()) + with pytest.raises(NoHealthyCredential): + await executor.create_embeddings(_request(model="emb")) + assert [row["ok"] for row in records] == [False] + assert records[0]["error_type"] is not None + + +async def test_create_embeddings_invalid_after_budget_raises_400(credentials): + """轮换预算耗尽时最后一类错误是 INVALID → 400(不是 503)。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + executor = _executor(credentials, {"zen": EmbeddingProvider([Rejected()])}) + with pytest.raises(InvalidRequest, match="not available on any configured upstream"): + await executor.create_embeddings(_request(model="emb")) + + +async def test_create_embeddings_dead_attempt_row_is_not_duplicated(credentials): + """DEAD 尝试行已落库 → 耗尽时不再追加收尾行(一次请求一行)。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + records: list[dict] = [] + executor = _executor(credentials, {"zen": EmbeddingProvider([Dead()])}, + stats=type("S", (), {"record": lambda _self, **kw: + records.append(kw)})()) + with pytest.raises(NoHealthyCredential): + await executor.create_embeddings(_request(model="emb")) + # DEAD 的尝试行由 `_note_upstream_error` 落,收尾行被 `attributed` 跳过 + assert len(records) == 1 + + +async def test_create_embeddings_without_selectable_credential_is_503(credentials): + """池里一个可选凭证都没有(首轮选号即 None)→ 503 + 一条收尾行。""" + # 一个凭证都不加:渠道有向量能力,但池里没有可选号 + records: list[dict] = [] + executor = _executor(credentials, {"zen": EmbeddingProvider([OK])}, + stats=type("S", (), {"record": lambda _self, **kw: + records.append(kw)})()) + with pytest.raises(NoHealthyCredential): + await executor.create_embeddings(_request(model="emb")) + assert [row["ok"] for row in records] == [False] + + +async def test_create_embeddings_rejected_with_no_rotation_budget_is_400(credentials): + """轮换预算只有 1:单次 INVALID 直接 400(不落到「无可用凭证」)。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + executor = _executor(credentials, {"zen": EmbeddingProvider([Rejected()])}, + scheduler=Scheduler(max_rotate=1)) + with pytest.raises(InvalidRequest, match="not available on any configured upstream"): + await executor.create_embeddings(_request(model="emb")) + + +async def test_create_embeddings_dead_with_no_rotation_budget_skips_final_row( + credentials): + """预算 1 且已落过 DEAD 尝试行:收尾行被跳过(一次请求一行)。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + records: list[dict] = [] + executor = _executor(credentials, {"zen": EmbeddingProvider([Dead()])}, + scheduler=Scheduler(max_rotate=1), + stats=type("S", (), {"record": lambda _self, **kw: + records.append(kw)})()) + with pytest.raises(NoHealthyCredential): + await executor.create_embeddings(_request(model="emb")) + assert len(records) == 1 + + +async def test_create_embeddings_no_usage_keeps_tokens_null(credentials): + """上游没给 usage:token 记 NULL(不拿 0 冒充「零用量」)。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + records: list[dict] = [] + executor = _executor(credentials, {"zen": EmbeddingProvider([{"data": []}])}, + stats=type("S", (), {"record": lambda _self, **kw: + records.append(kw)})()) + assert await executor.create_embeddings(_request(model="emb")) == {"data": []} + assert records[0]["input_tokens"] is None + assert records[0]["output_tokens"] is None diff --git a/tests/provider/zen/test_client.py b/tests/provider/zen/test_client.py index 31235961..61670f58 100644 --- a/tests/provider/zen/test_client.py +++ b/tests/provider/zen/test_client.py @@ -527,19 +527,25 @@ def handler(request: httpx.Request) -> httpx.Response: return httpx.Response(200, json={"data": [ {"id": "gpt-6-luna", "name": "GPT 6 Luna"}, {"id": "deepseek-v4.1-flash", "name": " "}, + {"id": "text-embedding-3-small", "type": "embedding"}, + {"id": "img-1", "type": "image"}, # 本轮无出口 → 不注册 {"id": ""}, "junk", ]}) client = _client(handler) models = await client.fetch_models("sk-zen") - assert [m.id for m in models] == ["gpt-6-luna", "deepseek-v4.1-flash"] + assert [m.id for m in models] == ["gpt-6-luna", "deepseek-v4.1-flash", + "text-embedding-3-small"] assert models[0].name == "GPT 6 Luna" assert models[1].name == "DeepSeek V4.1 Flash" # 无 name → 从 id 派生 + # 付费档才注册 embedding,且带能力类型(/v1/models 的 `type` 来源) + assert [m.model_type for m in models] == ["chat", "chat", "embedding"] assert calls == [f"{PAID_MODELS_ROOT}/models"] # 没有逐个探活 again = await client.fetch_models("sk-zen") - assert [m.id for m in again] == ["gpt-6-luna", "deepseek-v4.1-flash"] + assert [m.id for m in again] == ["gpt-6-luna", "deepseek-v4.1-flash", + "text-embedding-3-small"] assert len(calls) == 1 # 命中付费档缓存 await client.aclose() diff --git a/tests/provider/zen/test_console_parity.py b/tests/provider/zen/test_console_parity.py index 7c34026f..fa1ebfa8 100644 --- a/tests/provider/zen/test_console_parity.py +++ b/tests/provider/zen/test_console_parity.py @@ -175,14 +175,15 @@ def handler(request: httpx.Request) -> httpx.Response: async def test_fetch_models_filters_type_and_picks_zero_price(): - """只有 chat 且免费(后缀或零价)的条目进列表;名称用上游 name。""" + """chat 与 embedding 免费条目进列表(带能力类型);其余类型与付费条目不进。""" def handler(request: httpx.Request) -> httpx.Response: if request.url.path == EP_MODELS: return httpx.Response(200, json={"data": [ CHAT_FREE, # 零价无后缀 → 保留 CHAT_PAID, # 付费 → 剔除 - DECISION_FREE, # 非 chat → 剔除 - {"id": "emb-free", "type": "embedding"}, # 非 chat → 剔除 + DECISION_FREE, # 无出口 → 剔除 + {"id": "emb-free", "type": "embedding"}, # 匿名档无向量 → 剔除 + {"id": "img-free", "type": "image"}, # images 本轮不做 → 剔除 {"id": "alpha-free", "name": "Alpha Free"}, # 后缀 → 保留 "junk", # 非 dict 跳过 ]}) @@ -191,6 +192,23 @@ def handler(request: httpx.Request) -> httpx.Response: models = await _client(handler).fetch_models() assert [m.id for m in models] == ["big-pickle", "alpha-free"] assert [m.name for m in models] == ["Big Pickle", "Alpha Free"] + assert [m.model_type for m in models] == ["chat", "chat"] + + +def test_model_type_only_recognizes_declared_embedding(): + """`model_type` 只认上游声明的 embedding,其余(含未知类型)一律 chat。""" + from src.provider.zen.client import is_supported_model, model_type + + assert model_type({"id": "e", "type": "EMBEDDING"}) == "embedding" + assert model_type({"id": "c", "type": "chat"}) == "chat" + assert model_type({"id": "x"}) == "chat" + assert model_type({"id": "i", "type": "image"}) == "chat" + assert is_supported_model({"id": "i", "type": "image"}) is False + assert is_supported_model({"id": "e", "type": "embedding"}) is True + # 匿名免费档不认向量端点,embedding 条目在该档下不注册(无幽灵模型) + assert is_supported_model({"id": "e", "type": "embedding"}, + embeddings=False) is False + assert is_supported_model({"id": "x"}, embeddings=False) is True # ------------------------------------------------------------- 401 两套语义 diff --git a/tests/provider/zen/test_embeddings.py b/tests/provider/zen/test_embeddings.py new file mode 100644 index 00000000..9de966ea --- /dev/null +++ b/tests/provider/zen/test_embeddings.py @@ -0,0 +1,76 @@ +"""`ZenClient.create_embeddings`:端点选择、透传形状、错误与协议违规。""" + +from __future__ import annotations + +import json + +import httpx +import pytest + +from src.provider.base import UpstreamProtocolViolation +from src.provider.zen.client import EP_EMBEDDINGS, PAID_API_ROOT, UpstreamHTTPError +from tests.provider.zen._support import client as _client + +pytestmark = pytest.mark.real_upstream("zen") + +BODY = {"object": "list", + "data": [{"object": "embedding", "index": 0, "embedding": [0.1, 0.2]}], + "usage": {"prompt_tokens": 2, "total_tokens": 2}} + + +async def test_create_embeddings_posts_normalized_input(): + """免费档打 `/zen/v1/embeddings`,`input` 原样数组、`stream` 不转发。""" + seen: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + return httpx.Response(200, json=BODY) + + result = await _client(handler).create_embeddings( + {"input": ["a", "b"], "stream": True}, "text-embedding-3-small") + assert result == BODY + assert seen[0].url.path == EP_EMBEDDINGS + assert json.loads(seen[0].content) == {"input": ["a", "b"], + "model": "text-embedding-3-small"} + # 匿名档不带自己的 Key(Authorization 只由测试替身的连接池默认头提供) + assert seen[0].headers["authorization"] != "Bearer sk-x" + + +async def test_create_embeddings_paid_root_and_auth(): + """带 Key = 付费档:换到 `/inference/openai/v1` 并带 Bearer。""" + seen: list[httpx.Request] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append(request) + return httpx.Response(200, json=BODY) + + await _client(handler).create_embeddings({"input": ["a"]}, "emb", "sk-1") + assert seen[0].url.path == f"{PAID_API_ROOT}/embeddings" + assert seen[0].headers["Authorization"] == "Bearer sk-1" + + +async def test_create_embeddings_maps_upstream_errors(): + """非 2xx 抛 `UpstreamHTTPError`(带 Retry-After 线索),由 executor 分类。""" + def handler(_request: httpx.Request) -> httpx.Response: + return httpx.Response(429, headers={"Retry-After": "7"}, + json={"error": {"message": "slow down"}}) + + with pytest.raises(UpstreamHTTPError) as caught: + await _client(handler).create_embeddings({"input": ["a"]}, "emb") + assert caught.value.status == 429 + assert caught.value.retry_after_seconds == 7 + + +@pytest.mark.parametrize("payload", [ + {"not": "json"}, + {"data": "not-a-list"}, +]) +async def test_create_embeddings_rejects_bad_upstream_shape(payload): + """上游形状不符(非 JSON / 缺 data 数组):协议违规而不是 200 空响应。""" + def handler(_request: httpx.Request) -> httpx.Response: + if payload == {"not": "json"}: + return httpx.Response(200, text="not-json") + return httpx.Response(200, json=payload) + + with pytest.raises(UpstreamProtocolViolation): + await _client(handler).create_embeddings({"input": ["a"]}, "emb") diff --git a/tests/provider/zen/test_provider.py b/tests/provider/zen/test_provider.py index f34edec4..ebf5f75f 100644 --- a/tests/provider/zen/test_provider.py +++ b/tests/provider/zen/test_provider.py @@ -84,6 +84,27 @@ def handler(request: httpx.Request) -> httpx.Response: assert [m.id for m in models] == ["m1-free"] await provider.aclose() +async def test_provider_create_embeddings_delegates(): + """Provider 层只做 Key 提取 + 透传(付费根 + Bearer)。""" + seen: list[tuple[str, str, bytes]] = [] + + def handler(request: httpx.Request) -> httpx.Response: + seen.append((request.url.path, request.headers["Authorization"], + request.content)) + return httpx.Response(200, json={"object": "list", "data": [], + "usage": {"prompt_tokens": 1}}) + + provider = ZenProvider(client=_client(handler)) + result = await provider.create_embeddings( + {"api_key": "sk-zen"}, {"input": ["a"]}, "text-embedding-3-small") + assert result["object"] == "list" + path, authorization, content = seen[0] + assert path == "/inference/openai/v1/embeddings" + assert authorization == "Bearer sk-zen" + assert b'"model":"text-embedding-3-small"' in content + await provider.aclose() + + async def test_provider_stream_chat_with_and_without_pacer(): def handler(_request: httpx.Request) -> httpx.Response: return httpx.Response(200, text=_sse(chunk({"content": "hi"}, finish="stop"))) From fc887c70b31399edf24069ae1fb26331f62a1b87 Mon Sep 17 00:00:00 2001 From: Robbs Luo Date: Wed, 2 Dec 2026 15:30:44 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix=20COD-32=EF=BC=9Aembedding=20=E6=9C=AA?= =?UTF-8?q?=E7=9F=A5=E6=A8=A1=E5=9E=8B=E6=94=B9=E5=9B=9E=20404=20model=5Fn?= =?UTF-8?q?ot=5Ffound?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.en.md | 1 + README.md | 1 + TECHNICAL.md | 2 +- src/compat/openai/request.py | 9 ++++++ src/engine/executor.py | 44 +++++++++++++++++++++++--- src/webapp/handlers.py | 12 ++++++- tests/api/test_embeddings.py | 33 ++++++++++++++----- tests/engine/test_embeddings.py | 56 ++++++++++++++++++++++++++++----- 8 files changed, 137 insertions(+), 21 deletions(-) diff --git a/README.en.md b/README.en.md index d39072fc..b579d9e7 100644 --- a/README.en.md +++ b/README.en.md @@ -145,6 +145,7 @@ curl http://127.0.0.1:8000/v1/embeddings \ - `input` accepts a single string or an array of strings (a single string is normalized to an array at the edge); the response is `object=list` + `data[{index, embedding}]` + `usage.prompt_tokens`, same shape as OpenAI Embeddings. - `encoding_format` (float only), `dimensions` and `user` are forwarded; `stream=true` and `encoding_format=base64` → 400 `invalid_request`. +- An unknown model (bad channel suffix, absent from the catalog, or rejected by the upstream) → 404 `model_not_found`, same contract as `GET /v1/models/{id}`; upstream 429 / 5xx map exactly like the chat endpoints (429 rate limit, 503 with `Retry-After`), and no path ever leaks a bare 500 stack. - Auth, key / user quota layers, rate limiting, the credential pool and health scheduling, `model@channel` forcing and key→channel binding are all shared with the chat endpoints. One call counts as exactly one request per user / channel / model with tokens and list-price cost recorded; **inputs and vectors are never persisted**, and it takes no part in conversation affinity or response caching. - Only channels that implement the upstream vector endpoint (currently Zen) are candidates; embedding models of other channels are not listed, so there are no "listed but always 400" entries. Zen's **anonymous free tier** does not list embeddings either (the upstream vector endpoint answers 401 without a key) — put an `api_key` in the credential to use the paid tier. - **Explicitly out of scope this round**: images / audio / rerank / video / realtime (see the PROPOSAL non-goals). diff --git a/README.md b/README.md index 29a6c2fc..24b35115 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,7 @@ curl http://127.0.0.1:8000/v1/embeddings \ - `input` 收单个字符串或字符串数组(单字符串在入口归一成数组);返回 `object=list` + `data[{index, embedding}]` + `usage.prompt_tokens`,与 OpenAI Embeddings 同形。 - 透传 `encoding_format`(只支持 `float`)、`dimensions`、`user`;`stream=true` 与 `encoding_format=base64` → 400 `invalid_request`。 +- 未知模型(写错的渠道 / 目录里没有它 / 上游明确说不认)→ 404 `model_not_found`,与 `GET /v1/models/{id}` 同口径;上游 429 / 5xx 与 chat 出口映射一致(429 限流、503 带 `Retry-After`),任何路径都不出现裸 500 栈。 - 鉴权、Key / 用户双层配额、限流、凭证池与健康度调度、`模型@渠道` 强制与 Key 的渠道绑定完全复用 chat 出口;一次调用在按人 / 渠道 / 模型统计里各计 1 次请求并累加 token 与刊例价成本,**不落库输入文本与向量**,不参与对话粘性与响应缓存。 - 只有实现了上游向量接口的渠道(当前 Zen)参与路由;其他渠道的 embedding 模型不会被列出来,避免「列表里有、调用必 400」。Zen 的**匿名免费档**也不列 embedding(上游向量端点对匿名档回 401),需在凭证里填 `api_key` 走付费档。 - **本轮明确不做** images / audio / rerank / video / realtime(见 PROPOSAL 非目标)。 diff --git a/TECHNICAL.md b/TECHNICAL.md index cf32c0f1..e7e290b9 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -518,7 +518,7 @@ PRAGMA foreign_keys = ON; -- 库里没有外键,关系全在应用层校验 ### 11.0 端点总览 -**外部(API Key)**:`POST /v1/chat/completions`(`n` 只接受 1)、`POST /v1/embeddings`(非流式,`input` 收字符串或字符串数组,仅 `encoding_format=float`)、`POST /v1/responses`、`POST /v1/messages` + `POST /v1/messages/count_tokens`、`POST /v1beta/models/{model}:{generateContent|streamGenerateContent|countTokens}` + `GET /v1beta/models`、`GET /v1/models` + `GET /v1/models/{id}`(对外 id / 展示名 / 任一渠道原 id 三种写法,不存在或不在 Key 白名单 → 404 `model_not_found`)、`GET /v1/usage?days=1|7|30`(只查本 Key 明细)、`GET /v1/user/balance`、`GET /health`、`GET /healthz`、`GET /metrics`。 +**外部(API Key)**:`POST /v1/chat/completions`(`n` 只接受 1)、`POST /v1/embeddings`(非流式,`input` 收字符串或字符串数组,仅 `encoding_format=float`;未知模型 → 404 `model_not_found`,`stream=true` → 400 `invalid_request`)、`POST /v1/responses`、`POST /v1/messages` + `POST /v1/messages/count_tokens`、`POST /v1beta/models/{model}:{generateContent|streamGenerateContent|countTokens}` + `GET /v1beta/models`、`GET /v1/models` + `GET /v1/models/{id}`(对外 id / 展示名 / 任一渠道原 id 三种写法,不存在或不在 Key 白名单 → 404 `model_not_found`)、`GET /v1/usage?days=1|7|30`(只查本 Key 明细)、`GET /v1/user/balance`、`GET /health`、`GET /healthz`、`GET /metrics`。 **管理台(Cookie + RBAC)**:`/api/credentials`(`checkin` / `toggle` / `revive` / `probe` / `activity` / `pin` / `accounts/select` / `export` / `batch` / `batch-import` / `limits` / `tags` / `weight` / `login-secret` / `web-cookie`)、`/api/api-keys`、`/api/users`(`policy` / `disable` / `enable` / `reset-password`,**无 DELETE**)、`/api/model-catalog`、`/api/models/availability`、`/api/settings`、`/api/tasks` + `POST /api/tasks/{key}/run`、`/api/alerts` + `POST /api/alerts/{id}/resolve`、`/api/upstream-status`、`/api/stats/*`、`/api/billing`、`/api/logs` + `/api/logs/stream`、`/api/backups` + `/api/backups/restore`、`/api/nav-badges`、`/api/auth/*`、`/api/audit`、`GET /authorize`。列表端点统一 `sort` + `order`,未知键回落默认。 diff --git a/src/compat/openai/request.py b/src/compat/openai/request.py index e6493d7f..5b16497d 100644 --- a/src/compat/openai/request.py +++ b/src/compat/openai/request.py @@ -11,6 +11,15 @@ class InvalidRequest(ValueError): pass +class ModelNotFound(InvalidRequest): + """请求的模型不存在(或对该 Key / 渠道不可见)→ 404 `model_not_found`。 + + 继承 `InvalidRequest` 只为「凡是没单独注册处理器的子类仍落到 400」这条 + 兜底不变;`register_exception_handlers` 为它单独注册 404 处理器,与 + `GET /v1/models/{id}` 的单查口径一致(同一个模型,两个出口同一个答案)。 + """ + + # 采样参数与输出上限的宽松但有限的边界:本服务只做透传,上界只为拦住 # 明显畸形的输入(NaN/Inf、负数、超大值),真正语义由上游裁决。 MAX_TEMPERATURE = 1000.0 diff --git a/src/engine/executor.py b/src/engine/executor.py index 2a88cba5..d7e67050 100644 --- a/src/engine/executor.py +++ b/src/engine/executor.py @@ -19,7 +19,7 @@ from starlette.requests import ClientDisconnect from ..compat.openai.errors import UpstreamStreamError, stream_error_frame -from ..compat.openai.request import ChatRequest, InvalidRequest +from ..compat.openai.request import ChatRequest, InvalidRequest, ModelNotFound from ..compat.openai.response import ( StreamTranslator, aggregate, @@ -2142,10 +2142,18 @@ async def create_embeddings(self, request: ChatRequest, *, 错误口径与 chat 一致:所有上游都拒绝该模型 → 400,候选全在冷却 → 503。 """ - target = self.resolve_target(request, provider_binding) + try: + target = self.resolve_target(request, provider_binding) + except UnknownModelError as error: + # `emb@nope` 这类「写了个不存在的渠道」:对调用方就是「没有这个 + # 模型」,与 `GET /v1/models/{id}` 同口径回 404,而不是 400。 + raise ModelNotFound(f"model not found: {request.model}") from error model = target.model + self._require_known_model(model) providers = self._embedding_providers(target) if not providers: + # 目录里认识这个模型,但没有任何候选渠道声明向量能力:是能力缺口, + # 不是「模型不存在」——两者对调用方是不同动作(换模型 / 换渠道)。 raise InvalidRequest( f"model {model!r} is not available for embeddings") # 收窄到向量能力集后再走既有选号:`_select` 的 `_registered` 会与已注册 @@ -2165,7 +2173,9 @@ async def create_embeddings(self, request: ChatRequest, *, picked = await self._pick(narrowed, tried) if picked is None: if last_kind in REJECT_KINDS: - raise InvalidRequest(_reject_message(model, last_error)) + # 上游明确不认这个模型 → 404(与 `GET /v1/models/{id}` + # 同口径);能力类拒绝仍是 400(模型存在,只是不会向量)。 + raise self._reject_error(model, last_kind, last_error) if not attributed: self._deps.record( username=username, @@ -2202,8 +2212,7 @@ async def create_embeddings(self, request: ChatRequest, *, tried.update(row.credential_id for row in self._scope().all_rows([provider_id])) if not self._deps.scheduler.should_rotate(attempts): - raise InvalidRequest( - _reject_message(model, error)) from error + raise self._reject_error(model, kind, error) from error continue attributed = self._note_upstream_error( credential_id, kind or ErrKind.OTHER, provider_id, model, @@ -2240,6 +2249,31 @@ async def create_embeddings(self, request: ChatRequest, *, latency_ms=_elapsed_ms(started)) return result + def _require_known_model(self, model: str) -> None: + """目录已就绪时,未登记在任何候选渠道上的模型 → 404 `model_not_found`。 + + 与 `GET /v1/models/{id}` 同一判据(`match_entry` 的三种写法),否则同一个 + 模型在列表出口 404、在 embedding 出口 400,客户端没法统一处理。目录未就绪 + (`model_aliases` 为空:冷启动窗口 / 全部渠道没凭证)时放行,交给上游裁决 + —— 此时「不认识」只说明目录还没拉,不是模型不存在。 + """ + aliases = self._deps.model_aliases + if not aliases: + return + lower = model.lower() + if any(lower in table for table in aliases.values()): + return + raise ModelNotFound(f"model not found: {model}") + + def _reject_error(self, model: str, kind: ErrKind | None, + error: Exception | None) -> InvalidRequest: + """上游拒绝该模型时的对外异常:INVALID → 404,其余(能力类)→ 400。""" + if kind is not ErrKind.INVALID: + return InvalidRequest(_reject_message(model, error)) + summary = _error_summary(error) + detail = f": {summary}" if summary else "" + return ModelNotFound(f"model not found: {model}{detail}") + def _embedding_providers(self, target: ModelTarget) -> tuple[str, ...]: """当前可服务该模型向量的渠道(声明了 `create_embeddings` 的那些)。 diff --git a/src/webapp/handlers.py b/src/webapp/handlers.py index 3ad538e9..8d52c427 100644 --- a/src/webapp/handlers.py +++ b/src/webapp/handlers.py @@ -24,7 +24,7 @@ ) from ..auth.throttle import ThrottledError from ..compat.openai.errors import error_payload -from ..compat.openai.request import InvalidRequest +from ..compat.openai.request import InvalidRequest, ModelNotFound from ..db.crypto import CredentialDecryptError from ..engine.executor import ( NoHealthyCredential, @@ -55,6 +55,16 @@ async def _invalid(_request, error: InvalidRequest): return JSONResponse(status_code=400, content=error_payload(str(error), "invalid_request", 400)) + @app.exception_handler(ModelNotFound) + async def _model_not_found(_request, error: ModelNotFound): + """未知模型 → 404 `model_not_found`(与 `GET /v1/models/{id}` 同口径)。 + + `InvalidRequest` 的 400 是「请求本身不合规」,而模型不存在属于资源 + 不存在:RAG / SDK 客户端据此区分「换个模型名」与「改请求体」。 + """ + return JSONResponse(status_code=404, + content=error_payload(str(error), "model_not_found", 404)) + @app.exception_handler(UnknownModelError) async def _unknown_model(_request, error: UnknownModelError): return JSONResponse(status_code=400, diff --git a/tests/api/test_embeddings.py b/tests/api/test_embeddings.py index 04982b98..9a146863 100644 --- a/tests/api/test_embeddings.py +++ b/tests/api/test_embeddings.py @@ -174,21 +174,40 @@ async def stream_chat(self, *_args, **_kwargs): assert client.provider.calls == [] -def test_embeddings_unknown_model_is_400(client): +def test_embeddings_unknown_model_is_404(client): + """不存在的渠道 → 404 `model_not_found`(与 `GET /v1/models/{id}` 同口径)。""" headers = _key(client.app) response = client.post("/v1/embeddings", headers=headers, json=_body(model="emb@nope")) - assert response.status_code == 400 - assert response.json()["error"]["code"] == "invalid_request" + assert response.status_code == 404, response.text + error = response.json()["error"] + assert error["code"] == "model_not_found" and error["status"] == 404 + assert "emb@nope" in error["message"] + assert client.provider.calls == [] -def test_embeddings_upstream_rejection_maps_to_400(client): - """上游拒绝该模型(INVALID)→ 400,且不冷却凭证。""" +def test_embeddings_model_absent_from_catalog_is_404(client): + """目录已就绪但没有任何渠道登记它 → 404(不白打一轮上游)。""" + headers = _key(client.app) + client.app.state.services.model_aliases["zen"] = {"emb": "emb"} + response = client.post("/v1/embeddings", headers=headers, + json=_body(model="no-such-model")) + assert response.status_code == 404, response.text + assert response.json()["error"]["code"] == "model_not_found" + assert client.provider.calls == [] + + +def test_embeddings_upstream_rejection_maps_to_404(client): + """上游拒绝该模型(INVALID)→ 404 `model_not_found`,且不冷却凭证。""" headers = _key(client.app) client.provider.fail_with = RejectedModel("model not found") response = client.post("/v1/embeddings", headers=headers, json=_body()) - assert response.status_code == 400, response.text - assert response.json()["error"]["code"] == "invalid_request" + assert response.status_code == 404, response.text + error = response.json()["error"] + assert error["code"] == "model_not_found" and error["status"] == 404 + # 只给受控标识(异常类名),上游正文绝不回显 + assert error["message"].startswith("model not found: emb") + assert "boom" not in error["message"] rows = _events(client.app) assert [row["error_type"] for row in rows] == ["invalid_request"] diff --git a/tests/engine/test_embeddings.py b/tests/engine/test_embeddings.py index ff086f53..81c7f6da 100644 --- a/tests/engine/test_embeddings.py +++ b/tests/engine/test_embeddings.py @@ -9,7 +9,7 @@ import pytest -from src.compat.openai.request import InvalidRequest +from src.compat.openai.request import InvalidRequest, ModelNotFound from src.db.conn import Database from src.db.crypto import CredentialCipher from src.db.migrate import apply_schema @@ -126,11 +126,11 @@ async def test_create_embeddings_exhausted_rotation_raises_503(credentials): assert records[0]["error_type"] is not None -async def test_create_embeddings_invalid_after_budget_raises_400(credentials): - """轮换预算耗尽时最后一类错误是 INVALID → 400(不是 503)。""" +async def test_create_embeddings_invalid_after_budget_raises_404(credentials): + """轮换预算耗尽时最后一类错误是 INVALID → 404 `model_not_found`(不是 503)。""" credentials.add(provider="zen", credential_data={"api_key": "a"}) executor = _executor(credentials, {"zen": EmbeddingProvider([Rejected()])}) - with pytest.raises(InvalidRequest, match="not available on any configured upstream"): + with pytest.raises(ModelNotFound, match="model not found: emb"): await executor.create_embeddings(_request(model="emb")) @@ -159,12 +159,12 @@ async def test_create_embeddings_without_selectable_credential_is_503(credential assert [row["ok"] for row in records] == [False] -async def test_create_embeddings_rejected_with_no_rotation_budget_is_400(credentials): - """轮换预算只有 1:单次 INVALID 直接 400(不落到「无可用凭证」)。""" +async def test_create_embeddings_rejected_with_no_rotation_budget_is_404(credentials): + """轮换预算只有 1:单次 INVALID 直接 404(不落到「无可用凭证」)。""" credentials.add(provider="zen", credential_data={"api_key": "a"}) executor = _executor(credentials, {"zen": EmbeddingProvider([Rejected()])}, scheduler=Scheduler(max_rotate=1)) - with pytest.raises(InvalidRequest, match="not available on any configured upstream"): + with pytest.raises(ModelNotFound, match="model not found: emb"): await executor.create_embeddings(_request(model="emb")) @@ -192,3 +192,45 @@ async def test_create_embeddings_no_usage_keeps_tokens_null(credentials): assert await executor.create_embeddings(_request(model="emb")) == {"data": []} assert records[0]["input_tokens"] is None assert records[0]["output_tokens"] is None + + +async def test_create_embeddings_unknown_provider_suffix_is_404(credentials): + """`emb@nope`(渠道不存在)→ 404:对调用方就是「没有这个模型」。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + executor = _executor(credentials, {"zen": EmbeddingProvider([OK])}) + with pytest.raises(ModelNotFound, match="model not found: emb@nope"): + await executor.create_embeddings(_request(model="emb@nope")) + + +async def test_create_embeddings_unknown_model_with_ready_catalog_is_404(credentials): + """目录已就绪但没登记该模型 → 404(不扇出到不认它的上游)。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + executor = _executor(credentials, {"zen": EmbeddingProvider([OK])}, + model_aliases={"zen": {"emb": "emb"}}) + with pytest.raises(ModelNotFound, match="model not found: ghost"): + await executor.create_embeddings(_request(model="ghost")) + + +async def test_create_embeddings_known_model_with_ready_catalog_passes(credentials): + """目录已就绪且登记了该模型 → 正常放行(不被「未知模型」误拦)。""" + credentials.add(provider="zen", credential_data={"api_key": "a"}) + provider = EmbeddingProvider([OK]) + executor = _executor(credentials, {"zen": provider}, + model_aliases={"zen": {"emb": "emb"}}) + assert await executor.create_embeddings(_request(model="emb")) == OK + assert provider.calls == 1 + + +async def test_create_embeddings_capability_rejection_stays_400(credentials): + """能力类拒绝(CAPABILITY:模型存在但不会向量)仍是 400,不是 404。""" + + class Unsupported(Exception): + def kind(self) -> ErrKind: + return ErrKind.CAPABILITY + + credentials.add(provider="zen", credential_data={"api_key": "a"}) + executor = _executor(credentials, {"zen": EmbeddingProvider([Unsupported()])}) + with pytest.raises(InvalidRequest) as caught: + await executor.create_embeddings(_request(model="emb")) + assert not isinstance(caught.value, ModelNotFound) + assert "not available on any configured upstream" in str(caught.value) From e6618f8ff2070affb099c207acbcf22d14776b9d Mon Sep 17 00:00:00 2001 From: Robbs Luo Date: Wed, 2 Dec 2026 16:18:37 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix=20COD-32=EF=BC=9A=E6=97=A0=E5=90=91?= =?UTF-8?q?=E9=87=8F=E8=83=BD=E5=8A=9B=E6=A8=A1=E5=9E=8B=E7=9A=84=20embedd?= =?UTF-8?q?ing=20=E5=87=BA=E5=8F=A3=E6=94=B9=E5=9B=9E=20404=20model=5Fnot?= =?UTF-8?q?=5Ffound?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 +- src/engine/executor.py | 13 ++++++++----- tests/api/test_embeddings.py | 12 +++++++++--- tests/engine/test_embeddings.py | 10 +++++----- 4 files changed, 23 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 24b35115..534b8f74 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,7 @@ curl http://127.0.0.1:8000/v1/embeddings \ - 透传 `encoding_format`(只支持 `float`)、`dimensions`、`user`;`stream=true` 与 `encoding_format=base64` → 400 `invalid_request`。 - 未知模型(写错的渠道 / 目录里没有它 / 上游明确说不认)→ 404 `model_not_found`,与 `GET /v1/models/{id}` 同口径;上游 429 / 5xx 与 chat 出口映射一致(429 限流、503 带 `Retry-After`),任何路径都不出现裸 500 栈。 - 鉴权、Key / 用户双层配额、限流、凭证池与健康度调度、`模型@渠道` 强制与 Key 的渠道绑定完全复用 chat 出口;一次调用在按人 / 渠道 / 模型统计里各计 1 次请求并累加 token 与刊例价成本,**不落库输入文本与向量**,不参与对话粘性与响应缓存。 -- 只有实现了上游向量接口的渠道(当前 Zen)参与路由;其他渠道的 embedding 模型不会被列出来,避免「列表里有、调用必 400」。Zen 的**匿名免费档**也不列 embedding(上游向量端点对匿名档回 401),需在凭证里填 `api_key` 走付费档。 +- 只有实现了上游向量接口的渠道(当前 Zen)参与路由;其他渠道的 embedding 模型不会被列出来,避免「列表里有、调用必 404 `model_not_found`」。Zen 的**匿名免费档**也不列 embedding(上游向量端点对匿名档回 401),需在凭证里填 `api_key` 走付费档。 - **本轮明确不做** images / audio / rerank / video / realtime(见 PROPOSAL 非目标)。 ### 模型名三字段 diff --git a/src/engine/executor.py b/src/engine/executor.py index d7e67050..34e60b51 100644 --- a/src/engine/executor.py +++ b/src/engine/executor.py @@ -2140,7 +2140,8 @@ async def create_embeddings(self, request: ChatRequest, *, - 响应体原样返回(OpenAI 形状),用量取上游 `usage.prompt_tokens`, 据此算成本;不落库输入文本与向量。 - 错误口径与 chat 一致:所有上游都拒绝该模型 → 400,候选全在冷却 → 503。 + 错误口径与 chat 一致:所有上游都拒绝该模型 → 404 `model_not_found`, + 候选全在冷却 → 503。 """ try: target = self.resolve_target(request, provider_binding) @@ -2152,10 +2153,12 @@ async def create_embeddings(self, request: ChatRequest, *, self._require_known_model(model) providers = self._embedding_providers(target) if not providers: - # 目录里认识这个模型,但没有任何候选渠道声明向量能力:是能力缺口, - # 不是「模型不存在」——两者对调用方是不同动作(换模型 / 换渠道)。 - raise InvalidRequest( - f"model {model!r} is not available for embeddings") + # 目录里认识这个模型,但没有任何候选渠道声明向量能力:对调用方就是 + # 「这个模型不能拿来做向量」——与 `GET /v1/models/{id}` 同口径回 404 + # `model_not_found`,否则同一个模型在两个出口给出两种答案,RAG 客户端 + # 的 SDK 只会把它当成请求体不合法(400)去改 body,永远修不好。 + raise ModelNotFound( + f"model not found: {model} (not available for embeddings)") # 收窄到向量能力集后再走既有选号:`_select` 的 `_registered` 会与已注册 # 渠道取交,故等价于「在支持向量的渠道里选号」,冷却 / 限额 / 在途判定 # 全部复用,不另写一份。 diff --git a/tests/api/test_embeddings.py b/tests/api/test_embeddings.py index 9a146863..887a2a56 100644 --- a/tests/api/test_embeddings.py +++ b/tests/api/test_embeddings.py @@ -157,7 +157,11 @@ def test_embeddings_rejects_bad_shape(client, payload, fragment): def test_embeddings_rejects_uncovered_model(client): - """渠道没声明向量能力 → 400(不是 500,也不是白打一轮上游)。""" + """渠道没声明向量能力 → 404 `model_not_found`(不是 500,也不是白打一轮上游)。 + + 与 `GET /v1/models/{id}` 同口径:同一个模型在两个出口不能一个 404 一个 400, + 否则 RAG 客户端的 SDK 会去改请求体而不是换模型。 + """ headers = _key(client.app) class ChatOnly: @@ -169,8 +173,10 @@ async def stream_chat(self, *_args, **_kwargs): client.app.state.services.executor._deps.providers["kilo"] = ChatOnly() response = client.post("/v1/embeddings", headers=headers, json=_body(model="emb@kilo")) - assert response.status_code == 400, response.text - assert "not available for embeddings" in response.json()["error"]["message"] + assert response.status_code == 404, response.text + error = response.json()["error"] + assert error["code"] == "model_not_found" and error["status"] == 404 + assert "not available for embeddings" in error["message"] assert client.provider.calls == [] diff --git a/tests/engine/test_embeddings.py b/tests/engine/test_embeddings.py index 81c7f6da..469f0435 100644 --- a/tests/engine/test_embeddings.py +++ b/tests/engine/test_embeddings.py @@ -82,18 +82,18 @@ def _executor(credentials, providers, **kwargs): async def test_create_embeddings_requires_vector_channel(credentials): - """一个声明了向量的渠道都没有 → 400,不落在「无可用凭证」的 503 上。""" + """一个声明了向量的渠道都没有 → 404 `model_not_found`,不是 503 也不是 400。""" credentials.add(provider="trae", credential_data={"accessToken": "a"}) executor = _executor(credentials, {"trae": ChatOnlyProvider()}) - with pytest.raises(InvalidRequest, match="not available for embeddings"): + with pytest.raises(ModelNotFound, match="not available for embeddings"): await executor.create_embeddings(_request(model="glm-5.2")) -async def test_create_embeddings_binding_to_chat_only_channel_is_400(credentials): - """Key 绑定到没有向量能力的渠道 → 400(`@渠道` 同理,见 API 层用例)。""" +async def test_create_embeddings_binding_to_chat_only_channel_is_404(credentials): + """Key 绑定到没有向量能力的渠道 → 404(`@渠道` 同理,见 API 层用例)。""" credentials.add(provider="trae", credential_data={"accessToken": "a"}) executor = _executor(credentials, {"trae": ChatOnlyProvider()}) - with pytest.raises(InvalidRequest, match="not available for embeddings"): + with pytest.raises(ModelNotFound, match="not available for embeddings"): await executor.create_embeddings(_request(model="glm-5.2"), provider_binding="trae")