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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,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 模型不会被列出来,避免「列表里有、调用必 404 `model_not_found`」。Zen 的**匿名免费档**也不列 embedding(上游向量端点对匿名档回 401),需在凭证里填 `api_key` 走付费档。
- 只有实现了上游向量接口的渠道(当前 Zen 与 Generic 及其多实例)参与路由;其他渠道的 embedding 模型不会被列出来,避免「列表里有、调用必 404 `model_not_found`」。Zen 的**匿名免费档**也不列 embedding(上游向量端点对匿名档回 401),需在凭证里填 `api_key` 走付费档。Generic 渠道的向量模型按上游 `type` 或 id(含 `embed` / `bge` / `m3e`)推断,在 `/v1/models` 里带 `type=embedding`。
- **本轮明确不做** images / audio / rerank / video / realtime(见 PROPOSAL 非目标)。

### 模型名三字段
Expand Down
5 changes: 3 additions & 2 deletions TECHNICAL.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,10 +203,11 @@ UNKNOWN = None; EXHAUSTED = -1 # 0-100 已知;None 未知;-1 已耗尽

### 3.12 通用上游渠道(`generic`,可选)

`{base}/chat/completions` + `{base}/models`,标准 OpenAI 兼容、非逆向,凭证是部署者自己的 key。
`{base}/chat/completions` + `{base}/models` + `{base}/embeddings`,标准 OpenAI 兼容、非逆向,凭证是部署者自己的 key。

- `GENERIC_API_ENDPOINT` 非空才启用;装配期解析一次,同时决定注册与 base_url。分类与 Zen / Kilo 相反:401/403 = key 失效 → `DEAD`;402 → `CREDIT`,400/404/422 → `INVALID`,429 → `SOFT`,5xx → `OTHER`。
- `GENERIC_ALLOWED_ENDPOINTS` 非空只放行名单;留空放行任意 `http(s)`,拒绝非 HTTP scheme。请求体深拷 + 强制 `stream=true`;流式复用 `openai_chunk`;`/models` 失败回落 `GENERIC_MODELS`。无签到 / 成长 / 活跃 / 刷新 / 额度探测。
- 向量:`POST {base}/embeddings` 透传(非流式,`input` 已归一成字符串数组),非 2xx 走 `classify_status` + `Retry-After`,2xx 缺 `data` 数组判协议违规;`/models` 条目按上游 `type == "embedding"` 或 id 含 `embed` / `bge` / `m3e` 推断 `model_type=embedding`(标准 OpenAI `/models` 没有能力字段,不推断则 RAG 客户端在 `/v1/models` 里看不到向量模型)。

**多渠道(`GENERIC_CHANNELS`)**:`main.py::_generic_channel_endpoints` 解析 `名字=端点` 并用**同一套**端点校验,装配成多条 `GenericProvider`(各带 `id=名字` 与独立 pacer)。渠道 id 不是写到代码里的常量,而是配置值,所以有三处必须跟着动,漏一处就是「功能有但用不了」:

Expand Down Expand Up @@ -241,7 +242,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`(自带静态兜底表的渠道申报「本次是否降级 + 原因」)、`create_embeddings`(仅 Zen:`POST /v1/embeddings` 的候选渠道判据,未实现的渠道不参与向量路由)。
- **可选能力不实现即不定义**:调用方 `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 与 Generic 及其多实例:`POST /v1/embeddings` 的候选渠道判据,未实现的渠道不参与向量路由)。
- CodeBuddy / TRAE / Zen / Kilo / Qoder / OfficeAce 共用 `engine/sse.py`;CodeArts 自实现 `iter_data_lines`,只复用 `MAX_SSE_LINE_BYTES` / `SSEFrameTooLarge`。

## 5. 各渠道协议实现
Expand Down
67 changes: 64 additions & 3 deletions src/provider/generic/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,30 @@

EP_CHAT = "/chat/completions"
EP_MODELS = "/models"
EP_EMBEDDINGS = "/embeddings"

# 向量模型的 id 标记:多数 OpenAI 兼容网关的 `/models` 只有 id、没有 `type`
# (`text-embedding-3-small` / `nomic-embed-text` / `bge-m3` / `m3e-base`)。
# 只认这三个明确标记:宁可漏标(按 id 直接请求仍能调通,只是 `/v1/models`
# 不标 type),也不要把对话模型误标成 embedding——那会让 RAG 客户端挑中一个
# 不能向量化的模型。
_EMBEDDING_ID_HINTS = ("embed", "bge", "m3e")


def model_type(item: dict[str, Any]) -> str:
"""条目能力类型(对外值只有 `chat` / `embedding`)。

上游声明了 `type == "embedding"` 就照抄(vLLM / LiteLLM 会填),否则按
id 推断——标准 OpenAI `/models` 没有能力字段,不推断的话 generic 渠道的
向量模型在 `/v1/models` 里永远是 chat,RAG 客户端根本看不到它。
"""
kind = item.get("type")
if isinstance(kind, str) and kind.strip().lower() == "embedding":
return "embedding"
model_id = str(item.get("id") or "").lower()
if any(hint in model_id for hint in _EMBEDDING_ID_HINTS):
return "embedding"
return "chat"


def prepare_body(payload: dict[str, Any], model: str) -> dict[str, Any]:
Expand Down Expand Up @@ -153,7 +177,7 @@ def parse_all_events(frame) -> list[Event]:


class GenericClient(LazyClients):
"""标准 OpenAI 兼容客户端:`{base}/chat/completions` + `{base}/models`。"""
"""标准 OpenAI 兼容客户端:`chat/completions` + `models` + `embeddings`。"""

def __init__(self, *, endpoint: str, api_key: str = "",
user_agent: str = "",
Expand Down Expand Up @@ -219,11 +243,41 @@ async def fetch_models(self, api_key: str = "") -> list[Model]:
continue
name = item.get("name")
models.append(Model(id=model_id,
name=name if isinstance(name, str) else ""))
name=name if isinstance(name, str) else "",
model_type=model_type(item)))
if not models:
raise UpstreamProtocolViolation("models api returned no models")
return models

async def create_embeddings(self, payload: dict[str, Any], model: str,
api_key: str = "") -> dict[str, Any]:
"""POST `{base}/embeddings` 并原样返回上游响应体(非流式)。

`payload.input` 已由兼容层归一成字符串数组,这里只换 model 并转发,
其余键(`encoding_format` / `dimensions` / `user`)透传。非 2xx 抛
`UpstreamHTTPError`(分类见 `classify_status`,含 `Retry-After`),由
executor 按 429 / 5xx / 401 各自冷却或轮换;2xx 但不是 OpenAI 形状
(缺 `data` 数组)按协议违规,绝不当成成功透传。
"""
headers = self.headers()
key = api_key or self.api_key
if key and "Authorization" not in headers:
headers["Authorization"] = f"Bearer {key}"
# 向量端点是普通 JSON,别把 SSE 的 Accept 发过去(严格网关会 406)
headers.pop("Accept", None)
body = dict(payload)
body["model"] = model
body.pop("stream", None)
response = await self._short.post(f"{self.endpoint}{EP_EMBEDDINGS}",
json=body, headers=headers)
data = await json_or_raise(response, UpstreamHTTPError, "embeddings",
message="non-JSON embeddings response",
with_retry_hints=True)
if not isinstance(data, dict) or not isinstance(data.get("data"), list):
raise UpstreamProtocolViolation(
"embeddings response missing data list")
return data


def split_models(raw: str) -> list[Model]:
"""`GENERIC_MODELS` 静态兜底表(上游没 `/models` 时用,逗号分隔)。"""
Expand All @@ -242,7 +296,7 @@ def parse_frame(frame) -> Event | None: # pragma: no cover - 仅测试/诊断
class GenericProvider:
"""Provider 协议实现:标准 OpenAI 端点 + Bearer 凭证池。

只实现对话 / 模型列表 / 额度三件事。`probe_quota` 恒 `probe_failed`
只实现对话 / 模型列表 / 向量 / 额度四件事。`probe_quota` 恒 `probe_failed`
(标准端点没有统一的额度 API),签到 / 成长 / 活跃上报 / token 刷新一律
**不实现**——任务层用 `getattr` 探测,缺方法就跳过。
"""
Expand Down Expand Up @@ -290,6 +344,13 @@ async def list_models(self, credential_data: dict) -> list[Model]:
return list(self.static_models)
raise

async def create_embeddings(self, credential_data: dict, payload: dict,
model: str) -> dict:
"""`POST {base}/embeddings` 透传(非流式,OpenAI 形状原样返回)。"""
api_key = str(credential_data.get("api_key") or "")
async with paced(self.pacer, self.id):
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 = str(credential_data.get("api_key") or "")
Expand Down
40 changes: 40 additions & 0 deletions tests/engine/test_embeddings.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
ExecutorDeps,
NoHealthyCredential,
)
from src.engine.model_resolver import ProviderCatalog
from src.engine.scheduler import Scheduler
from src.provider.base import ErrKind
from tests.helpers.chat import chat_request as _request
Expand Down Expand Up @@ -234,3 +235,42 @@ def kind(self) -> ErrKind:
await executor.create_embeddings(_request(model="emb"))
assert not isinstance(caught.value, ModelNotFound)
assert "not available on any configured upstream" in str(caught.value)


# ------------------------------------------------- 候选收窄(向量能力集)

async def test_create_embeddings_narrows_to_vector_capable_provider(credentials):
"""混合候选:只有声明了 `create_embeddings` 的渠道被选中,chat-only 不白打。"""
credentials.add(provider="trae", credential_data={"accessToken": "a"})
credentials.add(provider="zen", credential_data={"api_key": "b"})
vector = EmbeddingProvider([OK])
chat_only = ChatOnlyProvider()
executor = _executor(credentials, {"trae": chat_only, "zen": vector})
# 默认模型 glm-5.2 → 候选含全部内置渠道,但向量能力集只有 zen
assert await executor.create_embeddings(_request(model="glm-5.2")) == OK
assert vector.calls == 1


async def test_create_embeddings_generic_provider_is_candidate(credentials):
"""generic 渠道实现了 `create_embeddings` → 它的向量模型不再 404。

COD-52:任意 OpenAI 兼容上游都走这条路径(generic / GENERIC_CHANNELS
多实例),未实现时 `/v1/embeddings` 一律 404 model_not_found。
"""
credentials.add(provider="generic", credential_data={"api_key": "sk-x"})
vector = EmbeddingProvider([OK])
vector.id = "generic"
executor = _executor(credentials, {"generic": vector})
assert await executor.create_embeddings(_request(model="bge-m3")) == OK
assert vector.calls == 1


async def test_create_embeddings_dynamic_generic_instance_is_candidate(credentials):
"""`GENERIC_CHANNELS` 的多实例(如 `groq`)同样参与向量路由。"""
credentials.add(provider="groq", credential_data={"api_key": "sk-x"})
vector = EmbeddingProvider([OK])
vector.id = "groq"
executor = _executor(credentials, {"groq": vector},
provider_catalog=ProviderCatalog(dynamic=("groq",)))
assert await executor.create_embeddings(_request(model="bge-m3@groq")) == OK
assert vector.calls == 1
118 changes: 118 additions & 0 deletions tests/provider/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
GenericProvider,
UpstreamHTTPError,
classify_status,
model_type,
prepare_body,
split_models,
)
Expand Down Expand Up @@ -180,6 +181,42 @@ def handler(_request: httpx.Request) -> httpx.Response:
assert models[0].name == "GPT 6.2"


async def test_fetch_models_infers_embedding_type():
"""上游声明 `type` 或 id 带向量标记 → `model_type=embedding`;其余 chat。"""
def handler(_request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"data": [
{"id": "bge-m3"}, # 无 type,按 id 推断
{"id": "text-embedding-3-small"},
{"id": "qwen3-8b", "type": "embedding"}, # 上游明确声明
{"id": "gpt-6.2", "type": "chat"},
{"id": "gpt-7"},
]})

models = await _client(handler).fetch_models("sk-x")
assert [(m.id, m.model_type) for m in models] == [
("bge-m3", "embedding"),
("text-embedding-3-small", "embedding"),
("qwen3-8b", "embedding"),
("gpt-6.2", "chat"),
("gpt-7", "chat"),
]


@pytest.mark.parametrize(("item", "expected"), [
({"id": "x", "type": "EMBEDDING"}, "embedding"),
({"id": "x", "type": " embedding "}, "embedding"),
({"id": "x", "type": "chat"}, "chat"),
({"id": "x", "type": 1}, "chat"),
({"id": "M3E-base"}, "embedding"),
({"id": "nomic-embed-text-v1.5"}, "embedding"),
# 空 id / 非字符串 id 不能因 `""` 里的空子串被误判(`"" in id` 恒真)
({}, "chat"),
({"id": 123}, "chat"),
])
def test_model_type_rules(item, expected):
assert model_type(item) == expected


async def test_fetch_models_rejects_bad_payloads():
for body in (b"not json", b'{"data": "x"}', b'{"data": []}'):
def handler(_request: httpx.Request, body=body) -> httpx.Response:
Expand Down Expand Up @@ -219,6 +256,87 @@ async def test_split_models_trims_and_skips_blank():
assert [m.id for m in split_models(" a , ,b ")] == ["a", "b"]


# ------------------------------------------------------------------ 向量

async def test_client_create_embeddings_posts_and_returns_body():
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/v1/embeddings"
assert request.headers["authorization"] == "Bearer sk-cred"
# 普通 JSON 端点不该带 SSE 的 Accept
assert request.headers["accept"] != "text/event-stream"
body = json.loads(request.content)
assert body == {"input": ["a", "b"], "model": "bge-m3"}
return httpx.Response(200, json={"object": "list",
"data": [{"index": 0, "embedding": [0.1]}],
"usage": {"prompt_tokens": 2}})

data = await _client(handler).create_embeddings(
{"input": ["a", "b"], "stream": True}, "bge-m3", "sk-cred")
assert data["data"][0]["embedding"] == [0.1]
assert data["usage"] == {"prompt_tokens": 2}


async def test_client_create_embeddings_uses_client_key_when_blank():
def handler(request: httpx.Request) -> httpx.Response:
assert request.headers["authorization"] == "Bearer sk-client"
return httpx.Response(200, json={"data": []})

data = await _client(handler, api_key="sk-client").create_embeddings({}, "m")
assert data == {"data": []}


async def test_client_create_embeddings_http_error_carries_retry_hint():
def handler(_request: httpx.Request) -> httpx.Response:
return httpx.Response(429, content=b'{"error":"slow down"}',
headers={"Retry-After": "7"})

with pytest.raises(UpstreamHTTPError) as caught:
await _client(handler).create_embeddings({"input": ["a"]}, "m", "sk-x")
assert caught.value.status == 429
assert caught.value.retry_after_seconds == 7
assert caught.value.kind() is ErrKind.SOFT


async def test_client_create_embeddings_rejects_bad_payloads():
for body in (b"not json", b'{"data": "x"}', b'[]'):
def handler(_request: httpx.Request, body=body) -> httpx.Response:
return httpx.Response(200, content=body)

with pytest.raises(UpstreamProtocolViolation):
await _client(handler).create_embeddings({"input": ["a"]}, "m", "sk-x")


async def test_provider_create_embeddings_uses_channel_pacer_key():
"""节流桶按渠道 id 分(多实例各一条上游,与 stream_chat 同口径)。"""
calls: list[str] = []

class FakePacer:
async def wait_turn(self, key=None):
calls.append(f"wait:{key}")

def release(self, key=None):
calls.append(f"release:{key}")

def handler(_request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"data": []})

provider = GenericProvider(client=_client(handler), pacer=FakePacer(),
id="groq")
data = await provider.create_embeddings({"api_key": "sk-x"},
{"input": ["a"]}, "m")
assert data == {"data": []}
assert calls == ["wait:groq", "release:groq"]


async def test_provider_create_embeddings_without_pacer():
def handler(_request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"data": []})

provider = GenericProvider(client=_client(handler))
assert await provider.create_embeddings({}, {"input": ["a"]}, "m") == {
"data": []}


# ------------------------------------------------------------------ 装配

def test_provider_stream_chat_with_and_without_pacer():
Expand Down