Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion PROPOSAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 上游事实与协议要点

Expand Down Expand Up @@ -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 目录刷新、运维告警、上游状态聚合。

Expand Down
20 changes: 18 additions & 2 deletions README.en.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -134,13 +134,29 @@ 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`.
- 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).

### 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`.
Expand Down
20 changes: 18 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 天窗口;单位统一积分。
- **模型列表按凭证加载**:只列有可用凭证的渠道 → 无幽灵模型。目录落盘,重启即用。
Expand Down Expand Up @@ -135,13 +135,29 @@ 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`。
- 未知模型(写错的渠道 / 目录里没有它 / 上游明确说不认)→ 404 `model_not_found`,与 `GET /v1/models/{id}` 同口径;上游 429 / 5xx 与 chat 出口映射一致(429 限流、503 带 `Retry-After`),任何路径都不出现裸 500 栈。
- 鉴权、Key / 用户双层配额、限流、凭证池与健康度调度、`模型@渠道` 强制与 Key 的渠道绑定完全复用 chat 出口;一次调用在按人 / 渠道 / 模型统计里各计 1 次请求并累加 token 与刊例价成本,**不落库输入文本与向量**,不参与对话粘性与响应缓存。
- 只有实现了上游向量接口的渠道(当前 Zen)参与路由;其他渠道的 embedding 模型不会被列出来,避免「列表里有、调用必 404 `model_not_found`」。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;留空 = 不分档,行为与改动前逐请求一致。
Expand Down
Loading