Skip to content

Commit 1b158f3

Browse files
authored
feat COD-54:embeddings 支持 encoding_format=base64 网关侧编码 (#94)
1 parent df4d503 commit 1b158f3

6 files changed

Lines changed: 127 additions & 21 deletions

File tree

‎README.en.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ curl http://127.0.0.1:8000/v1/embeddings \
144144
```
145145

146146
- `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.
147-
- `encoding_format` (float only), `dimensions` and `user` are forwarded; `stream=true` and `encoding_format=base64` → 400 `invalid_request`.
147+
- `encoding_format` (`float` | `base64` — base64 is encoded gateway-side: always fetched as float from upstream, then converted to little-endian float32 base64, so it does not depend on upstream support), `dimensions` and `user` are forwarded; `stream=true` → 400 `invalid_request`, and any other `encoding_format` value → 400 with the accepted values named in the error message.
148148
- 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.
149149
- 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.
150150
- 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.

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ curl http://127.0.0.1:8000/v1/embeddings \
146146

147147
- `input` 收单个字符串或字符串数组(单字符串在入口归一成数组);返回 `object=list` + `data[{index, embedding}]` + `usage.prompt_tokens`,与 OpenAI Embeddings 同形。
148148
- **提示文案语言**:错误/提示响应按请求 `Accept-Language` 返回对应语言(`en*` 英文、缺省与 `zh*` 中文),错误码与 HTTP 状态码两种语言下完全一致;管理台前端自动带上当前界面语言。上游原始错误体与用户自定义名称(用户名/凭证名/模型名)不翻译。
149-
- 透传 `encoding_format`(只支持 `float`)、`dimensions`、`user`;`stream=true` 与 `encoding_format=base64` → 400 `invalid_request`。
149+
- 透传 `encoding_format`(`float` | `base64`,base64 由网关侧编码:始终以 float 向上游请求,取回后按 little-endian float32 转 base64,不依赖上游支持)、`dimensions`、`user`;`stream=true` → 400 `invalid_request`,其它 `encoding_format` 值 → 400 且 error message 列出可用值。
150150
- 未知模型(写错的渠道 / 目录里没有它 / 上游明确说不认)→ 404 `model_not_found`,与 `GET /v1/models/{id}` 同口径;上游 429 / 5xx 与 chat 出口映射一致(429 限流、503 带 `Retry-After`),任何路径都不出现裸 500 栈。
151151
- 鉴权、Key / 用户双层配额、限流、凭证池与健康度调度、`模型@渠道` 强制与 Key 的渠道绑定完全复用 chat 出口;一次调用在按人 / 渠道 / 模型统计里各计 1 次请求并累加 token 与刊例价成本,**不落库输入文本与向量**,不参与对话粘性与响应缓存。
152152
- 只有实现了上游向量接口的渠道(当前 Zen)参与路由;其他渠道的 embedding 模型不会被列出来,避免「列表里有、调用必 404 `model_not_found`」。Zen 的**匿名免费档**也不列 embedding(上游向量端点对匿名档回 401),需在凭证里填 `api_key` 走付费档。

‎src/api/embeddings.py‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
统计与成本估算。本出口只做三件自己的事:
66
77
1. 形状校验(`compat.openai.embeddings`):`input` 单字符串 / 字符串数组,
8-
拒绝 `stream=true` 与 `encoding_format=base64`;
8+
拒绝 `stream=true`;`encoding_format` 收 `float` / `base64`;
99
2. 白名单与配额准入(与 chat 同判据);
10-
3. 把上游响应**原样**回给客户端(OpenAI Embeddings 形状)。
10+
3. 把上游响应回给客户端(OpenAI Embeddings 形状);`encoding_format=base64`
11+
时由网关侧把 float 向量编码成 base64(上游恒按 float 请求)。
1112
1213
不做流式、不落库输入文本与向量、不参与对话粘性与响应缓存。
1314
"""
@@ -17,7 +18,7 @@
1718
from fastapi import APIRouter, Depends, Request
1819
from fastapi.responses import JSONResponse
1920

20-
from ..compat.openai.embeddings import parse_embedding_request
21+
from ..compat.openai.embeddings import encode_embeddings_base64, parse_embedding_request
2122
from ..key_quota import QuotaExceeded
2223
from .deps import ApiKeyPrincipal, Services, api_key_user, read_json_body
2324
from .endpoints import _admit_quota, ensure_model_allowed, quota_exceeded_response
@@ -47,6 +48,9 @@ async def embeddings(request: Request,
4748
username=principal.username)
4849
finally:
4950
lease.release()
51+
if embedding_request.encoding_format == "base64":
52+
# 上游恒按 float 取回,这里只改响应编码(不动入参、不动上游请求体)
53+
result = encode_embeddings_base64(result)
5054
return JSONResponse(result)
5155

5256
return router

‎src/compat/openai/embeddings.py‎

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,27 @@
11
"""OpenAI Embeddings 入站解析(`POST /v1/embeddings`,非流式)。
22
33
只做**形状校验与归一**,不发请求:`input` 单字符串归一成单元素列表、显式
4-
拒绝 `stream=true` 与 `encoding_format=base64`(上游本仓只透传 float 向量,
5-
接了 base64 等于把「上游可能不支持」变成运行期 500)。与 chat 出口同一套
6-
错误口径:任何不合规都抛 `InvalidRequest` → 400 `invalid_request`。
4+
拒绝 `stream=true`。与 chat 出口同一套错误口径:任何不合规都抛
5+
`InvalidRequest` → 400 `invalid_request`。
6+
7+
`encoding_format` 收 `float` 与 `base64`(OpenAI 官方 SDK 的
8+
`Literal["float", "base64"]`):**两种都以 float 向上游取回**,base64 由网关
9+
侧编码(见 `encode_embeddings_base64`)——上游是否支持 base64 并不统一(Zen
10+
未声明),透传等于把「上游不支持」变成运行期 500。
711
"""
812

913
from __future__ import annotations
1014

15+
import base64
16+
import struct
1117
from dataclasses import dataclass
1218
from typing import Any
1319

1420
from .request import ChatRequest, InvalidRequest
1521

16-
# 上游 embeddings 的 `encoding_format` 取值。只放通 float:本项目透传上游
17-
# JSON,base64 需要额外的编解码契约,而上游是否支持并不统一(Zen 未声明)。
18-
SUPPORTED_ENCODING_FORMATS = frozenset({"float"})
22+
# 客户端可选的响应编码(OpenAI 官方口径)。注意:**上游请求恒发 float**,
23+
# base64 只是响应编码,转换在网关侧完成,不依赖上游支持。
24+
SUPPORTED_ENCODING_FORMATS = frozenset({"float", "base64"})
1925

2026

2127
@dataclass(slots=True)
@@ -51,7 +57,7 @@ def parse_embedding_request(body: Any) -> EmbeddingRequest:
5157
- `input` 不是字符串或字符串数组、空数组、含空串:上游对空串的处置不
5258
统一(有的 400、有的返回零向量),入口统一拒绝;
5359
- `stream=true`:本出口非流式,接了也只能忽略,不如明确 400;
54-
- `encoding_format` 非 `float`:见模块 docstring。
60+
- `encoding_format` 不在 {float, base64}:见模块 docstring。
5561
"""
5662
if not isinstance(body, dict):
5763
raise InvalidRequest("request body must be a JSON object")
@@ -68,7 +74,8 @@ def parse_embedding_request(body: Any) -> EmbeddingRequest:
6874
or encoding_format not in SUPPORTED_ENCODING_FORMATS:
6975
raise InvalidRequest(
7076
f"encoding_format {encoding_format!r} is not supported "
71-
f"(only {', '.join(sorted(SUPPORTED_ENCODING_FORMATS))})")
77+
f"(supported: {', '.join(sorted(SUPPORTED_ENCODING_FORMATS))}; "
78+
f"use encoding_format=float or encoding_format=base64)")
7279
dimensions = _parse_dimensions(body.get("dimensions"))
7380
user = body.get("user")
7481
if user is not None and not isinstance(user, str):
@@ -81,12 +88,32 @@ def parse_embedding_request(body: Any) -> EmbeddingRequest:
8188
raw["input"] = inputs
8289
if dimensions is not None:
8390
raw["dimensions"] = dimensions
84-
raw["encoding_format"] = encoding_format
91+
# 上游**恒要 float**:base64 是网关侧响应编码,上游不一定认这个值。
92+
raw["encoding_format"] = "float"
8593
return EmbeddingRequest(model=model.strip(), inputs=inputs,
8694
encoding_format=encoding_format,
8795
dimensions=dimensions, user=user, raw=raw)
8896

8997

98+
def encode_embeddings_base64(result: dict[str, Any]) -> dict[str, Any]:
99+
"""把 float 向量响应改写成 `encoding_format=base64` 形状(不修改入参)。
100+
101+
每个向量编码为 little-endian float32 的 base64 字符串——与 OpenAI 官方
102+
一致(`numpy.float32(v).tobytes()` 同字节序)。用标准库 `struct` +
103+
`base64`,不引入 numpy / pybase64 依赖。
104+
105+
`data[i].embedding` 由上游保证是数值数组(非数值已在
106+
`create_embeddings` 判过响应形状),故不重复做逐元素类型校验。
107+
"""
108+
encoded = dict(result)
109+
encoded["data"] = [{
110+
**item, "embedding": base64.b64encode(
111+
struct.pack(f"<{len(item['embedding'])}f",
112+
*item["embedding"])).decode("ascii")
113+
} for item in result["data"]]
114+
return encoded
115+
116+
90117
def _parse_input(value: Any) -> list[str]:
91118
"""`input` → 非空字符串列表(单字符串归一成单元素)。"""
92119
if isinstance(value, str):

‎tests/api/test_embeddings.py‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66

77
from __future__ import annotations
88

9+
import base64
10+
import struct
11+
912
import pytest
1013
from fastapi.testclient import TestClient
1114

@@ -112,6 +115,43 @@ def test_embeddings_returns_vectors(client):
112115
assert body["usage"]["prompt_tokens"] > 0
113116

114117

118+
def test_embeddings_base64_encoding_matches_float(client):
119+
"""`encoding_format=base64` → 200,向量为 base64 字符串,可无损还原。"""
120+
headers = _key(client.app)
121+
floats = client.post("/v1/embeddings", headers=headers, json=_body())
122+
assert floats.status_code == 200, floats.text
123+
expected = [item["embedding"] for item in floats.json()["data"]]
124+
upstream_float_payload = dict(client.provider.payload)
125+
126+
response = client.post("/v1/embeddings", headers=headers,
127+
json=_body(encoding_format="base64"))
128+
assert response.status_code == 200, response.text
129+
body = response.json()
130+
assert body["object"] == "list" and body["model"] == "emb"
131+
for index, item in enumerate(body["data"]):
132+
assert item["index"] == index and item["object"] == "embedding"
133+
raw = base64.b64decode(item["embedding"])
134+
assert len(raw) == len(expected[index]) * 4
135+
assert list(struct.unpack(f"<{len(expected[index])}f", raw)) \
136+
== list(struct.unpack(f"<{len(expected[index])}f",
137+
struct.pack(f"<{len(expected[index])}f",
138+
*expected[index])))
139+
# 上游请求体不含 base64:始终按 float 取回,网关侧才编码
140+
assert client.provider.payload["encoding_format"] == "float"
141+
assert client.provider.payload == upstream_float_payload
142+
143+
144+
def test_embeddings_rejects_unknown_encoding_with_actionable_message(client):
145+
"""非法 encoding_format → 400,且 error.message 列出 float 与 base64。"""
146+
headers = _key(client.app)
147+
response = client.post("/v1/embeddings", headers=headers,
148+
json=_body(encoding_format="pyshort"))
149+
assert response.status_code == 400, response.text
150+
error = response.json()["error"]
151+
assert error["code"] == "invalid_request"
152+
assert "float" in error["message"] and "base64" in error["message"]
153+
154+
115155
def test_embeddings_single_string_input(client):
116156
headers = _key(client.app)
117157
response = client.post("/v1/embeddings", headers=headers,
@@ -140,7 +180,9 @@ def test_embeddings_records_usage_once(client):
140180
({"model": "emb", "input": ["a", ""]}, "must not be an empty string"),
141181
({"model": "emb", "input": [1]}, "input[0] must be a string"),
142182
({"model": "emb", "input": "a", "stream": True}, "stream is not supported"),
143-
({"model": "emb", "input": "a", "encoding_format": "base64"},
183+
({"model": "emb", "input": "a", "encoding_format": "pyshort"},
184+
"encoding_format"),
185+
({"model": "emb", "input": "a", "encoding_format": 1},
144186
"encoding_format"),
145187
({"model": "emb", "input": "a", "dimensions": 0}, "positive integer"),
146188
({"model": "emb", "input": "a", "dimensions": "8"}, "positive integer"),

‎tests/compat/test_openai_embeddings.py‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
from __future__ import annotations
44

5+
import base64
6+
import struct
7+
58
import pytest
69

7-
from src.compat.openai.embeddings import parse_embedding_request
10+
from src.compat.openai.embeddings import encode_embeddings_base64, parse_embedding_request
811
from src.compat.openai.request import InvalidRequest
912

1013

@@ -31,13 +34,43 @@ def test_optional_fields_pass_through():
3134
assert parsed.raw["user"] == "u1"
3235

3336

34-
def test_stream_and_base64_are_rejected():
37+
def test_stream_is_rejected():
3538
with pytest.raises(InvalidRequest, match="stream is not supported"):
3639
_parse(stream=True)
37-
with pytest.raises(InvalidRequest, match="encoding_format"):
38-
_parse(encoding_format="base64")
39-
with pytest.raises(InvalidRequest, match="encoding_format"):
40-
_parse(encoding_format=1)
40+
41+
42+
def test_base64_is_accepted_but_upstream_still_gets_float():
43+
"""base64 是网关侧响应编码:入参收下,但转发上游的永远是 float。"""
44+
parsed = _parse(encoding_format="base64")
45+
assert parsed.encoding_format == "base64"
46+
assert parsed.raw["encoding_format"] == "float"
47+
48+
49+
def test_unknown_encoding_format_lists_both_supported_values():
50+
"""报错文案必须可行动:点名 float 与 base64 两个可用值。"""
51+
for value in ("pyshort", "FLOAT", 1, True):
52+
with pytest.raises(InvalidRequest) as info:
53+
_parse(encoding_format=value)
54+
message = str(info.value)
55+
assert "float" in message and "base64" in message
56+
57+
58+
def test_encode_embeddings_base64_round_trips_float32():
59+
"""编码结果 = little-endian float32 的 base64(与 OpenAI 官方同字节序)。"""
60+
result = {
61+
"object": "list",
62+
"data": [{"object": "embedding", "index": 0, "embedding": [0.1, -0.2]},
63+
{"object": "embedding", "index": 1, "embedding": []}],
64+
"usage": {"prompt_tokens": 3, "total_tokens": 3},
65+
}
66+
encoded = encode_embeddings_base64(result)
67+
assert result["data"][0]["embedding"] == [0.1, -0.2] # 入参不被修改
68+
raw = base64.b64decode(encoded["data"][0]["embedding"])
69+
assert len(raw) == 2 * 4
70+
assert struct.unpack("<2f", raw) == struct.unpack("<2f", struct.pack("<2f", 0.1, -0.2))
71+
assert encoded["data"][0]["index"] == 0
72+
assert encoded["data"][1]["embedding"] == "" # 空向量:零字节
73+
assert encoded["usage"] == result["usage"]
4174

4275

4376
def test_user_must_be_string():

0 commit comments

Comments
 (0)