Merge branch 'main' into fix/refresh-failure-overreaction

This commit is contained in:
Chenyme authored and GitHub committed 2026-07-15 11:53:47 +08:00
commit 17dd5fedcf
68 files changed
+3704 -2899

No files matched your search

+2
View File
@@ -15,6 +15,8 @@ Thumbs.db
/config.local.yaml
/config.*.local.yaml
/docs/rules/
/docs/project/
/backend/docs/goal/
*.har
*.pcap
*.pcapng
+6 -1
View File
@@ -1,4 +1,9 @@
.PHONY: swagger
.PHONY: run swagger
CONFIG ?= $(CURDIR)/config.yaml
run:
cd backend && GOCACHE=$(CURDIR)/.gocache go run ./cmd/grok2api --config "$(abspath $(CONFIG))" $(RUN_ARGS)
swagger:
cd backend && GOCACHE=$(CURDIR)/.gocache go run github.com/swaggo/swag/cmd/swag@v1.16.6 init \
+1 -3
View File
@@ -255,7 +255,7 @@ curl http://127.0.0.1:8000/v1/responses \
| 本地或单实例 | SQLite | Memory | 本地目录 |
| 多实例 | PostgreSQL | Redis | 共享卷或实例亲和 |
可热加载的 Provider(包括 Console 上游地址与 User-Agent)、批量任务并发、路由、媒体容量、审计和代理参数统一在管理端 `/settings` 修改,不需要直接编辑数据库。导入同步、账号转换、数据同步和凭据刷新默认并发均为 `25`,可分别限制为 `1–50`,并支持随机启动延迟;多实例使用 Redis 时,分类上限和总上限均在集群范围内生效。
Provider(包括 Console 上游地址与 User-Agent)、服务容量、批量任务并发、路由、媒体、审计和代理参数统一在管理端 `/settings` 修改,不需要直接编辑数据库;除页面明确标记“重启生效”的字段外均会热加载。导入同步、账号转换、数据同步和凭据刷新默认并发均为 `25`,可分别限制为 `1–50`,并支持随机启动延迟;多实例使用 Redis 时,分类上限和总上限均在集群范围内生效。
## 生产部署
@@ -292,5 +292,3 @@ pnpm build
- [后端说明](./backend/README.md)
- [前端说明](./frontend/README.md)
- [Provider 架构与维护边界](./backend/docs/PROVIDER_ARCHITECTURE.md)
- [API 与协议兼容范围](./backend/docs/RESPONSES_COMPATIBILITY.md)
+5
View File
@@ -0,0 +1,5 @@
.PHONY: run
# 在 backend/ 目录复用项目根目录的启动入口和配置路径。
run:
$(MAKE) -C .. run
+2 -2
View File
@@ -34,7 +34,7 @@ go run ./cmd/grok2api --config /path/to/config.yaml --listen 0.0.0.0:8000
## 配置与存储
启动配置统一由根目录 `config.yaml` 管理,启动阶段字段见 [`config.example.yaml`](../config.example.yaml)。Provider、批量任务、路由、媒体容量、审计和客户端密钥默认限制由管理端设置页持久化并热加载。
启动配置统一由根目录 `config.yaml` 管理,启动阶段字段见 [`config.example.yaml`](../config.example.yaml)。Provider、服务容量、批量任务、路由、媒体、审计和客户端密钥默认限制由管理端设置页持久化;除页面明确标记“重启生效”的字段外均会热加载。
| 场景 | 数据库 | 运行态存储 |
| --- | --- | --- |
@@ -43,7 +43,7 @@ go run ./cmd/grok2api --config /path/to/config.yaml --listen 0.0.0.0:8000
关系型数据库保存账号、凭据、模型、额度、客户端密钥、审计和媒体任务;Redis 仅承载限流、并发租约、粘滞路由、分布式锁和事件通知。敏感凭据使用 `credentialEncryptionKey` 加密,该密钥必须长期保留且不得提交到版本库。
可热加载的 Provider、批量任务并发、路由、审计、媒体和代理参数由管理端设置页维护;数据库驱动、监听地址、Redis、JWT 与加密密钥仍通过 YAML 配置并在启动时生效。
运行设置与代理参数由管理端设置页维护;数据库驱动、监听地址、Redis、JWT 与加密密钥仍通过 YAML 配置并在启动时生效。
## 服务入口
-85
View File
@@ -1,85 +0,0 @@
# Provider Architecture
## Stable Boundary
The service has three fixed upstream Providers:
| Provider | Internal route prefix | Model catalog | Credential lifecycle | Quota authority |
| --- | --- | --- | --- | --- |
| `grok_build` | `Build/` | Remote discovery per account | OAuth import, Device OAuth, refresh | Billing |
| `grok_web` | `Web/` | Built-in catalog filtered by account tier | SSO import | Remote quota windows |
| `grok_console` | `Console/` | Built-in catalog | SSO import | Local quota window |
`infra/provider.Definition` is the authoritative declaration of each Provider's capabilities. `Registry.Validate` runs during application startup and fails fast when a declaration does not match the Adapter's implemented small interfaces. Application services should read the Definition or request a capability from the Registry instead of branching on Provider names.
The Definition also owns lifecycle and gateway policy: credential refresh support, quota authority, upstream-versus-estimated usage, forbidden-response egress retry, conversation state, compaction, and media surfaces. These policies are intentionally declarative so the shared account and gateway services do not encode Build/Web/Console behavior by name.
## Ownership
- `domain/account` owns stable Provider identities and model namespaces.
- `domain/model` owns client-facing model names, Provider-qualified internal route IDs, and their normalization boundary.
- `infra/provider/cli` owns Grok Build upstream HTTP, OAuth, model discovery, Billing, and Responses compatibility.
- `infra/provider/web` owns Grok Web SSO, quota, app-chat, image, video, and Statsig/egress behavior.
- `infra/provider/console` owns Console SSO, its static model catalog, local quota policy, and stateless Responses transport.
- `application/account` orchestrates credential and quota maintenance without knowing upstream wire formats.
- `application/model` orchestrates account capability synchronization and route persistence from Registry definitions.
- `application/gateway` resolves a route, selects only that Provider's account pool, acquires concurrency capacity, forwards through a capability Adapter, and finalizes quota/audit state.
Provider packages must not depend on HTTP handlers or management-page DTOs. Transport handlers must not construct Provider-specific upstream payloads.
## Capability Interfaces
Adapters implement only the surfaces they own:
- `ResponseAdapter`: Responses plus normalized Chat Completions and Messages forwarding.
- `ModelCatalogAdapter`: remote discovery or static account-aware model calculation.
- `CredentialRefreshAdapter`, `DeviceOAuthAdapter`, `CredentialCodecAdapter`: credential lifecycle.
- `BillingAdapter` or `QuotaAdapter`: quota authority.
- `ImageAdapter`, `VideoAdapter`: media generation.
- `RoutingMetadataAdapter`: quota mode and tier eligibility used by the selector.
- `PricingMetadataAdapter`: maps private upstream model IDs to stable pricing IDs.
Adding a method to the base `Adapter` interface is intentionally avoided. A new capability requires a focused interface, a Definition field, Registry validation, and application-level consumption.
## Request and Pool Flow
1. Expand the client-facing model name into currently available Provider-qualified route candidates, or honor an explicitly qualified compatibility name.
2. Filter candidates by client-key permission, protocol capability, and stored-response ownership, then choose one Provider and upstream mapping.
3. Verify the requested protocol/media surface against the Provider Definition.
4. Enforce client-key model permission, Redis/memory RPM, billing reservation, and global concurrency.
5. Select an eligible account from only the route's Provider pool using model capability, quota mode, priority, cooldown, sticky routing, and per-account concurrency.
6. Ensure the credential is usable; only OAuth Providers may refresh.
7. Forward through the requested capability Adapter and apply bounded failover for account-scoped failures.
8. Finalize audit, quota, response ownership, billing, cooldown, and concurrency exactly once.
An unqualified client model such as `grok-4.5` may resolve to Build, Web, or Console when multiple available routes expose that name. Once a route is selected, request retries stay inside that Provider pool. An explicitly qualified compatibility name such as `Web/grok-chat-fast` pins the request to that source and never enters another Provider pool.
## Batch and Multi-Instance Runtime
Bulk import, conversion, model sync, and credential refresh use child pools under one shared upstream concurrency budget. Random delay and bounded worker counts prevent synchronized bursts. Singleflight prevents duplicate in-process full model syncs.
With `runtime_store.driver=redis`, Redis is authoritative for client-key RPM, distributed concurrency, sticky sessions, Device OAuth sessions, refresh locks, settings notifications, and quota-recovery scheduling. The memory implementation preserves the same interfaces for a single-instance deployment but is not a multi-instance coordination mechanism.
## Model-ID Migration
Stored route IDs are canonical: `Build/<model>`, `Web/<model>`, or `Console/<model>`. These prefixes are internal routing identities; `/v1/models`, request bodies, responses, and management-page public names use the unqualified client-facing model name. Schema initialization migrates legacy rows in one transaction:
- route IDs remain unchanged;
- client-key permissions and other route-ID references remain intact;
- the previous public ID is saved in `model_route_aliases`;
- catalog reconciliation can rename a route again without losing either alias;
- an unqualified name can resolve to several source routes without a database uniqueness conflict.
New manual routes are normalized to their selected Provider internally. A public ID or upstream target carrying another known Provider prefix is rejected.
## Change Checklist
When an upstream changes, keep the change inside its Provider package whenever possible:
1. Update that Adapter's private protocol implementation and tests.
2. Update its `Definition` only when the externally supported capability boundary changes.
3. Update its catalog/routing metadata if model eligibility or quota modes change.
4. Run Registry contract tests, Provider protocol tests, gateway tests, race tests, and the full backend suite.
5. Regenerate Swagger and update compatibility documentation when the downstream API surface changes.
If a change requires Provider-name conditionals in a transport handler or an unrelated Provider package, the abstraction boundary should be reconsidered first.
-264
View File
@@ -1,264 +0,0 @@
# Responses Compatibility
本项目向下游提供 OpenAI 风格接口,向上游连接 Grok Build OAuth inference proxy、Grok Web SSO 会话与 Grok Console SSO Responses。
## Supported Surface
公共 `/v1` API 开放:
| Endpoint | Status | Notes |
| --- | --- | --- |
| `POST /v1/responses` | Build / Web / Console | JSON 与 SSE,支持工具调用、结构化输出和 encrypted reasoning 回放;Console 仅支持无状态请求 |
| `POST /v1/responses/compact` | Build | 强制非流式;Web 与 Console 返回明确的不支持错误 |
| `GET /v1/responses/{response_id}` | Build / Web | 根据持久化归属回到创建该 Response 的账号,并透传 `include` 等查询参数 |
| `DELETE /v1/responses/{response_id}` | Build / Web | 上游删除成功后移除本地归属 |
| `GET /v1/models` | Supported | 返回管理端已启用且账号池具备服务能力的公开模型路由 |
| `POST /v1/chat/completions` | Build / Web / Console | xAI Chat Completions JSON 与 SSE;支持函数工具,Web Lite 图片模型支持 `image_config` |
| `POST /v1/messages` | Build / Web / Console | Anthropic Messages JSON 与 SSE;支持客户端工具、`tool_use` 和 `tool_result` |
| `POST /v1/images/generations` | Grok Web | Lite Chat 生图与 Imagine WebSocket 生图,支持 `n`、URL 与 Base64 |
| `POST /v1/images/edits` | Grok Web | 官方 JSON `image.url`/`images[].url` 图片编辑 |
| `GET /v1/media/images/{id}` | Public asset | 读取生成后归档到本地媒体存储的不可变图片 |
| `POST /v1/videos/generations` | Grok Web | xAI 官方异步视频生成协议,返回 `request_id` |
| `GET /v1/videos/{request_id}` | Grok Web | xAI 官方 `pending/done/failed` 轮询响应 |
## Model IDs
下游公开模型名称不带 Provider 前缀,例如 `grok-4.5`。内部路由目标使用 `Build/<model>`、`Web/<model>` 或 `Console/<model>` 区分来源;同一公开名称存在多个可用来源时,网关会结合客户端密钥权限、协议能力和账号可用性选择渠道。显式使用带前缀名称仍可定向指定来源,选定后请求重试只发生在该 Provider 账号池内。
数据库升级会原位迁移内部路由,保留路由主键、客户端密钥授权,并将旧名称登记为兼容别名。新创建和同步的路由在库内使用带来源前缀的稳定 ID;`GET /v1/models` 会按不带前缀的公开名称去重。
## Conversation Modes
### Stateful
Build/Web 调用方可使用 `store` 与 `previous_response_id`。网关持久化 `response_id -> account_id`,后续创建、读取和删除必须回到原账号。绑定账号不可用时返回服务不可用,不会切换账号并制造无效状态链。上游对 retrieve 或 delete 明确返回 `404`/`410` 后,本地归属同步删除,避免失效映射长期滞留。
Grok Web 同时保存本地标准 Response JSON、上游 `conversationId` 和父响应游标。续轮仍绑定原账号;`/responses/compact` 对 Web 模型返回明确的不支持错误。
### Grok Web Chat Images
Grok Web 来源的 `grok-chat-fast`、`grok-chat-auto`、`grok-chat-expert`、`grok-chat-heavy` 支持 OpenAI Chat `image_url` 和 Responses `input_image.image_url`。输入可以是 Base64 图片 data URI,也可以是无用户信息的公网 HTTPS URL。网关会校验 DNS 和目标地址、防止访问内网或元数据地址,限制单张大小和总大小,然后在同一账号、同一出口节点、同一 User-Agent 与 Cloudflare 会话中上传到 `/rest/app-chat/upload-file`,将返回的 `fileMetadataId` 写入 `fileAttachments`。下载第三方图片时不会发送 SSO、Cloudflare Cookie 或 Authorization。
单次对话最多接受 `8` 张图片,图片总大小最多 `64 MiB`;单张上限跟随设置页“单张图片上限”。当前未实现 xAI Files API,因此 `input_image.file_id` 会返回明确错误。
Grok Web 来源的 `grok-imagine-image` 也可通过 `/v1/chat/completions` 调用。请求正文使用普通 `messages` 作为提示词,并可提供:
```json
{
"image_config": {
"n": 2,
"response_format": "url"
}
}
```
Lite 上游每次 Fast Chat 查询固定生成两张候选,但旧协议只采用首张。因此 `n` 表示独立执行 `n` 次查询,范围为 `1..10`,每次按真实 Fast 额度扣减;流式 Chat 会在每张图片完成归档后输出一个 Markdown 图片增量。
### Grok Web Function Tools
Grok Web 上游没有公开的 OpenAI function calling 协议。网关对 Web 来源的 `grok-chat-*` 提供受控兼容层:接受 Chat Completions 的嵌套 `function` 定义和 Responses 的扁平函数定义,将最多 `128` 个函数及 `tool_choice` 注入结构化 XML 约定,再把模型结果转换为标准 `tool_calls` 或 Responses `function_call` item。支持 `auto`、`none`、`required` 和指定函数;未声明的函数名会被丢弃。
流式请求会在检测到工具 XML 起始标记后暂存该段内容,直到完整解析后才发送结构化工具事件,避免把内部 XML 泄露给客户端。Chat 多轮中的 assistant `tool_calls`、`role: tool`,以及 Responses 的 `function_call`、`function_call_output` 都会重建进下一轮上游上下文。
`web_search`/`web_search_preview` 声明使用 Grok Web 原生搜索,不伪装为客户端函数。上游搜索结果会去重写入响应根部 `search_sources`;正文中的 Grok 引用卡片会转换为 Markdown 引用,并输出标准 URL citation `annotations`。由于函数调用是兼容层而非上游原生 API,生产客户端仍应校验函数名和参数后再执行。
### Grok Build Stateless
调用方使用 `store: false`,并通过 `include: ["reasoning.encrypted_content"]` 获取 encrypted reasoning。后续请求可以回放 `reasoning`、assistant message、function call 与 function output。网关完整保留这些输入项。
### Grok Console Stateless
Console 请求固定使用 `store: false`。显式提交 `store: true` 或非空 `previous_response_id` 会在请求上游前返回 `400`,避免客户端误以为状态已被保存。Console 响应不会写入本地 response ownership,因此 retrieve/delete 返回 `404`,旧版本遗留的 Console ownership 会在首次访问时清理。
Chat Completions 与 Messages 同样采用无状态转换;客户端必须在下一轮回放所需消息、工具调用和工具结果。Console 上游的纯文本或 JSON 错误会按调用协议标准化,同时保留原始 HTTP 状态与 `Retry-After`,以便网关正确执行额度恢复和账号切换。
## Request Normalization
Grok Build Responses 默认保持原生转发,只执行以下改写:
- 将公开模型别名替换为上游模型 ID。
- 显式 `prompt_cache_key` 优先作为会话种子;未提供时可读取 Claude Code 的 `X-Claude-Code-Session-Id`、`metadata.session_id` 或 `metadata.user_id` 内嵌/后缀会话标识。Build 路由会结合客户端密钥、上游模型和调用协议生成固定长度的隔离 identity,同时用于账号粘滞、CLI 会话 Header 与上游请求体,避免共享账号池中的跨租户碰撞。
- 将旧式 `response_format` 映射到 Responses `text.format`;`json_schema` 会展开旧的 `json_schema` 包装层。
- 保留未知字段、encrypted reasoning,以及除下述明确受限的新工具项外的标准 Responses input item。
Grok Build `0.2.99` 尚未原生接受 OpenAI 新版 `namespace` 与 `tool_search` 工具类型,因此网关只对这部分执行请求级双向兼容:
- `namespace` 中可立即调用的函数会转换为不超过 `128` 字符的唯一普通函数别名;JSON 与 SSE 中的函数调用会恢复原始 `name` 和 `namespace`,响应根部的 `tools` 也恢复为客户端声明。
- `execution: "client"` 的 `tool_search` 会转换为内部普通函数。带 `defer_loading: true` 的函数在首次请求中不暴露;客户端回传 `tool_search_output` 后,选中的函数才会进入下一轮上游工具集合。
- 客户端 Tool Search 会默认写入 `parallel_tool_calls: false`;显式要求并行会返回错误,避免搜索函数与普通函数在工具定义加载完成前同时执行。
- 单独声明 `defer_loading: true` 但没有客户端 `tool_search` 时返回参数错误,避免把原本延迟的工具静默改成立即可调用。
- 服务端托管 Tool Search 需要上游在同一次推理中搜索并注入工具,当前无法等价模拟,因此缺省或 `execution: "server"` 会返回 `400 unsupported_parameter`,不会静默展开全部延迟工具。
- `additional_tools` 中的定义会进入上游顶层工具集合,同时在原输入位置保留 developer 边界消息,提示这些工具从该位置开始可用。由于 0.2.99 没有位置化工具定义,响应会携带 `additional_tools_position_approximated` 兼容警告。
`0.2.99` OAuth 上游实测原生工具 discriminator 为 `function`、`web_search`、`x_search`、`image_generation`、`collections_search`、`file_search`、`code_execution`、`code_interpreter`、`mcp` 和 `shell`。其中 `collections_search` 需要 `vector_store_ids`,`shell` 需要 `environment`;网关保留这些原生工具参数交由上游校验。旧 Codex `local_shell` 会升级为 `shell + environment.type=local`,JSON/SSE 中的 `shell_call` 恢复为 `local_shell_call`,续轮输出升级为结构化 `shell_call_output`;同一请求不能混用新旧 shell 声明。
`apply_patch` 不在 0.2.99 上游枚举中,网关将其包装为具有严格 operation schema 的内部 function,并在 JSON、SSE 和续轮历史中双向恢复 `apply_patch_call`/`apply_patch_call_output`。流式 function 参数事件不会泄露给 Codex;网关等待 operation 完整后再发出标准 output item added/done。`computer_use_preview` 涉及截图与动作循环,无法安全等价模拟,继续返回明确的不支持错误。
`web_search_preview` 及其版本别名会转换为最小 `web_search` 声明;当前上游会以 `Argument not supported` 拒绝 Codex/OpenAI 新版的 `external_web_access`、`indexed_web_access`、`search_content_types`、`search_context_size`、`user_location` 和 `filters` 等控制字段,因此兼容层会将可安全放宽的已知字段降级为 0.2.99 的最小搜索声明。遇到 `external_web_access: false` 时会移除整个 Web Search 工具,并将显式选择该工具的 `tool_choice` 收敛为 `none`,确保不会把“禁止外网”静默扩大为可联网搜索;这会禁用包括索引搜索在内的全部 Web Search,并通过兼容警告公开该降级。非空 `filters` 或 `allowed_domains` 等无法用更严格子集等价执行的范围约束仍会明确拒绝;其他未知字段同样报错。
OpenAI `custom` 工具会转换为只接受 `input` 字符串的普通函数,并在 JSON/SSE 响应及续轮历史中恢复为 `custom_tool_call`、`custom_tool_call_output` 和 `response.custom_tool_call_input.*` 事件。纯文本 format 可兼容;grammar 无法等价表达,会返回 `unsupported_parameter`。
Codex 的可见 `agent_message` 与 `mcp_tool_call_output` 会保留为 developer 文本;`local_shell_call/output` 与 `apply_patch_call/output` 保持结构化续轮协议。不透明或加密的 agent 内容会替换为不含密文的边界消息,`compaction_trigger` 会替换为压缩边界消息,避免静默丢弃或让整轮失败。SSE 兼容层只向下游保留标准 `response.*`、`error` 与 `[DONE]`,过滤上游私有事件,同时保留标准 comment、`id` 和 `retry` 字段。
发生协议降级时,响应 Header `X-Grok2API-Compatibility-Warnings` 会返回稳定的逗号分隔代码,例如 `web_search_controls_downgraded`、`web_search_disabled_no_external_access`、`web_search_tool_choice_disabled`、`legacy_local_shell_upgraded`、`apply_patch_emulated`、`additional_tools_position_approximated`。客户端可记录这些代码进行审计,不包含提示词、工具参数或凭据。
Chat Completions 与 Messages 都先转换为标准 Responses 输入项。Build 与 Console 将其发送到各自的 Responses 上游,并把 JSON/SSE 转回调用方协议;Web 再把同一规范输入转换为 app-chat 对话载荷。不支持的音频、Files API、Anthropic server tools,以及 Web/Console `/responses/compact` 会返回明确错误,不会静默丢弃。
Anthropic Messages 使用 `POST /v1/messages`,要求 `anthropic-version`,客户端密钥可通过 `x-api-key` 或 `Authorization: Bearer` 提供。返回使用 Anthropic `message` 对象;流式事件依次为 `message_start`、`content_block_*`、`message_delta` 和 `message_stop`。由于上游不是 Claude,模型 ID 仍使用本平台公开 Grok 模型名称。
Messages 转换层兼容 Claude Code 常见载荷:标准顶层 `system` 与误放在 `messages` 数组中的 `system`/`developer` 都会按原顺序合并为 Responses `instructions`,不会再因 `role: "system"` 返回 400。请求固定使用 `store: false`;`metadata.user_id` 映射为 `safety_identifier`。`thinking.enabled`/`thinking.adaptive` 会依据 `budget_tokens` 和 effort 映射到 Grok reasoning,并请求 `reasoning.encrypted_content`;JSON 与 SSE 会恢复 `thinking_delta`、`signature_delta`、`thinking` 或 `redacted_thinking`,便于下一轮原样回放,不伪造签名。
客户端工具支持 `strict`、`tool_choice.disable_parallel_tool_use`、严格的 `tool_use`/`tool_result` 配对和重复 ID 校验;带 `is_error` 的结果会保留失败语义。`tool_result` 可包含文本、图片、文档和 Anthropic `tool_reference`;引用只允许指向本次请求已声明的工具,并转换为确定性的搜索命中结果,因为对应工具定义已随请求提供给 Build。Messages 普通输入也支持 URL/Base64 图片、文本 document,以及 Build 上游可处理的 URL/Base64 `input_file`。Build 可把 `mcp_servers` 转换为原生 MCP 工具;Grok Web 对无法等价执行的 MCP 或文件内容返回明确错误。`stop_sequences` 在 JSON/SSE 下由网关跨内容块、跨增量执行并返回真实 `stop_sequence`;无法等价表示的 `top_k` 会在请求上游前明确拒绝。
图片编辑严格使用 xAI 当前 JSON 结构:`image.url` 或 `images[].url` 可使用公网 HTTPS URL 或 Base64 data URI,数量参数使用 `n`,`resolution` 支持 `1k`、`2k` 且默认 `1k`。不接受 multipart 或 `image_count` 等非官方兼容字段。当前未实现 Files API,因此 `image.file_id` 会返回明确的不支持错误。
## Usage
审计记录保存:
- `input_tokens`
- `input_tokens_details.cached_tokens`
- `output_tokens`
- `output_tokens_details.reasoning_tokens`
- `total_tokens`
- `cost_in_usd_ticks`
- `num_sources_used`
- `num_server_side_tools_used`
- `context_details.input_tokens/output_tokens`
- `media_input_images`
- `media_output_images`
- `media_output_seconds`
- `egress_mode`(`proxy` 或 `direct`)
- `egress_scope`
- `egress_node_id` / `egress_node_name`(出口节点快照)
不保存 prompt、response body、encrypted reasoning 内容、工具参数、代理 URL、代理认证信息、User-Agent 或 Cookie。
Grok Web 未提供与公开 API 等价的精确 Token 计量,因此聊天审计标记 `usageSource: estimated`;图片和视频标记 `usageSource: none`,不会伪造 Token,用量费用仅按已配置的官方媒体单价估算。
Grok Web 付费账号使用 `GrokBuildBilling/GetGrokCreditsConfig` 返回的统一周额度池:保存真实使用百分比、产品枚举分解、周期起止和重置时间,并作为 Chat、Imagine、图片编辑和视频共享的路由总闸门。成功调用后异步刷新周池,不按未知权重进行本地伪扣减;耗尽后按真实周重置时间进入单次恢复队列。
Free 账号先探测 gRPC 周池;没有有效周池时固定使用 `/rest/rate-limits` 的 `fast` 窗口及其真实重置时间。明确导入为 Super/Heavy 的账号只请求 gRPC 周池;`auto` 账号发现有效周池后先归为 Super,Heavy 需由导入等级明确指定,直到获得可验证的官方等级字段。全量同步会替换旧额度快照,避免升降级后残留窗口误导路由和 UI。
Free 的 429 会耗尽 `fast` 并按模式重置时间恢复。付费周池的 429 不直接置零:网关立即重新请求 gRPC,只有上游确认使用率达到 100% 才进入待重置队列;若周池尚未耗尽或同步失败,则按普通短期限流冷却并尝试其他账号。产品分解的 protobuf 枚举在获得官方 schema 前按数字原样保存,不猜测映射名称。
周池产品枚举为:`0 = Third Party`、`1 = API`、`2 = Grok Build`、`3 = Grok Plugins`、`4 = Chat`、`5 = Imagine`、`6 = Voice`。其中样本响应的 `Imagine 10% + Chat 1% = 总使用 11%` 已与 Grok Usage 页面交叉验证。管理端按真实百分比分段绘制进度条,零使用产品不显示;未来出现的未知枚举仍保留原始编号并使用通用标签。
### Image Generation
图片生成遵循 xAI REST API 的 `POST /v1/images/generations`:`n` 范围为 `1..10`,`aspect_ratio` 支持官方 Grok Imagine 枚举,`resolution` 支持 `1k` 与 `2k`。内部 WebSocket 将 `1k` 映射为 Speed、`2k` 映射为 Quality,并按 `n` 选择最小原生批次:`1..4 -> 4`、`5..8 -> 8`、`9..10 -> 12`,最终只返回请求的 `n` 张。
`size` 继续作为 OpenAI 客户端兼容别名;同时提供 `aspect_ratio` 时以后者为准。当前项目没有实现 xAI Files API,因此 `storage_options` 会返回明确的不支持错误,不会静默忽略。
所有生成图片都会在账号和出口租约释放前统一归档。WebSocket `blob` 会解码为二进制;只有上游 URL 时会使用原账号的资产出口下载。文件写入 `media.local.path`,数据库仅保存资源元数据。`response_format: url` 返回后端 `/v1/media/images/{id}`,`b64_json` 从同一份已归档字节编码,二者不会分别下载或保存两份。资源 ID 使用不可猜测随机值,读取端点支持 `GET`、`HEAD`、ETag 和不可变缓存头。
本地媒体默认容量上限为 `1 GiB`,自动清理阈值为 `80%`。占用超过阈值后按创建时间从旧到新删除,直到回落到阈值以内;保存图片会触发容量检查,后台每 `10m` 兜底执行。Memory/Redis 运行态均通过清理锁避免同一共享目录被多个实例同时清理。单图上限、容量、自动清理阈值和检查间隔由设置页管理并立即热加载;YAML 只保留存储驱动和本地目录,修改这两项需要重启。
`stream: true` 是 grok2api 扩展,不属于 xAI 官方 Images REST 字段。启用后响应为 SSE:先发送 `image_generation.started`,每张图片完成后发送 `image_generation.image.completed`,最后发送 `image_generation.completed` 与 `[DONE]`。首个事件写出后账号、出口节点和 WebSocket 均保持固定,不会跨账号拼接。Lite 模型在 `/v1/images/generations` 不支持该扩展,但可通过 `/v1/chat/completions` 流式返回图片。
### Video Generation
视频公共接口严格采用 xAI 官方异步协议。`POST /v1/videos/generations` 接受 `model`、`prompt`、`user`、`duration`、`aspect_ratio`、`resolution`、`image` 和 `reference_images`,成功仅返回 `request_id`。`duration` 按官方规则接受整数或整数字符串;不接受 `seconds`、`image_url`、`size`、`quality`、`input_reference` 等非原生字段。当前支持公网 HTTPS 或 Base64 data URI 图片;尚未实现 Files API,因此 `file_id` 会返回明确的不支持错误。`output.upload_url` 与 `storage_options` 同样不会被静默忽略。
`GET /v1/videos/{request_id}` 将内部任务状态映射为官方 `pending`、`done`、`failed`。完成响应在 `video` 中返回 `url`、`duration` 与 `respect_moderation`;失败响应只返回官方错误枚举和消息,不暴露账号、上游 Post ID、租约或数据库字段。当前不开放 `/videos/edits`、`/videos/extensions` 或独立内容代理端点。
## Grok Web SSO Import
标准导入格式:
```json
{
"provider": "grok_web",
"accounts": [
{ "name": "Web Account 01", "sso_token": "...", "tier": "auto" }
]
}
```
JSON 只接受当前 `accounts` 结构。SSO 不存在自动刷新:上游返回 401 后账号会标记为 `reauthRequired` 并退出号池。
也支持纯文本快速导入,每个非空行视为一个 SSO Token;可直接填写 Token 或 `sso=...` Cookie 形式。重复 Token 自动忽略,导入后仍会等待该批账号的首次额度与模型同步完成。
## Cloudflare And Egress
- Grok Build 使用标准 Go HTTP/TLS 传输并保持 CLI User-Agent;通过代理时仍沿用该传输,不切换成浏览器指纹。Grok Web HTTP 使用 Chrome TLS/HTTP2 指纹;Imagine 使用同一代理、User-Agent 和 Cookie Bundle 的 WebSocket 客户端。
- 每次上游 HTTP 请求生成独立 UUID v4 `x-xai-request-id`,并携带与浏览器同源 fetch 一致的最小稳定请求头;不伪造 Client Hints、Sentry、trace 数据或手工 HTTP/2 头顺序。
- 设置页支持两种 `x-statsig-id` 来源:手动模式直接使用管理员写入的固定值,不自动失效、刷新或替换;URL 模式会先使用同一账号、出口节点、User-Agent 与 Cookie 访问 `https://grok.com/index`,读取 `grok-site-verification` meta,再把请求 method、path 和 metaContent 发送到配置的签名服务。默认签名 URL 是 `https://grok.wodf.de/sign`。URL 签名按 method/path 缓存;Code 7 会立即强制刷新并替换旧值,刷新失败时保留上一个真实签名,绝不发送随机占位签名。
- URL 模式按 `method + path` 在当前实例内共享一份签名,跨账号复用并缓存 1 小时;不同路径不会混用。并发刷新使用 singleflight 合并,缓存最多保存 4096 个路径,过期项会及时清理。签名服务不会收到 SSO、Cloudflare Cookie、提示词或响应正文。公网签名服务必须使用无凭据、查询参数或片段的 HTTPS:443 地址;Docker 单标签服务名、localhost、`.local/.internal` 和私有地址可使用 HTTP/HTTPS 与自定义端口,例如 `http://grok-signer-go:8788/sign`。签名请求不跟随重定向。手动值仅写入,管理接口只返回是否已配置。
- HTTP 403 或流首包 Code 7 会在任何内容写给客户端前立即失效对应路径的缓存,重新获取 meta 并重签一次。首次失效不处罚代理节点;刷新后仍失败才反馈出口健康并返回反机器人错误。流已经开始后绝不重放或拼接第二条响应。
- 手动 Cookie 只保留 `cf_clearance`、`__cf_bm`、`_cfuvid` 和 `cf_chl_*`。
- 不配置、存储或发送 `grok_device_id`、`x-anonuserid`、`x-userid`、`x-challenge`、`x-signature`。
- `/index` 响应中的 `Set-Cookie` 不进入 Cookie Jar,也不会写库或转发;即使上游下发 `x-userid` 也会被丢弃。
- `sso`、`sso-rw` 始终从当前账号的加密 SSO Token 生成。
- Clearance 与出口节点绑定;403 或挑战只重建当前节点会话并降低健康分,下一次优先选择更健康节点,不会冷却或移除账号。
- User-Agent 必须与获取 Clearance 时一致。当前 TLS 客户端使用其最新 Chrome 146 profile;自定义为 Firefox、Safari 等非 Chromium UA 会造成明显指纹不一致。
- 出口节点按 `Grok Build`、`Grok Web`、`Grok Console`、`Grok Web(仅资源)` 四个作用域独立管理代理、健康度和冷却状态。Grok Build 始终沿用 Provider 的 CLI User-Agent,节点不能覆盖;Grok Web、Console 和 Web 资源节点独立管理浏览器 User-Agent 与 Cloudflare Cookie。Web 资源未配置专用节点时仅回退到 Grok Web 节点。
- 代理地址支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5 与 SOCKS5H,可携带用户名和密码。Cloudflare Cookie 只适用于 Grok Web。
- 配置过对应作用域的出口节点后,如果全部节点不可用,服务不会静默退回直连;只有该作用域完全没有配置节点时才使用 direct。Grok Build 未配置节点时保持原有标准 HTTP 直连。
- 首版仅支持 `none/manual` Clearance,不接 FlareSolverr。
`cost_in_usd_ticks` 是 xAI 公开 Responses 成本字段。Build OAuth 实测响应中 Free 请求返回 `0`,但字段仍按原值透传并进入审计。
`grok-code-fast*` 与 `grok-composer-2.5-fast` 按 `grok-build-0.1` 价格估算:标准输入 `$1.00 / 1M Tokens`、缓存输入 `$0.20`、输出 `$2.00`;Context 超过 200k 后分别为 `$2.00`、`$0.40`、`$4.00`。
文本计费模型会先移除系统已知的 `Build/`、`Web/`、`Console/` 来源前缀,再匹配官方精确名称和锚定的模型家族规则。该规则兼容 `latest`、日期、Build Free、reasoning、non-reasoning、multi-agent 等版本后缀,但不会用子串包含方式为未知模型套用价格。
Grok Web Chat 不返回官方 usage,输入、输出与推理 Token 由网关估算并标记为 `usageSource=estimated`。Web 来源的 `grok-chat-fast`、`grok-chat-auto`、`grok-chat-expert`、`grok-chat-heavy` 统一使用官方 `grok-4.5` Token 单价计算估算费用;图片、图片编辑和视频不伪造 Token。
Web 来源的 `grok-imagine-image-quality` 按客户端请求参数 `n` 计费:1K 为 `$0.05 × n`,2K 为 `$0.07 × n`。上游为了满足请求采用 4/8/12 原生批次时,不按原生批次数量多计费。`grok-imagine-image` 固定为 `$0.02 × n`,不区分 resolution。
Web 来源的 `grok-imagine-image-edit` 输出图片按 1K `$0.05 × n`、2K `$0.07 × n` 计费,并按输入图片数量额外计入 `$0.01 × input_images`。`grok-imagine-video` 按请求时长计费:480p 为 `$0.08 × seconds`,720p 为 `$0.14 × seconds`;没有已配置价格的分辨率保持未计费。媒体审计不写入伪造 Token,只保存价格、模型和价格版本。
## Response Headers
网关保留 `Content-Type`、请求追踪和上游限流等端到端响应头。HTTP hop-by-hop headers、`Connection` 动态声明的逐跳头、`Content-Length` 以及上游 `Set-Cookie` 不会转发给下游,避免连接级状态和上游会话凭据穿透代理边界。
## Transfer Limits
请求体默认最大 `32 MiB`。非流式响应以 `128 MiB`、流式响应以 `256 MiB` 作为单请求传输安全上限,并使用固定小缓冲直接转发。JSON usage 与单条 SSE 事件的内存检查上限为 `8 MiB`;超出时正文仍继续转发,但该次请求可能无法提取 usage、模型或 Response ID。
## Build Billing Observation
Grok Build `0.2.93` 实测使用 `GET /billing` 与 `GET /billing?format=credits`。网关保存真实出现的 `monthlyLimit`、`used`、`onDemandCap`、`onDemandUsed`、`prepaidBalance`、`isUnifiedBillingUser`、`topUpMethod`、`currentPeriod.type` 和历史账期。
这些端点没有公开 xAI 字段契约,因此实现遵守以下限制:
- Billing 全零本身不证明 Free,`isUnifiedBillingUser: true` 也不证明付费;但完整匹配已捕获的 weekly/unified/top-up Free Profile 时可标记为 `estimated`。
- 估算态使用约 1M 作为管理端参考值,并通过 `confidence: estimated` 与 `limitKnown: false` 明确标识,不参与上游确认语义。
- 真实响应模型以 `-build-free` 结尾时标记为 `observed`;上游返回 Free 耗尽 `actual/limit` 后标记为 `confirmed` 并覆盖估算值。
- 升级 Grok Build 版本时使用脱敏 fixture 重新验证 Billing 和 Responses 字段。
## Model Capabilities
模型发现以账号为粒度执行。每个账号保存最后一次成功返回的模型集合,公开模型目录使用所有账号能力的并集。请求路由只使用已确认支持目标上游模型的账号;未完成首次能力同步的账号可以作为兼容回退,已确认不支持的账号不会参与该模型的负载均衡。
会员等级只使用上游 Billing 明确返回的 plan/tier 元数据展示,不通过额度大小反推套餐名称。路由决策以实际模型能力快照为准,因此即使两个付费账号的套餐名称不同,只要模型集合不同,也会被正确拆分处理。
同步失败不会删除最后一次成功快照。只有当全部活跃账号均已完成同步且都不支持某个模型时,该模型才会从 `GET /v1/models` 和新请求路由中移除。既有 `previous_response_id` 状态链仍遵守原账号归属,不会为切换会员等级而跨账号迁移。
## Version Contract
当前 Grok Build 基线为 `0.2.99`:
- `x-grok-client-version: 0.2.99`
- `x-grok-client-identifier: grok-shell`
- `User-Agent: grok-shell/0.2.99 (linux; x86_64)`
升级 CLI 版本时必须重新运行请求捕获和以下回归:首轮文本、stateless encrypted reasoning 续轮、stateful `previous_response_id`、函数调用、namespace、客户端 Tool Search、结构化输出、SSE usage、compact、retrieve 与 delete。
## Upstream Boundary
公开 xAI API 文档:
- https://docs.x.ai/build/overview
- https://docs.x.ai/developers/rest-api-reference/inference/chat
- https://docs.x.ai/developers/model-capabilities/text/generate-text
OpenAI Responses 参考:
- https://platform.openai.com/docs/api-reference/responses
- https://developers.openai.com/api/docs/guides/tools-shell
- https://developers.openai.com/api/docs/guides/tools-local-shell
- https://developers.openai.com/api/docs/guides/tools-apply-patch
`cli-chat-proxy.grok.com` 是 Grok Build 产品上游,不是公开、长期稳定的第三方 API 契约。项目通过版本锁定和协议回归降低变化风险,但不能承诺跨未知未来版本的零变更兼容。
+4 -1
View File
@@ -37,6 +37,7 @@ import (
"github.com/chenyme/grok2api/backend/internal/pkg/batch"
"github.com/chenyme/grok2api/backend/internal/repository"
httpserver "github.com/chenyme/grok2api/backend/internal/transport/http"
httpmiddleware "github.com/chenyme/grok2api/backend/internal/transport/http/middleware"
)
// Application 管理后端进程生命周期和本地后台任务。
@@ -237,6 +238,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
gatewayService.ConfigureMedia(mediaJobRepo, cfg.Provider.Web.MediaConcurrency)
quotaRecoveryService := quotarecoveryapp.NewService(logger, quotaQueue, accountService, cfg.Provider.Web.RecoveryBackoffBase.Value(), cfg.Provider.Web.RecoveryBackoffMax.Value())
quotaRecoveryService.SetBulkPool(syncPool)
inferenceConcurrency := httpmiddleware.NewConcurrencyGate(cfg.Server.MaxConcurrentRequests)
var notifySettings func(context.Context)
if settingsBus != nil {
notifySettings = func(notifyCtx context.Context) {
@@ -248,6 +250,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
}
}
settingsService := settingsapp.NewService(cfg, settingsUpdatedAt, settingsRevision, runtimeSettingsRepo, notifySettings, func(next config.Config) {
inferenceConcurrency.UpdateLimit(next.Server.MaxConcurrentRequests)
bulkPool.UpdateLimit(maxBatchConcurrency(next.Batch))
importPool.UpdateLimit(next.Batch.ImportConcurrency)
conversionPool.UpdateLimit(next.Batch.ConversionConcurrency)
@@ -277,7 +280,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat
readiness := func(readyCtx context.Context) httpserver.ReadinessSnapshot {
return readinessSnapshot(readyCtx, startup, runtimeHealth, modelRepo, accountRepo, providers)
}
router := httpserver.New(httpserver.Dependencies{Logger: logger, RequestTimeout: cfg.Server.RequestTimeout.Value(), MaxBodyBytes: cfg.Server.MaxBodyBytes, SecureCookies: cfg.Auth.SecureCookies, SwaggerEnabled: cfg.Server.SwaggerEnabled, PublicAPIBaseURL: cfg.Frontend.EffectivePublicAPIBaseURL(), FrontendStaticPath: cfg.Frontend.StaticPath, Readiness: readiness, TrafficReady: startup.acceptsTraffic, AdminAuth: adminService, Accounts: accountService, AccountSync: accountSyncService, Models: modelService, ClientKeys: clientKeyService, Audits: auditService, Dashboard: dashboardService, Gateway: gatewayService, Media: mediaService, Settings: settingsService, Egress: egressService})
router := httpserver.New(httpserver.Dependencies{Logger: logger, RequestTimeout: cfg.Server.RequestTimeout.Value(), MaxBodyBytes: cfg.Server.MaxBodyBytes, ConcurrencyGate: inferenceConcurrency, SecureCookies: cfg.Auth.SecureCookies, SwaggerEnabled: cfg.Server.SwaggerEnabled, PublicAPIBaseURL: cfg.Frontend.EffectivePublicAPIBaseURL(), FrontendStaticPath: cfg.Frontend.StaticPath, Readiness: readiness, TrafficReady: startup.acceptsTraffic, AdminAuth: adminService, Accounts: accountService, AccountSync: accountSyncService, Models: modelService, ClientKeys: clientKeyService, Audits: auditService, Dashboard: dashboardService, Gateway: gatewayService, Media: mediaService, Settings: settingsService, Egress: egressService})
server := &http.Server{Addr: cfg.Server.Listen, Handler: router, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: cfg.Server.ReadTimeout.Value(), IdleTimeout: 2 * time.Minute, MaxHeaderBytes: 64 << 10}
return &Application{
logger: logger, database: database, server: server,
@@ -1,6 +1,16 @@
package account
import "testing"
import (
"context"
"path/filepath"
"sync/atomic"
"testing"
"time"
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/infra/persistence/relational"
"github.com/chenyme/grok2api/backend/internal/infra/provider"
)
func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) {
service := NewService(nil, nil, nil, nil, nil, nil, nil)
@@ -23,3 +33,98 @@ func TestWebQuotaRefreshDeduplicatesPerMode(t *testing.T) {
t.Fatalf("queued refreshes = %d", len(service.quotaRefreshQueue))
}
}
func TestRefreshQuotaModeDoesNotTriggerFullProviderSyncForAutoTier(t *testing.T) {
ctx := context.Background()
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quota-mode.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = database.Close() })
if err := database.InitializeSchema(ctx); err != nil {
t.Fatal(err)
}
accounts := relational.NewAccountRepository(database)
credential, _, err := accounts.UpsertByIdentity(ctx, accountdomain.Credential{
Provider: accountdomain.ProviderWeb, AuthType: accountdomain.AuthTypeSSO,
Name: "web-auto", SourceKey: "web-auto", EncryptedAccessToken: "encrypted",
Enabled: true, AuthStatus: accountdomain.AuthStatusActive, WebTier: accountdomain.WebTierAuto,
})
if err != nil {
t.Fatal(err)
}
adapter := &quotaCountingAdapter{}
service := NewService(accounts, nil, nil, nil, provider.NewRegistry(adapter), nil, nil)
window, err := service.RefreshQuotaMode(ctx, credential.ID, "fast")
if err != nil {
t.Fatal(err)
}
if window.Mode != "fast" || adapter.modeCalls.Load() != 1 || adapter.fullCalls.Load() != 0 {
t.Fatalf("window = %#v, mode calls = %d, full calls = %d", window, adapter.modeCalls.Load(), adapter.fullCalls.Load())
}
stored, err := accounts.Get(ctx, credential.ID)
if err != nil {
t.Fatal(err)
}
if stored.WebTier != accountdomain.WebTierAuto {
t.Fatalf("single-mode sync changed tier to %q", stored.WebTier)
}
service.QueueQuotaRefresh(credential.ID, "fast")
service.QueueQuotaRefresh(credential.ID, "fast")
request := <-service.quotaRefreshQueue
service.runWebQuotaRefresh(ctx, request)
if adapter.modeCalls.Load() != 2 || adapter.fullCalls.Load() != 0 {
t.Fatalf("coalesced mode calls = %d, full calls = %d", adapter.modeCalls.Load(), adapter.fullCalls.Load())
}
service.quotaRefreshMu.Lock()
_, queued := service.quotaRefreshes[request.key]
service.quotaRefreshMu.Unlock()
if queued {
t.Fatal("completed coalesced refresh retained queue state")
}
service.refreshLock = deniedQuotaRefreshLock{}
service.QueueQuotaRefresh(credential.ID, "fast")
request = <-service.quotaRefreshQueue
service.runWebQuotaRefresh(ctx, request)
if adapter.modeCalls.Load() != 2 {
t.Fatalf("worker without distributed lease made %d mode calls", adapter.modeCalls.Load())
}
}
type deniedQuotaRefreshLock struct{}
func (deniedQuotaRefreshLock) Acquire(context.Context, string, time.Duration) (func(), bool, error) {
return nil, false, nil
}
type quotaCountingAdapter struct {
modeCalls atomic.Int64
fullCalls atomic.Int64
}
func (a *quotaCountingAdapter) Provider() accountdomain.Provider { return accountdomain.ProviderWeb }
func (a *quotaCountingAdapter) Definition() provider.Definition {
return provider.Definition{
Provider: accountdomain.ProviderWeb, ModelNamespace: accountdomain.ProviderWeb.ModelNamespace(),
Quota: provider.QuotaRemoteWindow, Credential: provider.CredentialSurface{AuthType: accountdomain.AuthTypeSSO},
}
}
func (a *quotaCountingAdapter) SyncQuota(context.Context, accountdomain.Credential) (provider.QuotaSnapshot, error) {
a.fullCalls.Add(1)
return provider.QuotaSnapshot{}, nil
}
func (a *quotaCountingAdapter) SyncQuotaMode(_ context.Context, credential accountdomain.Credential, mode string) (accountdomain.QuotaWindow, error) {
a.modeCalls.Add(1)
now := time.Now().UTC()
resetAt := now.Add(time.Hour)
return accountdomain.QuotaWindow{
AccountID: credential.ID, Mode: mode, Remaining: 0, Total: 30,
WindowSeconds: 3600, ResetAt: &resetAt, SyncedAt: &now, Source: accountdomain.QuotaSourceUpstream, UpdatedAt: now,
}, nil
}
+30 -15
View File
@@ -1602,15 +1602,9 @@ func (s *Service) refreshQuotaMode(ctx context.Context, id uint64, mode string)
var tier accountdomain.WebTier
quotaKind, _ := s.providers.QuotaKind(value.Provider)
if quotaKind == provider.QuotaRemoteWindow {
// 单模式核实只负责更新本次 429 对应的窗口。套餐判级由完整额度同步负责;
// 这里再次调用 SyncQuota 会重复请求当前模式,并额外访问其他额度端点。
tier = value.WebTier
if tier == "" || tier == accountdomain.WebTierAuto {
if snapshot, syncErr := adapter.SyncQuota(ctx, value); syncErr == nil {
tier = snapshot.Tier
_ = s.accounts.ReplaceQuotaWindows(ctx, id, snapshot.Tier, snapshot.SyncedAt, snapshot.Windows)
} else {
tier = accountdomain.WebTierBasic
}
}
}
now := time.Now().UTC()
if err := s.accounts.SaveQuotaWindows(ctx, id, tier, now, []accountdomain.QuotaWindow{window}); err != nil {
@@ -1691,6 +1685,17 @@ func (s *Service) RunWebQuotaRefresh(ctx context.Context) {
func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRefreshRequest) {
for {
// Worker 开始前已经合并的重复请求由本轮远端快照覆盖。只有网络请求
// 进行期间再次到达的调用才需要尾随刷新,避免每个突发批次固定请求两次。
s.quotaRefreshMu.Lock()
state := s.quotaRefreshes[request.key]
if state == nil {
s.quotaRefreshMu.Unlock()
return
}
state.pending = false
s.quotaRefreshMu.Unlock()
ctx, cancel := context.WithTimeout(parent, webQuotaRefreshTimeout)
refreshMode := request.mode
if windows, err := s.accounts.GetQuotaWindows(ctx, []uint64{request.accountID}); err == nil {
@@ -1703,11 +1708,21 @@ func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRef
}
if refreshMode != "" {
var refreshErr error
if err := s.syncPool.Do(ctx, func(workCtx context.Context) error {
_, refreshErr = s.RefreshWebQuotaMode(workCtx, request.accountID, refreshMode)
return refreshErr
}); err != nil {
refreshErr = err
acquired := true
var release func()
if s.refreshLock != nil {
release, acquired, refreshErr = s.refreshLock.Acquire(ctx, "quota-refresh:"+request.key, webQuotaRefreshTimeout)
}
if refreshErr == nil && acquired {
if err := s.syncPool.Do(ctx, func(workCtx context.Context) error {
_, refreshErr = s.RefreshWebQuotaMode(workCtx, request.accountID, refreshMode)
return refreshErr
}); err != nil {
refreshErr = err
}
}
if release != nil {
release()
}
if refreshErr != nil && !errors.Is(refreshErr, context.Canceled) {
s.logger.Warn("web_quota_refresh_failed", "account_id", request.accountID, "mode", refreshMode, "error", refreshErr)
@@ -1716,7 +1731,7 @@ func (s *Service) runWebQuotaRefresh(parent context.Context, request webQuotaRef
cancel()
s.quotaRefreshMu.Lock()
state := s.quotaRefreshes[request.key]
state = s.quotaRefreshes[request.key]
if state != nil && state.pending {
state.pending = false
s.quotaRefreshMu.Unlock()
@@ -1915,7 +1930,7 @@ func (s *Service) runAccountBatch(ctx context.Context, operation string, ids []u
func (s *Service) logBatchSummary(operation string, pool *batch.Pool, summary batch.Summary, err error) {
snapshot := pool.Snapshot()
s.logger.Info("account_bulk_completed", "operation", operation, "total", summary.Total, "submitted", summary.Submitted, "succeeded", summary.Succeeded, "failed", summary.Failed, "panicked", summary.Panicked, "duration_ms", summary.Duration.Milliseconds(), "canceled", summary.Canceled, "pool_limit", snapshot.Limit, "pool_active", snapshot.Active, "pool_peak", snapshot.Peak, "error", err)
s.logger.Info("account_bulk_completed", "operation", operation, "total", summary.Total, "submitted", summary.Submitted, "succeeded", summary.Succeeded, "failed", summary.Failed, "panicked", summary.Panicked, "duration_ms", summary.Duration.Milliseconds(), "canceled", summary.Canceled, "pool_limit", snapshot.Limit, "pool_active", snapshot.Active, "pool_queued", snapshot.Queued, "pool_peak", snapshot.Peak, "error", err)
}
func (s *Service) persistSeed(ctx context.Context, seed provider.CredentialSeed) (accountdomain.Credential, bool, error) {
@@ -114,7 +114,7 @@ func (s *Service) get(ctx context.Context, rawPeriod, rawTimezone string, useCac
func (s *Service) load(ctx context.Context, period Period, bucketCount, bucketDays int, location *time.Location, rawNow time.Time) (Result, error) {
now := rawNow.In(location)
series := buildSeries(now, period, bucketCount, bucketDays)
boundaries := make([]time.Time, 0, len(series)+1)
boundaries := make([]time.Time, 0, len(series))
for _, point := range series {
boundaries = append(boundaries, point.Start)
}
@@ -0,0 +1,279 @@
package gateway
import (
"context"
"fmt"
"net/http"
"sync"
"time"
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/domain/audit"
"github.com/chenyme/grok2api/backend/internal/domain/clientkey"
modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model"
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
"github.com/chenyme/grok2api/backend/internal/infra/provider"
)
// ImageGenerationInput 表示图片生成用例已经完成协议校验后的输入。
type ImageGenerationInput struct {
RequestID string
ClientKey clientkey.Key
PublicModel string
Prompt string
Count int
Size string
AspectRatio string
Resolution string
ResponseFormat string
Streaming bool
}
// ImageEditInput 表示图片编辑用例已经完成协议校验后的输入。
type ImageEditInput struct {
RequestID string
ClientKey clientkey.Key
PublicModel string
Prompt string
ImageURLs []string
Count int
Resolution string
ResponseFormat string
}
type imageProviderSupport func(accountdomain.Provider) bool
type imageExecution func(context.Context, accountdomain.Provider, accountdomain.Credential, string) (*provider.Response, error)
// GenerateImage 选择支持图片生成的路由和账号,并返回可统一审计的上游响应。
func (s *Service) GenerateImage(ctx context.Context, input ImageGenerationInput) (*Result, error) {
return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImage, modeldomain.CapabilityImage, func(providerValue accountdomain.Provider) bool {
_, ok := s.providers.ImageGeneration(providerValue)
return ok
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
adapter, ok := s.providers.ImageGeneration(providerValue)
if !ok {
return nil, ErrNoAvailableAccount
}
return adapter.GenerateImage(executionCtx, provider.ImageGenerationRequest{
Credential: credential, Model: upstream, Prompt: input.Prompt, Count: input.Count,
Size: input.Size, AspectRatio: input.AspectRatio, Resolution: input.Resolution,
ResponseFormat: input.ResponseFormat, Streaming: input.Streaming,
})
}, input.Streaming, input.Resolution, input.Count, 0)
}
// EditImage 选择支持图片编辑的路由和账号,并返回可统一审计的上游响应。
func (s *Service) EditImage(ctx context.Context, input ImageEditInput) (*Result, error) {
return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImageEdit, modeldomain.CapabilityImageEdit, func(providerValue accountdomain.Provider) bool {
_, ok := s.providers.ImageEdit(providerValue)
return ok
}, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
adapter, ok := s.providers.ImageEdit(providerValue)
if !ok {
return nil, ErrNoAvailableAccount
}
return adapter.EditImage(executionCtx, provider.ImageEditRequest{
Credential: credential, Model: upstream, Prompt: input.Prompt,
ImageURLs: input.ImageURLs, Count: input.Count, Resolution: input.Resolution, ResponseFormat: input.ResponseFormat,
})
}, false, input.Resolution, input.Count, len(input.ImageURLs))
}
func (s *Service) executeImage(
ctx context.Context,
requestID string,
key clientkey.Key,
publicModel string,
operation audit.Operation,
capability modeldomain.Capability,
supports imageProviderSupport,
execute imageExecution,
streaming bool,
resolution string,
requestedCount int,
inputImageCount int,
) (*Result, error) {
ctx, egressTrace := infraegress.WithTrace(ctx)
startedAt := time.Now()
eventID := newAuditEventID()
routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel)
if err != nil {
return nil, ErrModelNotFound
}
route, err := s.selectMediaRoute(routes, key, capability, supports)
if err != nil {
return nil, err
}
externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID)
auditBase := audit.Record{
EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name,
ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel),
Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, Streaming: streaming,
}
if operation == audit.OperationImageEdit {
auditBase.MediaInputImages = int64(max(0, inputImageCount))
}
writeFailureAudit := func(statusCode int, errorCode string, credential *accountdomain.Credential) {
record := auditBase
record.StatusCode = statusCode
record.ErrorCode = errorCode
record.DurationMS = time.Since(startedAt).Milliseconds()
record.CreatedAt = time.Now().UTC()
if credential != nil {
accountID := credential.ID
record.AccountID = &accountID
record.AccountName = credential.Name
}
applyAuditEgress(&record, egressTrace, route.Provider)
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
defer cancel()
if auditErr := s.audits.Create(persistCtx, record); auditErr != nil {
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", auditErr)
}
}
pricingModel := s.providers.PricingModel(route.Provider, route.UpstreamModel)
var reservation audit.PricingResult
var priced bool
switch operation {
case audit.OperationImage:
reservation, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, requestedCount)
case audit.OperationImageEdit:
reservation, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, requestedCount, inputImageCount)
}
reserved := false
if priced {
reserved, err = s.clientKeys.ReserveBilling(ctx, key, eventID, reservation.CostInUSDTicks, mediaBillingReservationTTL)
if err != nil {
return nil, err
}
}
finalizationOwnsReservation := false
defer func() {
if reserved && !finalizationOwnsReservation {
s.cancelBillingReservation(eventID)
}
}()
quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel)
attempts := int(s.maxAttempts.Load())
if attempts <= 0 {
attempts = 3
}
excluded := make(map[uint64]bool)
var lease *accountLease
var credential accountdomain.Credential
var response *provider.Response
var lastCredentialFailure *accountdomain.Credential
var lastCredentialError error
for attempt := 0; attempt < attempts; attempt++ {
lease, err = s.selector.Acquire(ctx, route.Provider, route.UpstreamModel, quotaMode, "", excluded, false)
if err != nil {
writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", lastCredentialFailure)
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err)
}
excluded[lease.Credential.ID] = true
credential, err = s.accounts.EnsureCredential(ctx, lease.Credential, false)
if err != nil {
s.logger.Error("image_credential_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", lease.Credential.ID, "error", err)
failedCredential := lease.Credential
lastCredentialFailure = &failedCredential
lastCredentialError = err
lease.Release()
continue
}
response, err = execute(ctx, route.Provider, credential, route.UpstreamModel)
if err != nil {
s.logger.Error("image_upstream_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", credential.ID, "error", err)
if !provider.IsMediaPostProcessingError(err) {
s.selector.MarkFailure(ctx, credential, 0, 0)
}
lease.Release()
errorCode := "upstream_unavailable"
if provider.IsMediaPostProcessingError(err) {
errorCode = "media_postprocessing_failed"
}
writeFailureAudit(http.StatusBadGateway, errorCode, &credential)
return nil, err
}
if s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden && attempt == 0 && attempt+1 < attempts {
_, _ = readRetryableBody(response.Body)
lease.Release()
delete(excluded, credential.ID)
continue
}
if quotaKind, _ := s.providers.QuotaKind(credential.Provider); quotaKind == provider.QuotaRemoteWindow && response.StatusCode == http.StatusTooManyRequests && lease.QuotaMode != "" {
retryAfter := parseRetryAfter(response.Header.Get("Retry-After"), time.Now().UTC())
exhausted, reconcileErr := s.accounts.ReconcileWebRateLimit(ctx, credential.ID, lease.QuotaMode, retryAfter)
s.selector.MarkQuotaStateChanged(credential.Provider)
if reconcileErr != nil || !exhausted {
s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter)
}
if attempt+1 < attempts {
_, _ = readRetryableBody(response.Body)
lease.Release()
continue
}
}
break
}
if response == nil {
writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", lastCredentialFailure)
if lastCredentialError == nil {
lastCredentialError = ErrNoAvailableAccount
}
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, lastCredentialError)
}
if response.StatusCode == http.StatusUnauthorized && credential.AuthType == accountdomain.AuthTypeSSO {
_ = s.accounts.MarkReauthRequired(ctx, credential.ID, fmt.Sprintf("%s SSO credential rejected", credential.Provider))
s.selector.MarkFailure(ctx, credential, http.StatusUnauthorized, 0)
}
effectiveQuotaMode := lease.QuotaMode
accountID := credential.ID
var once sync.Once
finalize := func(_ Usage, _ string, errorCode string) {
once.Do(func() {
lease.Release()
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
defer cancel()
record := auditBase
record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode
record.ErrorCode = errorCode
record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC()
applyAuditEgress(&record, egressTrace, route.Provider)
if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" {
record.MediaOutputImages = int64(max(0, requestedCount))
var pricing audit.PricingResult
var priced bool
switch operation {
case audit.OperationImage:
pricing, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, requestedCount)
case audit.OperationImageEdit:
pricing, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, requestedCount, inputImageCount)
}
if priced {
record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks
record.PricingModel = pricing.Model
record.PricingVersion = audit.OfficialPricingAsOf
}
}
if err := s.audits.Create(persistCtx, record); err != nil {
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", err)
}
quotaKind, _ := s.providers.QuotaKind(route.Provider)
if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" && quotaKind == provider.QuotaRemoteWindow && effectiveQuotaMode != "" {
if effectiveQuotaMode != "weekly" {
units := max(1, response.QuotaUnits)
updated, err := s.accounts.DecrementWebQuota(persistCtx, accountID, effectiveQuotaMode, units)
if err != nil {
s.logger.Warn("web_quota_decrement_failed", "account_id", accountID, "mode", effectiveQuotaMode, "units", units, "error", err)
} else if updated {
s.selector.ConsumeQuota(route.Provider, accountID, effectiveQuotaMode, units)
}
}
s.accounts.QueueQuotaRefresh(accountID, effectiveQuotaMode)
}
})
}
finalizationOwnsReservation = true
return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, Finalize: finalize}, nil
}
@@ -5,7 +5,6 @@ import (
"crypto/sha256"
"encoding/hex"
"fmt"
"sort"
"strings"
"sync"
"time"
@@ -206,10 +205,11 @@ func (s *Selector) Acquire(ctx context.Context, provider account.Provider, upstr
return nil, &SelectionUnavailableError{Reason: reason, RetryAfter: retryDelay(now, earliestRetry)}
}
if len(probeCandidates) > 0 {
if err := s.sortCandidates(ctx, probeCandidates, now, s.resolveTierOrder(provider, upstreamModel)); err != nil {
plan, err := s.planCandidates(ctx, probeCandidates, now, s.resolveTierOrder(provider, upstreamModel))
if err != nil {
return nil, err
}
for _, candidate := range probeCandidates {
for candidate, ok := plan.Next(); ok; candidate, ok = plan.Next() {
lease, err := s.claimAccountSlot(ctx, candidate.Credential)
if err != nil {
return nil, err
@@ -256,10 +256,11 @@ func (s *Selector) Acquire(ctx context.Context, provider account.Provider, upstr
waitDeadline := time.Now().Add(capacityWait)
for {
currentTime := time.Now().UTC()
if err := s.sortCandidates(ctx, normalCandidates, currentTime, s.resolveTierOrder(provider, upstreamModel)); err != nil {
plan, err := s.planCandidates(ctx, normalCandidates, currentTime, s.resolveTierOrder(provider, upstreamModel))
if err != nil {
return nil, err
}
for _, candidate := range normalCandidates {
for candidate, ok := plan.Next(); ok; candidate, ok = plan.Next() {
lease, err := s.claimAccountSlot(ctx, candidate.Credential)
if err != nil {
return nil, err
@@ -550,7 +551,7 @@ func (s *Selector) claimAccountSlot(ctx context.Context, value account.Credentia
if limit <= 0 {
limit = account.DefaultMaxConcurrent
}
release, acquired, err := s.concurrency.Acquire(ctx, fmt.Sprintf("account:%d", value.ID), limit)
release, acquired, err := s.concurrency.Acquire(ctx, accountConcurrencyKey(value.ID), limit)
if err != nil {
return nil, fmt.Errorf("获取账号并发租约: %w", err)
}
@@ -641,81 +642,6 @@ func retryDelay(now, retryAt time.Time) time.Duration {
return retryAt.Sub(now)
}
func (s *Selector) sortCandidates(ctx context.Context, values []account.RoutingCandidate, now time.Time, tierOrder []account.WebTier) error {
s.mu.Lock()
lastSelected := make(map[uint64]time.Time, len(s.lastSelectedAt))
for id, value := range s.lastSelectedAt {
lastSelected[id] = value
}
s.mu.Unlock()
remaining := make(map[uint64]float64, len(values))
fresh := make(map[uint64]bool, len(values))
inFlight := make(map[uint64]int, len(values))
concurrencyKeys := make([]string, 0, len(values))
for _, candidate := range values {
concurrencyKeys = append(concurrencyKeys, fmt.Sprintf("account:%d", candidate.Credential.ID))
}
concurrencySnapshot := make(map[string]int, len(values))
batchReader, batched := s.concurrency.(repository.ConcurrencySnapshotReader)
if batched {
var err error
concurrencySnapshot, err = batchReader.CurrentMany(ctx, concurrencyKeys)
if err != nil {
return fmt.Errorf("批量读取账号并发租约: %w", err)
}
}
for _, candidate := range values {
value := candidate.Credential
key := fmt.Sprintf("account:%d", value.ID)
current, found := concurrencySnapshot[key]
if !batched {
var err error
current, err = s.concurrency.Current(ctx, key)
if err != nil {
return fmt.Errorf("读取账号并发租约: %w", err)
}
} else if !found {
current = 0
}
inFlight[value.ID] = current
if candidate.Billing != nil {
remaining[value.ID] = candidate.Billing.Remaining()
fresh[value.ID] = now.Sub(candidate.Billing.SyncedAt) <= 30*time.Minute
}
}
sort.SliceStable(values, func(i, j int) bool {
leftCandidate, rightCandidate := values[i], values[j]
left, right := leftCandidate.Credential, rightCandidate.Credential
if leftCandidate.SupportsModel != rightCandidate.SupportsModel {
return leftCandidate.SupportsModel
}
if leftCandidate.ModelCapabilityKnown != rightCandidate.ModelCapabilityKnown {
return leftCandidate.ModelCapabilityKnown
}
leftTier, rightTier := tierOrderRank(tierOrder, left.WebTier), tierOrderRank(tierOrder, right.WebTier)
if leftTier != rightTier {
return leftTier < rightTier
}
if left.Priority != right.Priority {
return left.Priority > right.Priority
}
if fresh[left.ID] != fresh[right.ID] {
return fresh[left.ID]
}
if inFlight[left.ID] != inFlight[right.ID] {
return inFlight[left.ID] < inFlight[right.ID]
}
if remaining[left.ID] != remaining[right.ID] {
return remaining[left.ID] > remaining[right.ID]
}
if !lastSelected[left.ID].Equal(lastSelected[right.ID]) {
return lastSelected[left.ID].Before(lastSelected[right.ID])
}
return left.ID < right.ID
})
return nil
}
func (s *Selector) resolveTierOrder(provider account.Provider, upstreamModel string) []account.WebTier {
if s.tierOrders == nil {
return nil
@@ -0,0 +1,138 @@
package gateway
import (
"container/heap"
"context"
"fmt"
"strconv"
"time"
"github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/repository"
)
type candidateScore struct {
index int
tier int
billingFresh bool
inFlight int
remaining float64
lastSelected time.Time
}
// candidatePlan 使用线性建堆保留完整路由优先级,并允许 claim 失败后按顺序取下一账号。
type candidatePlan struct {
values []account.RoutingCandidate
scores []candidateScore
}
func (p *candidatePlan) Len() int { return len(p.scores) }
func (p *candidatePlan) Less(left, right int) bool {
return candidateScoreBetter(p.values, p.scores[left], p.scores[right])
}
func (p *candidatePlan) Swap(left, right int) {
p.scores[left], p.scores[right] = p.scores[right], p.scores[left]
}
func (p *candidatePlan) Push(value any) {
p.scores = append(p.scores, value.(candidateScore))
}
func (p *candidatePlan) Pop() any {
last := len(p.scores) - 1
value := p.scores[last]
p.scores = p.scores[:last]
return value
}
func (p *candidatePlan) Next() (account.RoutingCandidate, bool) {
if p == nil || p.Len() == 0 {
return account.RoutingCandidate{}, false
}
score := heap.Pop(p).(candidateScore)
return p.values[score.index], true
}
func candidateScoreBetter(values []account.RoutingCandidate, leftScore, rightScore candidateScore) bool {
leftCandidate, rightCandidate := values[leftScore.index], values[rightScore.index]
left, right := leftCandidate.Credential, rightCandidate.Credential
if leftCandidate.SupportsModel != rightCandidate.SupportsModel {
return leftCandidate.SupportsModel
}
if leftCandidate.ModelCapabilityKnown != rightCandidate.ModelCapabilityKnown {
return leftCandidate.ModelCapabilityKnown
}
if leftScore.tier != rightScore.tier {
return leftScore.tier < rightScore.tier
}
if left.Priority != right.Priority {
return left.Priority > right.Priority
}
if leftScore.billingFresh != rightScore.billingFresh {
return leftScore.billingFresh
}
if leftScore.inFlight != rightScore.inFlight {
return leftScore.inFlight < rightScore.inFlight
}
if leftScore.remaining != rightScore.remaining {
return leftScore.remaining > rightScore.remaining
}
if !leftScore.lastSelected.Equal(rightScore.lastSelected) {
return leftScore.lastSelected.Before(rightScore.lastSelected)
}
return left.ID < right.ID
}
// planCandidates 批量读取动态并发状态,并以 O(n) 建堆生成保持原比较规则的候选计划。
func (s *Selector) planCandidates(ctx context.Context, values []account.RoutingCandidate, now time.Time, tierOrder []account.WebTier) (*candidatePlan, error) {
keys := make([]string, len(values))
for index, candidate := range values {
keys[index] = accountConcurrencyKey(candidate.Credential.ID)
}
var concurrencySnapshot map[string]int
batchReader, batched := s.concurrency.(repository.ConcurrencySnapshotReader)
if batched {
var err error
concurrencySnapshot, err = batchReader.CurrentMany(ctx, keys)
if err != nil {
return nil, fmt.Errorf("批量读取账号并发租约: %w", err)
}
}
inFlight := make([]int, len(values))
for index := range values {
if batched {
inFlight[index] = concurrencySnapshot[keys[index]]
continue
}
current, err := s.concurrency.Current(ctx, keys[index])
if err != nil {
return nil, fmt.Errorf("读取账号并发租约: %w", err)
}
inFlight[index] = current
}
s.mu.Lock()
scores := make([]candidateScore, len(values))
for index, candidate := range values {
score := candidateScore{
index: index, tier: tierOrderRank(tierOrder, candidate.Credential.WebTier),
inFlight: inFlight[index], lastSelected: s.lastSelectedAt[candidate.Credential.ID],
}
if candidate.Billing != nil {
score.remaining = candidate.Billing.Remaining()
score.billingFresh = now.Sub(candidate.Billing.SyncedAt) <= 30*time.Minute
}
scores[index] = score
}
s.mu.Unlock()
plan := &candidatePlan{values: values, scores: scores}
heap.Init(plan)
return plan, nil
}
func accountConcurrencyKey(accountID uint64) string {
return "account:" + strconv.FormatUint(accountID, 10)
}
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"path/filepath"
"slices"
"testing"
"time"
@@ -74,6 +75,42 @@ func TestSelectorPrioritizesDueQuotaProbeOnce(t *testing.T) {
}
}
func BenchmarkSelectorCandidatePlanning(b *testing.B) {
ctx := context.Background()
limiter := memory.NewConcurrencyLimiter()
selector := NewSelector(nil, limiter, nil, nil, time.Hour, time.Second, time.Minute)
now := time.Now().UTC()
candidates := make([]account.RoutingCandidate, 3000)
for index := range candidates {
id := uint64(index + 1)
billing := account.Billing{
AccountID: id, MonthlyLimit: 1_000_000, Used: float64(index % 1000), SyncedAt: now.Add(-time.Duration(index%60) * time.Minute),
}
candidates[index] = account.RoutingCandidate{
Credential: account.Credential{
ID: id, Provider: account.ProviderBuild, AuthStatus: account.AuthStatusActive,
Priority: index % 10, MaxConcurrent: account.DefaultMaxConcurrent,
},
Billing: &billing, ModelCapabilityKnown: true, SupportsModel: true,
}
}
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(parallel *testing.PB) {
for parallel.Next() {
values := append([]account.RoutingCandidate(nil), candidates...)
plan, err := selector.planCandidates(ctx, values, now, nil)
if err != nil {
b.Fatal(err)
}
if _, ok := plan.Next(); !ok {
b.Fatal("候选计划为空")
}
}
})
}
func TestSelectorSkipsQuotaProbeBeforeDue(t *testing.T) {
ctx := context.Background()
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "selector.db"))
@@ -348,14 +385,50 @@ func TestSelectorUsesBatchConcurrencySnapshot(t *testing.T) {
{Credential: account.Credential{ID: 1, Priority: 1}},
{Credential: account.Credential{ID: 2, Priority: 1}},
}
if err := selector.sortCandidates(context.Background(), values, time.Now().UTC(), nil); err != nil {
plan, err := selector.planCandidates(context.Background(), values, time.Now().UTC(), nil)
if err != nil {
t.Fatal(err)
}
if limiter.batchCalls != 1 || limiter.currentCalls != 0 || values[0].Credential.ID != 2 {
first, ok := plan.Next()
if limiter.batchCalls != 1 || limiter.currentCalls != 0 || !ok || first.Credential.ID != 2 {
t.Fatalf("batchCalls=%d currentCalls=%d values=%#v", limiter.batchCalls, limiter.currentCalls, values)
}
}
func TestCandidatePlanPreservesSelectorOrdering(t *testing.T) {
now := time.Now().UTC()
limiter := &batchConcurrencyLimiter{values: map[string]int{"account:2": 1}}
selector := &Selector{concurrency: limiter, lastSelectedAt: map[uint64]time.Time{6: now}}
newCandidate := func(id uint64, tier account.WebTier, priority int, known, supported bool) account.RoutingCandidate {
return account.RoutingCandidate{
Credential: account.Credential{ID: id, WebTier: tier, Priority: priority},
Billing: &account.Billing{
AccountID: id, MonthlyLimit: 100, SyncedAt: now,
},
ModelCapabilityKnown: known, SupportsModel: supported,
}
}
values := []account.RoutingCandidate{
newCandidate(5, account.WebTierHeavy, 100, false, false),
newCandidate(4, account.WebTierSuper, 100, true, true),
newCandidate(3, account.WebTierHeavy, 9, true, true),
newCandidate(2, account.WebTierHeavy, 10, true, true),
newCandidate(6, account.WebTierHeavy, 10, true, true),
newCandidate(1, account.WebTierHeavy, 10, true, true),
}
plan, err := selector.planCandidates(context.Background(), values, now, []account.WebTier{account.WebTierHeavy, account.WebTierSuper})
if err != nil {
t.Fatal(err)
}
ordered := make([]uint64, 0, len(values))
for candidate, ok := plan.Next(); ok; candidate, ok = plan.Next() {
ordered = append(ordered, candidate.Credential.ID)
}
if expected := []uint64{1, 6, 2, 3, 4, 5}; !slices.Equal(ordered, expected) {
t.Fatalf("候选顺序 = %v, want %v", ordered, expected)
}
}
func TestSelectorConsumesOnlyMatchingQuotaSnapshot(t *testing.T) {
key := candidateCacheKey{provider: account.ProviderWeb, upstreamModel: "chat", quotaMode: "fast"}
selector := &Selector{candidates: map[candidateCacheKey]candidateSnapshot{
@@ -698,236 +698,6 @@ type ResourceInput struct {
RawQuery string
}
type ImageGenerationInput struct {
RequestID string
ClientKey clientkey.Key
PublicModel string
Prompt string
Count int
Size string
AspectRatio string
Resolution string
ResponseFormat string
Streaming bool
}
type ImageEditInput struct {
RequestID string
ClientKey clientkey.Key
PublicModel string
Prompt string
ImageURLs []string
Count int
Resolution string
ResponseFormat string
}
func (s *Service) GenerateImage(ctx context.Context, input ImageGenerationInput) (*Result, error) {
return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImage, func(executionCtx context.Context, adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
return adapter.GenerateImage(executionCtx, provider.ImageGenerationRequest{
Credential: credential, Model: upstream, Prompt: input.Prompt, Count: input.Count,
Size: input.Size, AspectRatio: input.AspectRatio, Resolution: input.Resolution,
ResponseFormat: input.ResponseFormat, Streaming: input.Streaming,
})
}, input.Streaming, input.Resolution, input.Count, 0)
}
func (s *Service) EditImage(ctx context.Context, input ImageEditInput) (*Result, error) {
return s.executeImage(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationImageEdit, func(executionCtx context.Context, adapter provider.ImageAdapter, credential accountdomain.Credential, upstream string) (*provider.Response, error) {
return adapter.EditImage(executionCtx, provider.ImageEditRequest{
Credential: credential, Model: upstream, Prompt: input.Prompt,
ImageURLs: input.ImageURLs, Count: input.Count, Resolution: input.Resolution, ResponseFormat: input.ResponseFormat,
})
}, false, input.Resolution, input.Count, len(input.ImageURLs))
}
func (s *Service) executeImage(ctx context.Context, requestID string, key clientkey.Key, publicModel string, operation audit.Operation, execute func(context.Context, provider.ImageAdapter, accountdomain.Credential, string) (*provider.Response, error), streaming bool, resolution string, requestedCount, inputImageCount int) (*Result, error) {
ctx, egressTrace := infraegress.WithTrace(ctx)
startedAt := time.Now()
eventID := newAuditEventID()
routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel)
if err != nil {
return nil, ErrModelNotFound
}
capability := modeldomain.CapabilityImage
if operation == audit.OperationImageEdit {
capability = modeldomain.CapabilityImageEdit
}
route, err := s.selectMediaRoute(routes, key, capability, func(providerValue accountdomain.Provider) bool {
_, ok := s.providers.Images(providerValue)
return ok
})
if err != nil {
return nil, err
}
externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID)
adapter, ok := s.providers.Images(route.Provider)
if !ok {
return nil, ErrNoAvailableAccount
}
auditBase := audit.Record{
EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name,
ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel),
Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, Streaming: streaming,
}
if operation == audit.OperationImageEdit {
auditBase.MediaInputImages = int64(max(0, inputImageCount))
}
writeFailureAudit := func(statusCode int, errorCode string, credential *accountdomain.Credential) {
record := auditBase
record.StatusCode = statusCode
record.ErrorCode = errorCode
record.DurationMS = time.Since(startedAt).Milliseconds()
record.CreatedAt = time.Now().UTC()
if credential != nil {
accountID := credential.ID
record.AccountID = &accountID
record.AccountName = credential.Name
}
applyAuditEgress(&record, egressTrace, route.Provider)
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
defer cancel()
if auditErr := s.audits.Create(persistCtx, record); auditErr != nil {
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", auditErr)
}
}
pricingModel := s.providers.PricingModel(route.Provider, route.UpstreamModel)
var reservation audit.PricingResult
var priced bool
switch operation {
case audit.OperationImage:
reservation, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, requestedCount)
case audit.OperationImageEdit:
reservation, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, requestedCount, inputImageCount)
}
reserved := false
if priced {
reserved, err = s.clientKeys.ReserveBilling(ctx, key, eventID, reservation.CostInUSDTicks, mediaBillingReservationTTL)
if err != nil {
return nil, err
}
}
finalizationOwnsReservation := false
defer func() {
if reserved && !finalizationOwnsReservation {
s.cancelBillingReservation(eventID)
}
}()
quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel)
attempts := int(s.maxAttempts.Load())
if attempts <= 0 {
attempts = 3
}
excluded := make(map[uint64]bool)
var lease *accountLease
var credential accountdomain.Credential
var response *provider.Response
var lastCredentialFailure *accountdomain.Credential
for attempt := 0; attempt < attempts; attempt++ {
lease, err = s.selector.Acquire(ctx, route.Provider, route.UpstreamModel, quotaMode, "", excluded, false)
if err != nil {
writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", lastCredentialFailure)
return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err)
}
excluded[lease.Credential.ID] = true
credential, err = s.accounts.EnsureCredential(ctx, lease.Credential, false)
if err != nil {
s.logger.Error("image_credential_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", lease.Credential.ID, "error", err)
failedCredential := lease.Credential
lastCredentialFailure = &failedCredential
lease.Release()
continue
}
response, err = execute(ctx, adapter, credential, route.UpstreamModel)
if err != nil {
s.logger.Error("image_upstream_failed", "event_id", eventID, "request_id", requestID, "model", externalModel, "provider", route.Provider, "account_id", credential.ID, "error", err)
if !provider.IsMediaPostProcessingError(err) {
s.selector.MarkFailure(ctx, credential, 0, 0)
}
lease.Release()
errorCode := "upstream_unavailable"
if provider.IsMediaPostProcessingError(err) {
errorCode = "media_postprocessing_failed"
}
writeFailureAudit(http.StatusBadGateway, errorCode, &credential)
return nil, err
}
if s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden && attempt == 0 && attempt+1 < attempts {
_, _ = readRetryableBody(response.Body)
lease.Release()
delete(excluded, credential.ID)
continue
}
if quotaKind, _ := s.providers.QuotaKind(credential.Provider); quotaKind == provider.QuotaRemoteWindow && response.StatusCode == http.StatusTooManyRequests && lease.QuotaMode != "" {
retryAfter := parseRetryAfter(response.Header.Get("Retry-After"), time.Now().UTC())
exhausted, reconcileErr := s.accounts.ReconcileWebRateLimit(ctx, credential.ID, lease.QuotaMode, retryAfter)
s.selector.MarkQuotaStateChanged(credential.Provider)
if reconcileErr != nil || !exhausted {
s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter)
}
if attempt+1 < attempts {
_, _ = readRetryableBody(response.Body)
lease.Release()
continue
}
}
break
}
if response.StatusCode == http.StatusUnauthorized && credential.AuthType == accountdomain.AuthTypeSSO {
_ = s.accounts.MarkReauthRequired(ctx, credential.ID, fmt.Sprintf("%s SSO credential rejected", credential.Provider))
s.selector.MarkFailure(ctx, credential, http.StatusUnauthorized, 0)
}
effectiveQuotaMode := lease.QuotaMode
accountID := credential.ID
var once sync.Once
finalize := func(_ Usage, _ string, errorCode string) {
once.Do(func() {
lease.Release()
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
defer cancel()
record := auditBase
record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode
record.ErrorCode = errorCode
record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC()
applyAuditEgress(&record, egressTrace, route.Provider)
if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" {
record.MediaOutputImages = int64(max(0, requestedCount))
var pricing audit.PricingResult
var priced bool
switch operation {
case audit.OperationImage:
pricing, priced = audit.EstimateOfficialImageCost(pricingModel, resolution, requestedCount)
case audit.OperationImageEdit:
pricing, priced = audit.EstimateOfficialImageEditCost(pricingModel, resolution, requestedCount, inputImageCount)
}
if priced {
record.EstimatedCostInUSDTicks = pricing.CostInUSDTicks
record.PricingModel = pricing.Model
record.PricingVersion = audit.OfficialPricingAsOf
}
}
if err := s.audits.Create(persistCtx, record); err != nil {
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", err)
}
quotaKind, _ := s.providers.QuotaKind(route.Provider)
if response.StatusCode >= 200 && response.StatusCode < 300 && errorCode == "" && quotaKind == provider.QuotaRemoteWindow && effectiveQuotaMode != "" {
if effectiveQuotaMode != "weekly" {
units := max(1, response.QuotaUnits)
updated, err := s.accounts.DecrementWebQuota(persistCtx, accountID, effectiveQuotaMode, units)
if err != nil {
s.logger.Warn("web_quota_decrement_failed", "account_id", accountID, "mode", effectiveQuotaMode, "units", units, "error", err)
} else if updated {
s.selector.ConsumeQuota(route.Provider, accountID, effectiveQuotaMode, units)
}
}
s.accounts.QueueQuotaRefresh(accountID, effectiveQuotaMode)
}
})
}
finalizationOwnsReservation = true
return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, Finalize: finalize}, nil
}
func (s *Service) cancelBillingReservation(eventID string) {
ctx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
defer cancel()
@@ -186,7 +186,7 @@ func TestSelectMediaRouteSkipsSameNamedConversationRoute(t *testing.T) {
{ID: 20, PublicID: "Web/grok-shared", Provider: account.ProviderWeb, UpstreamModel: "grok-shared", Capability: modeldomain.CapabilityImage},
}
selected, err := service.selectMediaRoute(routes, clientkey.Key{}, modeldomain.CapabilityImage, func(providerValue account.Provider) bool {
_, ok := registry.Images(providerValue)
_, ok := registry.ImageGeneration(providerValue)
return ok
})
if err != nil || selected.ID != 20 {
@@ -194,6 +194,57 @@ func TestSelectMediaRouteSkipsSameNamedConversationRoute(t *testing.T) {
}
}
func TestGenerateImageReturnsWhenEveryCredentialRefreshFails(t *testing.T) {
ctx := context.Background()
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "image-credential-failure.db"))
if err != nil {
t.Fatal(err)
}
defer database.Close()
if err := database.InitializeSchema(ctx); err != nil {
t.Fatal(err)
}
accountRepo := relational.NewAccountRepository(database)
modelRepo := relational.NewModelRepository(database)
auditRepo := relational.NewAuditRepository(database)
responseRepo := relational.NewResponseRepository(database)
now := time.Now().UTC()
credential, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth,
Name: "expired-image", SourceKey: "expired-image", EncryptedAccessToken: "expired", EncryptedRefreshToken: "refresh",
ExpiresAt: now.Add(-time.Minute), Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1,
})
if err != nil {
t.Fatal(err)
}
if err := modelRepo.UpsertRoutes(ctx, []modeldomain.Route{{
PublicID: "image-credential-failure", Provider: account.ProviderBuild, UpstreamModel: "image-credential-failure",
Capability: modeldomain.CapabilityImage, Enabled: true,
}}); err != nil {
t.Fatal(err)
}
if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"image-credential-failure"}, now); err != nil {
t.Fatal(err)
}
adapter := &credentialFailureImageAdapter{}
registry := provider.NewRegistry(adapter)
sticky := memory.NewStickyStore()
accountService := accountapp.NewService(accountRepo, auditRepo, memory.NewDeviceSessionStore(), sticky, registry, testCipher(t), nil)
selector := NewSelector(accountRepo, memory.NewConcurrencyLimiter(), sticky, registry, time.Hour, time.Second, time.Minute)
service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), registry, selector, responseRepo, 1)
_, err = service.GenerateImage(ctx, ImageGenerationInput{
RequestID: "req-image-credential-failure", ClientKey: clientkey.Key{ID: 1, Name: "image-key"},
PublicModel: "image-credential-failure", Prompt: "test", Count: 1, ResponseFormat: "url",
})
if !errors.Is(err, ErrNoAvailableAccount) {
t.Fatalf("error = %v", err)
}
if adapter.generationCalls.Load() != 0 {
t.Fatalf("generation calls = %d", adapter.generationCalls.Load())
}
}
func TestGatewayDoesNotPersistStatelessConsoleResponses(t *testing.T) {
ctx := context.Background()
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "console-stateless.db"))
@@ -904,6 +955,29 @@ type webChatQuotaAdapter struct {
synced chan string
}
type credentialFailureImageAdapter struct {
generationCalls atomic.Int64
}
func (a *credentialFailureImageAdapter) Provider() account.Provider { return account.ProviderBuild }
func (a *credentialFailureImageAdapter) Definition() provider.Definition {
return provider.Definition{
Provider: account.ProviderBuild, ModelNamespace: account.ProviderBuild.ModelNamespace(),
Credential: provider.CredentialSurface{AuthType: account.AuthTypeOAuth, Refresh: true},
Media: provider.MediaSurface{ImageGeneration: true},
}
}
func (a *credentialFailureImageAdapter) RefreshCredential(context.Context, account.Credential) (provider.RefreshedCredential, error) {
return provider.RefreshedCredential{}, errors.New("simulated credential refresh failure")
}
func (a *credentialFailureImageAdapter) GenerateImage(context.Context, provider.ImageGenerationRequest) (*provider.Response, error) {
a.generationCalls.Add(1)
return nil, errors.New("unexpected image generation")
}
func (webRateLimitAdapter) Provider() account.Provider { return account.ProviderWeb }
func (webRateLimitAdapter) Definition() provider.Definition {
return testConversationDefinition(account.ProviderWeb)
+32 -3
View File
@@ -282,10 +282,39 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model
s.deferVideoJob(parent, job)
return
}
if errors.Is(err, provider.ErrUnauthorized) && lease.Credential.AuthType == account.AuthTypeSSO {
_ = s.accounts.MarkReauthRequired(context.Background(), lease.Credential.ID, fmt.Sprintf("%s SSO credential rejected", lease.Credential.Provider))
failureCtx, failureCancel := context.WithTimeout(context.Background(), finalizationTimeout)
failureHandled := false
if errors.Is(err, provider.ErrUnauthorized) {
if lease.Credential.AuthType == account.AuthTypeSSO {
_ = s.accounts.MarkReauthRequired(failureCtx, lease.Credential.ID, fmt.Sprintf("%s SSO credential rejected", lease.Credential.Provider))
}
s.selector.MarkFailure(failureCtx, lease.Credential, http.StatusUnauthorized, 0)
failureHandled = true
} else if status, ok := provider.ErrorHTTPStatus(err); ok {
switch {
case status == http.StatusForbidden && s.providers.RetryForbiddenAsEgress(lease.Credential.Provider):
// Web Provider 已对 anti-bot 403 降低出口健康并重建浏览器会话;
// 视频请求已提交,不能换号重试,也不能误伤账号池。
failureHandled = true
case (status == http.StatusPaymentRequired || status == http.StatusTooManyRequests) && lease.QuotaMode != "":
exhausted, reconcileErr := s.accounts.ReconcileRateLimit(failureCtx, lease.Credential.ID, lease.QuotaMode, 0)
s.selector.MarkQuotaStateChanged(lease.Credential.Provider)
if reconcileErr != nil || !exhausted {
s.selector.MarkFailure(failureCtx, lease.Credential, status, 0)
}
failureHandled = true
case status >= http.StatusInternalServerError:
// 5xx 是 Provider 服务级故障,不应让某个账号退出号池。
failureHandled = true
default:
s.selector.MarkFailure(failureCtx, lease.Credential, status, 0)
failureHandled = true
}
}
s.selector.MarkFailure(context.Background(), lease.Credential, 0, 0)
if !failureHandled && !provider.IsMediaPostProcessingError(err) {
s.selector.MarkFailure(failureCtx, lease.Credential, 0, 0)
}
failureCancel()
applyMediaJobEgress(&job, egressTrace, route.Provider)
s.failVideoJob(parent, job, "generation_failed", err)
return
@@ -320,7 +320,7 @@ func (s *Service) syncAllAccounts(ctx context.Context) (int, error) {
return s.syncAccountCapabilities(workCtx, value, adapter)
})
pool := s.bulkPool.Snapshot()
s.logger.Info("model_bulk_sync_completed", "total", summary.Total, "submitted", summary.Submitted, "succeeded", summary.Succeeded, "failed", summary.Failed, "panicked", summary.Panicked, "duration_ms", summary.Duration.Milliseconds(), "canceled", summary.Canceled, "pool_limit", pool.Limit, "pool_active", pool.Active, "pool_peak", pool.Peak, "error", runErr)
s.logger.Info("model_bulk_sync_completed", "total", summary.Total, "submitted", summary.Submitted, "succeeded", summary.Succeeded, "failed", summary.Failed, "panicked", summary.Panicked, "duration_ms", summary.Duration.Milliseconds(), "canceled", summary.Canceled, "pool_limit", pool.Limit, "pool_active", pool.Active, "pool_queued", pool.Queued, "pool_peak", pool.Peak, "error", runErr)
if runErr != nil {
return 0, runErr
}
@@ -55,6 +55,11 @@ type ProviderConsoleConfig struct {
ChatTimeout string
}
// ServerConfig 是管理接口使用的推理入口容量输入。
type ServerConfig struct {
MaxConcurrentRequests int
}
// BatchConfig 是管理接口使用的批量任务并发输入。
type BatchConfig struct {
ImportConcurrency int
@@ -100,6 +105,7 @@ type ClientKeyDefaultsConfig struct {
// EditableConfig 聚合管理端允许修改的运行参数。
type EditableConfig struct {
Server ServerConfig
ProviderBuild ProviderBuildConfig
ProviderWeb ProviderWebConfig
ProviderConsole ProviderConsoleConfig
@@ -245,6 +251,7 @@ func (s *Service) ReloadPersisted(ctx context.Context) error {
}
func applyDomainConfig(base config.Config, value settingsdomain.Config) config.Config {
base.Server.MaxConcurrentRequests = value.Server.MaxConcurrentRequests
capacityWait := value.Routing.CapacityWait
if capacityWait <= 0 {
capacityWait = base.Routing.CapacityWait.Value()
@@ -262,11 +269,9 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C
MediaConcurrency: value.ProviderWeb.MediaConcurrency, AllowNSFW: value.ProviderWeb.AllowNSFW,
RecoveryBackoffBase: config.Duration(value.ProviderWeb.RecoveryBackoffBase), RecoveryBackoffMax: config.Duration(value.ProviderWeb.RecoveryBackoffMax),
}
if strings.TrimSpace(value.ProviderConsole.BaseURL) != "" {
base.Provider.Console = config.ConsoleProviderConfig{
BaseURL: value.ProviderConsole.BaseURL, UserAgent: value.ProviderConsole.UserAgent,
ChatTimeout: config.Duration(value.ProviderConsole.ChatTimeout),
}
base.Provider.Console = config.ConsoleProviderConfig{
BaseURL: value.ProviderConsole.BaseURL, UserAgent: value.ProviderConsole.UserAgent,
ChatTimeout: config.Duration(value.ProviderConsole.ChatTimeout),
}
randomDelay := time.Duration(-1)
if value.Batch.RandomDelay != nil {
@@ -298,6 +303,7 @@ func applyDomainConfig(base config.Config, value settingsdomain.Config) config.C
func toDomainConfig(value config.Config) settingsdomain.Config {
randomDelay := value.Batch.RandomDelay.Value()
return settingsdomain.Config{
Server: settingsdomain.ServerConfig{MaxConcurrentRequests: value.Server.MaxConcurrentRequests},
ProviderBuild: settingsdomain.ProviderBuildConfig{
BaseURL: value.Provider.Build.BaseURL, ClientVersion: value.Provider.Build.ClientVersion,
ClientIdentifier: value.Provider.Build.ClientIdentifier, TokenAuth: value.Provider.Build.TokenAuth,
@@ -361,6 +367,7 @@ func (s *Service) snapshotLocked() Snapshot {
func mergeEditable(current config.Config, input EditableConfig) (config.Config, error) {
next := current
next.Server.MaxConcurrentRequests = input.Server.MaxConcurrentRequests
next.Provider.Build.BaseURL = strings.TrimSpace(input.ProviderBuild.BaseURL)
next.Provider.Build.ClientVersion = strings.TrimSpace(input.ProviderBuild.ClientVersion)
next.Provider.Build.ClientIdentifier = strings.TrimSpace(input.ProviderBuild.ClientIdentifier)
@@ -431,6 +438,7 @@ func mergeEditable(current config.Config, input EditableConfig) (config.Config,
func toEditable(cfg config.Config) EditableConfig {
return EditableConfig{
Server: ServerConfig{MaxConcurrentRequests: cfg.Server.MaxConcurrentRequests},
ProviderBuild: ProviderBuildConfig{
BaseURL: cfg.Provider.Build.BaseURL, ClientVersion: cfg.Provider.Build.ClientVersion,
ClientIdentifier: cfg.Provider.Build.ClientIdentifier, TokenAuth: cfg.Provider.Build.TokenAuth,
@@ -44,12 +44,13 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) {
var applied config.Config
service := NewService(cfg, time.Time{}, 0, repository, nil, func(next config.Config) { applied = next })
input := service.Get().Config
input.Server.MaxConcurrentRequests = 2048
input.Routing.MaxAttempts = 5
input.Audit.BufferSize = cfg.Audit.BufferSize + 1
input.Media.MaxTotalBytes = 2 << 30
input.Media.CleanupThresholdPercent = 75
input.Media.CleanupInterval = "5m"
input.Frontend.PublicAPIBaseURL = "http://public.example.com"
input.Frontend.PublicAPIBaseURL = "https://public.example.com"
input.ProviderConsole.BaseURL = "https://console.example.com"
input.ProviderConsole.UserAgent = "console-test-agent"
input.ProviderConsole.ChatTimeout = "6m"
@@ -62,10 +63,13 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) {
if applied.Routing.MaxAttempts != 5 {
t.Fatalf("runtime configuration was not applied: %#v", applied.Routing)
}
if applied.Server.MaxConcurrentRequests != 2048 {
t.Fatalf("server configuration was not applied: %#v", applied.Server)
}
if applied.Media.MaxTotalBytes != 2<<30 || applied.Media.CleanupThresholdPercent != 75 || applied.Media.CleanupInterval.Value() != 5*time.Minute {
t.Fatalf("media configuration was not applied: %#v", applied.Media)
}
if applied.Frontend.PublicAPIBaseURLOverride != "http://public.example.com" || applied.Frontend.EffectivePublicAPIBaseURL() != "http://public.example.com" {
if applied.Frontend.PublicAPIBaseURLOverride != "https://public.example.com" || applied.Frontend.EffectivePublicAPIBaseURL() != "https://public.example.com" {
t.Fatalf("frontend configuration was not applied: %#v", applied.Frontend)
}
if applied.Batch.ImportConcurrency != 26 || applied.Batch.ConversionConcurrency != 27 || applied.Batch.SyncConcurrency != 28 || applied.Batch.RefreshConcurrency != 29 || applied.Batch.RandomDelay.Value() != 750*time.Millisecond {
@@ -81,25 +85,11 @@ func TestUpdatePersistsAppliesAndReportsRestart(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if reloaded.Routing.MaxAttempts != 5 || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" {
if reloaded.Server.MaxConcurrentRequests != 2048 || reloaded.Routing.MaxAttempts != 5 || reloaded.Audit.BufferSize != input.Audit.BufferSize || reloaded.Media.MaxTotalBytes != 2<<30 || reloaded.Media.CleanupThresholdPercent != 75 || reloaded.Batch.SyncConcurrency != 28 || reloaded.Batch.RandomDelay.Value() != 750*time.Millisecond || reloaded.Provider.Console.BaseURL != "https://console.example.com" {
t.Fatalf("configuration was not persisted")
}
}
func TestLoadPersistedKeepsConsoleDefaultsWhenFieldIsMissing(t *testing.T) {
cfg := testConfig(t)
value := toDomainConfig(cfg)
value.ProviderConsole = settingsdomain.ProviderConsoleConfig{}
repository := &runtimeSettingsRepositoryStub{value: value, found: true}
loaded, _, _, err := LoadPersisted(context.Background(), cfg, repository)
if err != nil {
t.Fatal(err)
}
if loaded.Provider.Console != cfg.Provider.Console {
t.Fatalf("console config = %#v, want %#v", loaded.Provider.Console, cfg.Provider.Console)
}
}
func TestSnapshotIncludesRecommendedBuildBaseline(t *testing.T) {
service := NewService(testConfig(t), time.Time{}, 0, &runtimeSettingsRepositoryStub{}, nil, nil)
recommended := service.Get().RecommendedProviderBuild
@@ -4,6 +4,7 @@ import "time"
// Config 表示可跨重启持久化并支持热加载的网关运行参数。
type Config struct {
Server ServerConfig
ProviderBuild ProviderBuildConfig
ProviderWeb ProviderWebConfig
ProviderConsole ProviderConsoleConfig
@@ -15,6 +16,11 @@ type Config struct {
ClientKeyDefaults ClientKeyDefaultsConfig
}
// ServerConfig 定义可热更新的推理入口容量参数。
type ServerConfig struct {
MaxConcurrentRequests int
}
// FrontendConfig 定义公开 API 地址的运行时覆盖值;留空时使用配置文件值。
type FrontendConfig struct {
PublicAPIBaseURL string
+14 -12
View File
@@ -53,11 +53,12 @@ type Config struct {
}
type ServerConfig struct {
Listen string `yaml:"listen"`
MaxBodyBytes int64 `yaml:"maxBodyBytes"`
ReadTimeout Duration `yaml:"readTimeout"`
RequestTimeout Duration `yaml:"requestTimeout"`
SwaggerEnabled bool `yaml:"swaggerEnabled"`
Listen string `yaml:"listen"`
MaxBodyBytes int64 `yaml:"maxBodyBytes"`
MaxConcurrentRequests int `yaml:"maxConcurrentRequests"`
ReadTimeout Duration `yaml:"readTimeout"`
RequestTimeout Duration `yaml:"requestTimeout"`
SwaggerEnabled bool `yaml:"swaggerEnabled"`
}
type FrontendConfig struct {
@@ -300,6 +301,9 @@ func (c Config) Validate() error {
if c.Server.RequestTimeout.Value() <= 0 || c.Server.RequestTimeout.Value() > maxRequestTimeout {
return errors.New("server.requestTimeout 必须大于零且不超过 24 小时")
}
if c.Server.MaxConcurrentRequests < 1 || c.Server.MaxConcurrentRequests > 100000 {
return errors.New("server.maxConcurrentRequests 必须在 1 到 100000 之间")
}
for _, item := range []struct {
name string
value string
@@ -312,9 +316,6 @@ func (c Config) Validate() error {
if err != nil || (publicAPIURL.Scheme != "http" && publicAPIURL.Scheme != "https") || publicAPIURL.Host == "" || publicAPIURL.User != nil || publicAPIURL.RawQuery != "" || publicAPIURL.Fragment != "" {
return fmt.Errorf("%s 必须是不含凭据、查询参数和片段的 HTTP(S) URL", item.name)
}
if publicAPIURL.Scheme == "https" && !c.Auth.SecureCookies {
return errors.New("HTTPS 公共地址必须启用 auth.secureCookies")
}
}
}
switch c.Database.Driver {
@@ -449,10 +450,11 @@ func (c Config) Validate() error {
func defaultConfig() Config {
return Config{
Server: ServerConfig{
Listen: "127.0.0.1:8000",
MaxBodyBytes: 32 << 20,
ReadTimeout: Duration(15 * time.Minute),
RequestTimeout: Duration(2 * time.Hour),
Listen: "127.0.0.1:8000",
MaxBodyBytes: 32 << 20,
MaxConcurrentRequests: 1024,
ReadTimeout: Duration(15 * time.Minute),
RequestTimeout: Duration(2 * time.Hour),
},
Frontend: FrontendConfig{PublicAPIBaseURL: DefaultPublicAPIBaseURL, StaticPath: "./frontend/dist"},
Database: DatabaseConfig{
+2 -13
View File
@@ -171,7 +171,7 @@ func TestValidateRejectsUnsafeRuntimeLimits(t *testing.T) {
}
}
func TestValidateRejectsExampleSecretsAndUnsafeCookies(t *testing.T) {
func TestValidateRejectsExampleSecrets(t *testing.T) {
base := defaultConfig()
base.Secrets.JWTSecret = "12345678901234567890123456789012"
base.Secrets.CredentialEncryptionKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="
@@ -180,10 +180,6 @@ func TestValidateRejectsExampleSecretsAndUnsafeCookies(t *testing.T) {
"example jwt": func(cfg *Config) { cfg.Secrets.JWTSecret = "replace-with-at-least-32-characters" },
"invalid encryption key": func(cfg *Config) { cfg.Secrets.CredentialEncryptionKey = "not-a-32-byte-base64-key" },
"example admin password": func(cfg *Config) { cfg.BootstrapAdmin.Password = "replace-with-a-strong-password" },
"https insecure cookie": func(cfg *Config) {
cfg.Frontend.PublicAPIBaseURL = "https://api.example.com"
cfg.Auth.SecureCookies = false
},
}
for name, mutate := range tests {
t.Run(name, func(t *testing.T) {
@@ -194,13 +190,6 @@ func TestValidateRejectsExampleSecretsAndUnsafeCookies(t *testing.T) {
}
})
}
secure := base
secure.Frontend.PublicAPIBaseURL = "https://api.example.com"
secure.Auth.SecureCookies = true
if err := secure.Validate(); err != nil {
t.Fatalf("secure HTTPS configuration rejected: %v", err)
}
}
func TestValidateStatsigModes(t *testing.T) {
@@ -268,7 +257,7 @@ func TestValidateFrontendPublicAPIBaseURL(t *testing.T) {
}
}
cfg.Frontend.PublicAPIBaseURL = "https://api.example.com/grok2api"
cfg.Auth.SecureCookies = true
cfg.Auth.SecureCookies = false
if err := cfg.Validate(); err != nil {
t.Fatalf("valid frontend.publicApiBaseURL rejected: %v", err)
}
+52 -13
View File
@@ -56,16 +56,21 @@ type Manager struct {
repository repository.EgressRepository
cipher *security.Cipher
mu sync.Mutex
clients map[uint64]cachedClient
clients map[clientCacheKey]cachedClient
inflight map[uint64]int
nodes map[domain.Scope]cachedNodeSnapshot
nodeLoads singleflight.Group
}
type cachedClient struct {
client requestClient
browser *browserClient
}
type clientCacheKey struct {
nodeID uint64
scope domain.Scope
fingerprint string
client requestClient
browser *browserClient
}
type cachedNodeSnapshot struct {
@@ -74,7 +79,7 @@ type cachedNodeSnapshot struct {
}
func NewManager(repository repository.EgressRepository, cipher *security.Cipher) *Manager {
return &Manager{repository: repository, cipher: cipher, clients: make(map[uint64]cachedClient), inflight: make(map[uint64]int), nodes: make(map[domain.Scope]cachedNodeSnapshot)}
return &Manager{repository: repository, cipher: cipher, clients: make(map[clientCacheKey]cachedClient), inflight: make(map[uint64]int), nodes: make(map[domain.Scope]cachedNodeSnapshot)}
}
func (m *Manager) Acquire(ctx context.Context, scope domain.Scope, affinity string) (*Lease, error) {
@@ -239,13 +244,17 @@ func (m *Manager) clientFor(id uint64, scope domain.Scope, proxyURL, userAgent,
clientKind = "build"
}
fingerprint := fmt.Sprintf("%x", sha256.Sum256([]byte(clientKind+"\x00"+proxyURL+"\x00"+userAgent+"\x00"+cookies)))
cacheScope := scope
if cacheScope == domain.ScopeWebAsset {
cacheScope = domain.ScopeWeb
}
key := clientCacheKey{nodeID: id, scope: cacheScope, fingerprint: fingerprint}
m.mu.Lock()
defer m.mu.Unlock()
if cached, ok := m.clients[id]; ok && cached.fingerprint == fingerprint {
if cached, ok := m.clients[key]; ok {
return cached, nil
}
var value cachedClient
value.fingerprint = fingerprint
if scope == domain.ScopeBuild {
client, err := newBuildClient(proxyURL)
if err != nil {
@@ -260,10 +269,20 @@ func (m *Manager) clientFor(id uint64, scope domain.Scope, proxyURL, userAgent,
value.client = client
value.browser = client
}
if previous, exists := m.clients[id]; exists && previous.client != nil {
previous.client.CloseIdleConnections()
// 持久化节点只属于一个 Scope;同节点出现新指纹说明配置已更新,旧连接池应淘汰。
// 直连节点统一使用 ID 0,不同 Provider 的传输必须并存,避免 Build 与 Web 互相重建客户端。
if id != 0 {
for previousKey, previous := range m.clients {
if previousKey.nodeID != id {
continue
}
if previous.client != nil {
previous.client.CloseIdleConnections()
}
delete(m.clients, previousKey)
}
}
m.clients[id] = value
m.clients[key] = value
return value, nil
}
@@ -275,7 +294,7 @@ func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, node
if nodeID == 0 {
if transportErr != nil || status >= 500 || (scope != domain.ScopeBuild && status == http.StatusForbidden) {
m.mu.Lock()
m.invalidateClientLocked(0)
m.invalidateClientForScopeLocked(0, scope)
m.mu.Unlock()
}
return
@@ -326,10 +345,30 @@ func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, node
}
func (m *Manager) invalidateClientLocked(nodeID uint64) {
if cached, exists := m.clients[nodeID]; exists && cached.client != nil {
cached.client.CloseIdleConnections()
for key, cached := range m.clients {
if key.nodeID != nodeID {
continue
}
if cached.client != nil {
cached.client.CloseIdleConnections()
}
delete(m.clients, key)
}
}
func (m *Manager) invalidateClientForScopeLocked(nodeID uint64, scope domain.Scope) {
if scope == domain.ScopeWebAsset {
scope = domain.ScopeWeb
}
for key, cached := range m.clients {
if key.nodeID != nodeID || key.scope != scope {
continue
}
if cached.client != nil {
cached.client.CloseIdleConnections()
}
delete(m.clients, key)
}
delete(m.clients, nodeID)
}
func BuildSSOCookie(token, cloudflareCookies string) string {
+54 -4
View File
@@ -15,13 +15,52 @@ import (
)
func TestDirectFallbackRebuildsClientAfterAntiBotRejection(t *testing.T) {
manager := &Manager{clients: map[uint64]cachedClient{0: {}}}
manager := &Manager{clients: map[clientCacheKey]cachedClient{{nodeID: 0, scope: domain.ScopeWeb, fingerprint: "web"}: {}}}
manager.Feedback(context.Background(), 0, http.StatusForbidden, nil)
if _, exists := manager.clients[0]; exists {
if len(manager.clients) != 0 {
t.Fatal("direct fallback client was not invalidated after anti-bot rejection")
}
}
func TestDirectBuildAndWebClientsDoNotEvictEachOther(t *testing.T) {
cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=")
if err != nil {
t.Fatal(err)
}
manager := NewManager(egressRepositoryTestStub{}, cipher)
buildFirst, err := manager.Acquire(context.Background(), domain.ScopeBuild, "")
if err != nil {
t.Fatal(err)
}
defer buildFirst.Release()
web, err := manager.Acquire(context.Background(), domain.ScopeWeb, "")
if err != nil {
t.Fatal(err)
}
defer web.Release()
buildSecond, err := manager.Acquire(context.Background(), domain.ScopeBuild, "")
if err != nil {
t.Fatal(err)
}
defer buildSecond.Release()
if buildFirst.client != buildSecond.client {
t.Fatal("Web direct traffic evicted the reusable Build connection pool")
}
if buildFirst.client == web.client || len(manager.clients) != 2 {
t.Fatalf("direct clients were not isolated: build=%T web=%T cached=%d", buildFirst.client, web.client, len(manager.clients))
}
manager.FeedbackForScope(context.Background(), domain.ScopeWeb, 0, http.StatusForbidden, nil)
buildAfterWebFailure, err := manager.Acquire(context.Background(), domain.ScopeBuild, "")
if err != nil {
t.Fatal(err)
}
defer buildAfterWebFailure.Release()
if buildAfterWebFailure.client != buildFirst.client || len(manager.clients) != 1 {
t.Fatalf("Web failure evicted Build direct client: reused=%v cached=%d", buildAfterWebFailure.client == buildFirst.client, len(manager.clients))
}
}
func TestBrowserRequestLeavesHeaderOrderingToTLSProfile(t *testing.T) {
request, err := http.NewRequest(http.MethodPost, "https://grok.com/rest/app-chat/conversations/new", nil)
if err != nil {
@@ -158,7 +197,7 @@ func TestBuildForbiddenDoesNotPoisonEgressNode(t *testing.T) {
if repository.updates != 0 || repository.node.Health != 1 || repository.node.LastError != "" {
t.Fatalf("build 403 poisoned node: updates=%d node=%#v", repository.updates, repository.node)
}
if _, exists := manager.clients[1]; !exists {
if !managerHasClientForNode(manager, 1) {
t.Fatal("build client was invalidated by an ambiguous 403")
}
}
@@ -179,7 +218,7 @@ func TestWebForbiddenStillRebuildsBrowserSession(t *testing.T) {
if repository.updates != 1 || repository.node.Health >= 1 || repository.node.LastError != "anti-bot rejection" {
t.Fatalf("web 403 feedback = updates=%d node=%#v", repository.updates, repository.node)
}
if _, exists := manager.clients[1]; exists {
if managerHasClientForNode(manager, 1) {
t.Fatal("web browser session was not invalidated after 403")
}
}
@@ -227,6 +266,17 @@ func TestEgressNodeSnapshotAvoidsRepeatedRepositoryReads(t *testing.T) {
type egressRepositoryTestStub struct{ nodes []domain.Node }
func managerHasClientForNode(manager *Manager, nodeID uint64) bool {
manager.mu.Lock()
defer manager.mu.Unlock()
for key := range manager.clients {
if key.nodeID == nodeID {
return true
}
}
return false
}
type countingEgressRepository struct {
egressRepositoryTestStub
calls int
@@ -394,7 +394,7 @@ func (r *AccountRepository) UpsertManyByIdentity(ctx context.Context, values []a
if err := tx.Where("identity_key IN ?", identityKeys).Find(&existingRows).Error; err != nil {
return err
}
existingByIdentity := make(map[string]accountModel, len(existingRows)+len(values))
existingByIdentity := make(map[string]accountModel, len(values))
for _, row := range existingRows {
existingByIdentity[row.IdentityKey] = row
}
@@ -154,7 +154,7 @@ func (r *DashboardRepository) Snapshot(ctx context.Context, bucketBoundaries []t
func dashboardBucketExpression(boundaries []time.Time) (string, []any) {
var expression strings.Builder
expression.WriteString("CASE")
args := make([]any, 0, (len(boundaries)-1)*3)
args := make([]any, 0)
for index := 0; index < len(boundaries)-1; index++ {
expression.WriteString(" WHEN created_at >= ? AND created_at < ? THEN ?")
args = append(args, boundaries[index], boundaries[index+1], index)
@@ -151,7 +151,7 @@ func (r *ModelRepository) GetByPublicIDIncludingDisabled(ctx context.Context, pu
func findModelRoutesByPublicID(db *gorm.DB, publicID string) ([]modelRouteModel, error) {
candidates := model.PublicIDCandidates(publicID)
rows := make([]modelRouteModel, 0, len(candidates)+1)
rows := make([]modelRouteModel, 0, len(candidates))
if len(candidates) > 0 {
if err := db.Session(&gorm.Session{}).Where("model_routes.public_id IN ?", candidates).
Order(modelProviderPriorityExpression + ", model_routes.id ASC").Find(&rows).Error; err != nil {
@@ -164,8 +164,8 @@ func findModelRoutesByPublicID(db *gorm.DB, publicID string) ([]modelRouteModel,
Order(modelProviderPriorityExpression + ", model_routes.id ASC").Find(&aliases).Error; err != nil {
return nil, err
}
seen := make(map[uint64]bool, len(rows)+len(aliases))
result := make([]modelRouteModel, 0, len(rows)+len(aliases))
seen := make(map[uint64]bool)
result := make([]modelRouteModel, 0, len(rows))
for _, values := range [][]modelRouteModel{rows, aliases} {
for _, row := range values {
if seen[row.ID] {
@@ -32,6 +32,7 @@ func TestRuntimeSettingsRepositoryRoundTrip(t *testing.T) {
t.Fatalf("initial get found = %v, err = %v", found, err)
}
settings := settingsdomain.Config{
Server: settingsdomain.ServerConfig{MaxConcurrentRequests: 2048},
ProviderWeb: settingsdomain.ProviderWebConfig{StatsigManualValue: "sensitive-statsig-value"},
Media: settingsdomain.MediaConfig{
MaxImageBytes: 16 << 20, MaxTotalBytes: 1 << 30, CleanupThresholdPercent: 80,
@@ -47,7 +48,7 @@ func TestRuntimeSettingsRepositoryRoundTrip(t *testing.T) {
if err != nil || !found {
t.Fatalf("saved get found = %v, err = %v", found, err)
}
if value.Routing != settings.Routing || value.Media != settings.Media || !storedUpdatedAt.Equal(updatedAt) || revision != 1 || storedRevision != revision {
if value.Server != settings.Server || value.Routing != settings.Routing || value.Media != settings.Media || !storedUpdatedAt.Equal(updatedAt) || revision != 1 || storedRevision != revision {
t.Fatalf("saved value = %#v", value)
}
if value.ProviderWeb.StatsigManualValue != settings.ProviderWeb.StatsigManualValue {
@@ -0,0 +1,184 @@
package cli
import (
"encoding/json"
"fmt"
"strings"
)
// normalizeInputItems 将 Codex/Responses 扩展历史降级为 Grok Build 可接受的结构,
// 同时收集 tool_search 或 additional_tools 动态加载的工具定义。
func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, []any, []any, error) {
rewritten := make([]any, 0, len(items))
loadedTools := make([]any, 0)
visibleTools := make([]any, 0)
for index, rawItem := range items {
item, ok := rawItem.(map[string]any)
if !ok {
rewritten = append(rewritten, rawItem)
continue
}
param := fmt.Sprintf("input[%d]", index)
switch stringField(item, "type") {
case "function_call":
namespace := strings.TrimSpace(stringField(item, "namespace"))
if namespace == "" {
rewritten = append(rewritten, cloneJSONValue(item))
continue
}
name := strings.TrimSpace(stringField(item, "name"))
if name == "" {
return nil, nil, nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"}
}
converted := cloneJSONObject(item)
converted["name"] = c.alias(responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name})
delete(converted, "namespace")
c.changed = true
rewritten = append(rewritten, converted)
case "tool_search_call":
callID := strings.TrimSpace(stringField(item, "call_id"))
if callID == "" {
return nil, nil, nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"}
}
arguments, err := encodeFunctionArguments(item["arguments"])
if err != nil {
return nil, nil, nil, &responsesRequestError{Message: param + ".arguments 无法编码", Param: param + ".arguments", Code: "invalid_parameter"}
}
rewritten = append(rewritten, map[string]any{
"type": "function_call", "call_id": callID,
"name": c.alias(responsesToolIdentity{Kind: responsesToolSearch, Name: "tool_search"}), "arguments": arguments,
})
c.changed = true
case "tool_search_output":
execution := strings.ToLower(strings.TrimSpace(stringField(item, "execution")))
if execution != "client" {
return nil, nil, nil, &responsesRequestError{Message: "Grok Build 只兼容客户端 tool_search_output", Param: param + ".execution", Code: "unsupported_parameter"}
}
callID := strings.TrimSpace(stringField(item, "call_id"))
if callID == "" {
return nil, nil, nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"}
}
tools, ok := item["tools"].([]any)
if !ok {
return nil, nil, nil, &responsesRequestError{Message: param + ".tools 必须是数组", Param: param + ".tools", Code: "invalid_parameter"}
}
for toolIndex, rawTool := range tools {
converted, err := c.normalizeTool(rawTool, "", false, true, fmt.Sprintf("%s.tools[%d]", param, toolIndex))
if err != nil {
return nil, nil, nil, err
}
loadedTools = append(loadedTools, converted...)
}
visibleTools = append(visibleTools, cloneJSONArray(tools)...)
c.changed = true
rewritten = append(rewritten, map[string]any{
"type": "function_call_output", "call_id": callID,
"output": fmt.Sprintf("Tool search completed; %d selected tool definitions are now available.", len(tools)),
})
case "custom_tool_call":
name := strings.TrimSpace(stringField(item, "name"))
if name == "" {
return nil, nil, nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"}
}
input, ok := item["input"].(string)
if !ok {
return nil, nil, nil, &responsesRequestError{Message: param + ".input 必须是字符串", Param: param + ".input", Code: "invalid_parameter"}
}
arguments, err := encodeCustomToolArguments(input)
if err != nil {
return nil, nil, nil, err
}
namespace := strings.TrimSpace(stringField(item, "namespace"))
converted := cloneJSONObject(item)
converted["type"] = "function_call"
converted["name"] = c.alias(responsesToolIdentity{Kind: responsesCustomTool, Namespace: namespace, Name: name})
converted["arguments"] = arguments
delete(converted, "input")
delete(converted, "namespace")
c.changed = true
rewritten = append(rewritten, converted)
case "custom_tool_call_output":
converted := cloneJSONObject(item)
converted["type"] = "function_call_output"
delete(converted, "name")
delete(converted, "namespace")
c.changed = true
rewritten = append(rewritten, converted)
case "apply_patch_call":
converted, err := c.normalizeApplyPatchCallInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "apply_patch_call_output":
converted, err := normalizeApplyPatchOutputInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "agent_message":
if _, visible := textInputContent(item["content"]); !visible {
c.addWarning("opaque_agent_message_redacted")
}
converted, err := normalizeAgentMessageInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "local_shell_call":
converted, err := normalizeLegacyLocalShellCallInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "local_shell_call_output":
converted, err := normalizeLegacyLocalShellOutputInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "mcp_tool_call_output":
converted, err := normalizeMCPOutputInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "compaction_trigger":
c.changed = true
c.addWarning("compaction_boundary_preserved")
rewritten = append(rewritten, compatibilityBoundaryMessage("Codex context compaction boundary reached."))
case "additional_tools":
marker, additional, visible, err := c.normalizeAdditionalToolsInput(item, param)
if err != nil {
return nil, nil, nil, err
}
loadedTools = append(loadedTools, additional...)
visibleTools = append(visibleTools, visible...)
c.changed = true
rewritten = append(rewritten, marker)
default:
rewritten = append(rewritten, cloneJSONValue(item))
}
}
return rewritten, loadedTools, visibleTools, nil
}
func encodeFunctionArguments(value any) (string, error) {
if text, ok := value.(string); ok {
return text, nil
}
if value == nil {
return "{}", nil
}
encoded, err := json.Marshal(value)
if err != nil {
return "", err
}
return string(encoded), nil
}
@@ -0,0 +1,119 @@
package cli
import (
"encoding/json"
"fmt"
"strings"
)
func (c *responsesToolCompatibility) normalizeToolChoice(payload map[string]json.RawMessage, normalizedTools []any) error {
raw := payload["tool_choice"]
if isEmptyJSON(raw) {
return nil
}
var choice any
if err := json.Unmarshal(raw, &choice); err != nil {
return &responsesRequestError{Message: "tool_choice 格式无效", Param: "tool_choice", Code: "invalid_parameter"}
}
object, ok := choice.(map[string]any)
if !ok {
if value, isString := choice.(string); isString && (value == "auto" || value == "required") && c.webSearchDisabled && len(normalizedTools) == 0 {
payload["tool_choice"] = mustJSON("none")
c.changed = true
c.addWarning("web_search_tool_choice_disabled")
}
return nil
}
kind := stringField(object, "type")
if c.webSearchDisabled && normalizeHostedToolChoiceKind(kind) == "web_search" && !hasToolType(normalizedTools, "web_search") {
payload["tool_choice"] = mustJSON("none")
c.changed = true
c.addWarning("web_search_tool_choice_disabled")
return nil
}
if kind == "tool_search" {
if c.clientSearchTool == nil {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 tool_search", Param: "tool_choice", Code: "invalid_parameter"}
}
object = map[string]any{
"type": "function",
"name": c.alias(responsesToolIdentity{Kind: responsesToolSearch, Name: "tool_search"}),
}
c.changed = true
payload["tool_choice"] = mustJSON(object)
return nil
}
if kind == "custom" {
name := strings.TrimSpace(stringField(object, "name"))
namespace := strings.TrimSpace(stringField(object, "namespace"))
if name == "" {
return &responsesRequestError{Message: "tool_choice.name 不能为空", Param: "tool_choice.name", Code: "invalid_parameter"}
}
identity := responsesToolIdentity{Kind: responsesCustomTool, Namespace: namespace, Name: name}
alias, exists := c.identityAliases[identity.key()]
if !exists {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 custom 工具", Param: "tool_choice.name", Code: "invalid_parameter"}
}
object["type"] = "function"
object["name"] = alias
delete(object, "namespace")
c.changed = true
payload["tool_choice"] = mustJSON(object)
return nil
}
if kind == "apply_patch" {
identity := responsesToolIdentity{Kind: responsesApplyPatchTool, Name: "apply_patch"}
alias, exists := c.identityAliases[identity.key()]
if !exists {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 apply_patch 工具", Param: "tool_choice", Code: "invalid_parameter"}
}
payload["tool_choice"] = mustJSON(map[string]any{"type": "function", "name": alias})
c.changed = true
return nil
}
if normalizedKind := normalizeHostedToolChoiceKind(kind); normalizedKind != "" {
if !hasSingleToolType(normalizedTools, normalizedKind) {
return &responsesRequestError{
Message: "Grok Build 仅能在请求中只有一个匹配工具时兼容 hosted tool_choice",
Param: "tool_choice", Code: "unsupported_parameter",
}
}
payload["tool_choice"] = mustJSON("required")
c.changed = true
return nil
}
if kind != "function" {
return &responsesRequestError{Message: fmt.Sprintf("Grok Build 不支持 tool_choice.type=%q", kind), Param: "tool_choice.type", Code: "unsupported_parameter"}
}
name := strings.TrimSpace(stringField(object, "name"))
namespace := strings.TrimSpace(stringField(object, "namespace"))
if function, nested := object["function"].(map[string]any); nested {
name = strings.TrimSpace(stringField(function, "name"))
namespace = strings.TrimSpace(stringField(function, "namespace"))
if name != "" && namespace != "" {
identity := responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}
alias, exists := c.identityAliases[identity.key()]
if !exists {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 namespace 函数", Param: "tool_choice.function.name", Code: "invalid_parameter"}
}
function["name"] = alias
delete(function, "namespace")
c.changed = true
payload["tool_choice"] = mustJSON(object)
}
return nil
}
if name == "" || namespace == "" {
return nil
}
identity := responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}
alias, exists := c.identityAliases[identity.key()]
if !exists {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 namespace 函数", Param: "tool_choice.name", Code: "invalid_parameter"}
}
object["name"] = alias
delete(object, "namespace")
c.changed = true
payload["tool_choice"] = mustJSON(object)
return nil
}
@@ -0,0 +1,289 @@
package cli
import (
"encoding/json"
"fmt"
"strings"
)
func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesToolCompatibility, error) {
compatibility := newResponsesToolCompatibility()
tools, hasTools, err := decodeOptionalArray(payload["tools"], "tools")
if err != nil {
return nil, err
}
if hasTools {
compatibility.visibleTools = cloneJSONArray(tools)
}
clientSearch, err := inspectToolSearch(tools)
if err != nil {
return nil, err
}
if err := compatibility.normalizeClientToolSearchParallel(payload, clientSearch); err != nil {
return nil, err
}
normalizedTools := make([]any, 0, len(tools))
for index, rawTool := range tools {
converted, convertErr := compatibility.normalizeTool(rawTool, "", clientSearch, false, fmt.Sprintf("tools[%d]", index))
if convertErr != nil {
return nil, convertErr
}
normalizedTools = append(normalizedTools, converted...)
}
if rawInput := payload["input"]; !isEmptyJSON(rawInput) {
var input any
if err := json.Unmarshal(rawInput, &input); err != nil {
return nil, &responsesRequestError{Message: "input 必须是字符串或数组", Param: "input", Code: "invalid_parameter"}
}
if items, ok := input.([]any); ok {
rewritten, loadedTools, visibleTools, rewriteErr := compatibility.normalizeInputItems(items)
if rewriteErr != nil {
return nil, rewriteErr
}
normalizedTools = append(normalizedTools, loadedTools...)
compatibility.visibleTools = append(compatibility.visibleTools, visibleTools...)
payload["input"] = mustJSON(rewritten)
}
}
if compatibility.clientSearchTool != nil {
searchTool, searchErr := compatibility.buildClientSearchFunction()
if searchErr != nil {
return nil, searchErr
}
normalizedTools = append(normalizedTools, searchTool)
}
normalizedTools = dedupeNormalizedTools(normalizedTools)
if len(normalizedTools) > 0 {
payload["tools"] = mustJSON(normalizedTools)
} else if hasTools && compatibility.webSearchDisabled {
delete(payload, "tools")
compatibility.changed = true
}
if err := compatibility.normalizeToolChoice(payload, normalizedTools); err != nil {
return nil, err
}
if !compatibility.changed {
return nil, nil
}
return compatibility, nil
}
// normalizeClientToolSearchParallel 保证搜索函数先独立完成,再由客户端选择并回传工具定义。
func (c *responsesToolCompatibility) normalizeClientToolSearchParallel(payload map[string]json.RawMessage, clientSearch bool) error {
if !clientSearch {
return nil
}
raw, exists := payload["parallel_tool_calls"]
if !exists || isEmptyJSON(raw) {
payload["parallel_tool_calls"] = mustJSON(false)
c.changed = true
return nil
}
var parallel bool
if err := json.Unmarshal(raw, &parallel); err != nil {
return &responsesRequestError{
Message: "parallel_tool_calls 必须是布尔值",
Param: "parallel_tool_calls", Code: "invalid_parameter",
}
}
if parallel {
return &responsesRequestError{
Message: "客户端 tool_search 暂不支持并行工具调用",
Param: "parallel_tool_calls", Code: "unsupported_parameter",
}
}
return nil
}
func decodeOptionalArray(raw json.RawMessage, param string) ([]any, bool, error) {
if isEmptyJSON(raw) {
return nil, false, nil
}
var values []any
if err := json.Unmarshal(raw, &values); err != nil {
return nil, false, &responsesRequestError{Message: param + " 必须是数组", Param: param, Code: "invalid_parameter"}
}
return values, true, nil
}
func inspectToolSearch(tools []any) (bool, error) {
clientSearch := false
for index, rawTool := range tools {
tool, ok := rawTool.(map[string]any)
if !ok {
return false, &responsesRequestError{Message: fmt.Sprintf("tools[%d] 必须是对象", index), Param: fmt.Sprintf("tools[%d]", index), Code: "invalid_parameter"}
}
if stringField(tool, "type") != "tool_search" {
continue
}
param := fmt.Sprintf("tools[%d]", index)
execution := strings.ToLower(strings.TrimSpace(stringField(tool, "execution")))
if execution == "" || execution == "server" {
return false, &responsesRequestError{
Message: "Grok Build 上游不支持服务端 tool_search;请使用 execution: \"client\"",
Param: param + ".execution", Code: "unsupported_parameter",
}
}
if execution != "client" {
return false, &responsesRequestError{Message: "tool_search.execution 只支持 client", Param: param + ".execution", Code: "unsupported_parameter"}
}
if clientSearch {
return false, &responsesRequestError{Message: "单次请求只能声明一个客户端 tool_search", Param: param, Code: "invalid_parameter"}
}
clientSearch = true
}
return clientSearch, nil
}
func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, clientSearch, force bool, param string) ([]any, error) {
tool, ok := raw.(map[string]any)
if !ok {
return nil, &responsesRequestError{Message: param + " 必须是对象", Param: param, Code: "invalid_parameter"}
}
kind := strings.TrimSpace(stringField(tool, "type"))
switch kind {
case "function":
name := strings.TrimSpace(stringField(tool, "name"))
if name == "" {
return nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"}
}
deferred, _ := tool["defer_loading"].(bool)
if deferred && !clientSearch && !force {
return nil, &responsesRequestError{
Message: "defer_loading: true 需要 execution: \"client\" 的 tool_search",
Param: param + ".defer_loading", Code: "invalid_parameter",
}
}
if deferred && clientSearch && !force {
c.changed = true
if namespace == "" {
c.deferredSurfaces = append(c.deferredSurfaces, describeDeferredTool(name, stringField(tool, "description")))
}
return nil, nil
}
converted := cloneJSONObject(tool)
identity := responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}
alias := c.alias(identity)
converted["name"] = alias
if namespace != "" || alias != name {
c.changed = true
}
if _, exists := converted["defer_loading"]; exists {
delete(converted, "defer_loading")
c.changed = true
}
return []any{converted}, nil
case "namespace":
name := strings.TrimSpace(stringField(tool, "name"))
if name == "" {
return nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"}
}
children, ok := tool["tools"].([]any)
if !ok {
return nil, &responsesRequestError{Message: param + ".tools 必须是数组", Param: param + ".tools", Code: "invalid_parameter"}
}
c.changed = true
c.addWarning("namespace_flattened")
if clientSearch && !force && namespaceHasDeferredFunctions(children) {
c.deferredSurfaces = append(c.deferredSurfaces, describeDeferredTool(name, stringField(tool, "description")))
}
converted := make([]any, 0, len(children))
for index, rawChild := range children {
child, childOK := rawChild.(map[string]any)
childParam := fmt.Sprintf("%s.tools[%d]", param, index)
if !childOK {
return nil, &responsesRequestError{Message: childParam + " 必须是对象", Param: childParam, Code: "invalid_parameter"}
}
if stringField(child, "type") != "function" {
return nil, &responsesRequestError{Message: "namespace 内只支持 function 工具", Param: childParam + ".type", Code: "unsupported_parameter"}
}
items, err := c.normalizeTool(child, name, clientSearch, force, childParam)
if err != nil {
return nil, err
}
converted = append(converted, items...)
}
return converted, nil
case "tool_search":
if force {
return nil, &responsesRequestError{Message: "tool_search_output.tools 不能再次声明 tool_search", Param: param, Code: "unsupported_parameter"}
}
c.changed = true
c.addWarning("client_tool_search_emulated")
c.clientSearchTool = cloneJSONObject(tool)
c.clientSearchParam = param
return nil, nil
case "custom":
return c.normalizeCustomTool(tool, namespace, param)
case "web_search", "web_search_preview", "web_search_preview_2025_03_11", "web_search_2025_08_26":
return c.normalizeWebSearchTool(tool, kind, param)
case "mcp":
return c.normalizeMCPTool(tool, clientSearch, force, param)
case "shell":
return c.normalizeShellTool(tool, param)
case "local_shell":
return c.normalizeLegacyLocalShellTool(tool, param)
case "apply_patch":
return c.normalizeApplyPatchTool(tool, namespace, param)
case "x_search", "image_generation", "collections_search", "file_search", "code_execution", "code_interpreter":
return c.normalizeNativeTool(tool, param)
case "computer_use_preview":
return nil, unsupportedBuildToolError(kind, param)
default:
if kind == "" {
return nil, &responsesRequestError{Message: param + ".type 不能为空", Param: param + ".type", Code: "invalid_parameter"}
}
return nil, unsupportedBuildToolError(kind, param)
}
}
func namespaceHasDeferredFunctions(children []any) bool {
for _, rawChild := range children {
child, ok := rawChild.(map[string]any)
if !ok || stringField(child, "type") != "function" {
continue
}
if deferred, _ := child["defer_loading"].(bool); deferred {
return true
}
}
return false
}
func describeDeferredTool(name, description string) string {
description = strings.TrimSpace(description)
if description == "" {
return name
}
if len(description) > 240 {
description = description[:240]
}
return name + ": " + description
}
func (c *responsesToolCompatibility) buildClientSearchFunction() (map[string]any, error) {
identity := responsesToolIdentity{Kind: responsesToolSearch, Name: "tool_search"}
description := strings.TrimSpace(stringField(c.clientSearchTool, "description"))
if description == "" {
description = "Search for tools needed to continue the task."
}
if len(c.deferredSurfaces) > 0 {
description += "\nDeferred tool surfaces available to search:\n- " + strings.Join(c.deferredSurfaces, "\n- ")
}
if len(description) > maxToolSearchDescriptionBytes {
description = description[:maxToolSearchDescriptionBytes]
}
parameters, exists := c.clientSearchTool["parameters"]
if !exists {
parameters = map[string]any{"type": "object", "properties": map[string]any{}, "additionalProperties": true}
} else if _, ok := parameters.(map[string]any); !ok {
return nil, &responsesRequestError{Message: "tool_search.parameters 必须是对象", Param: c.clientSearchParam + ".parameters", Code: "invalid_parameter"}
}
return map[string]any{
"type": "function", "name": c.alias(identity), "description": description,
"parameters": cloneJSONValue(parameters),
}, nil
}
@@ -0,0 +1,148 @@
package cli
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
)
const (
maxBuildToolAliasLength = 128
maxToolSearchDescriptionBytes = 16 << 10
)
type responsesToolKind uint8
const (
responsesFunctionTool responsesToolKind = iota
responsesCustomTool
responsesToolSearch
responsesApplyPatchTool
)
type responsesToolIdentity struct {
Kind responsesToolKind
Namespace string
Name string
}
func (i responsesToolIdentity) key() string {
return fmt.Sprintf("%d\x00%s\x00%s", i.Kind, i.Namespace, i.Name)
}
// responsesToolCompatibility 保存一次请求内的工具别名和响应恢复状态;实例不得跨请求复用。
type responsesToolCompatibility struct {
aliases map[string]responsesToolIdentity
identityAliases map[string]string
visibleTools []any
deferredSurfaces []string
clientSearchTool map[string]any
clientSearchParam string
streamCalls map[string]*responsesStreamCall
legacyLocalShell bool
nativeShell bool
webSearchDisabled bool
warnings []string
warningSet map[string]struct{}
changed bool
}
// responsesRequestError 表示可直接映射为 OpenAI 错误结构的 Provider 请求错误。
type responsesRequestError struct {
Message string
Param string
Code string
}
func (e *responsesRequestError) Error() string { return e.Message }
func newResponsesToolCompatibility() *responsesToolCompatibility {
return &responsesToolCompatibility{
aliases: make(map[string]responsesToolIdentity),
identityAliases: make(map[string]string),
streamCalls: make(map[string]*responsesStreamCall),
warningSet: make(map[string]struct{}),
}
}
func (c *responsesToolCompatibility) alias(identity responsesToolIdentity) string {
key := identity.key()
if alias, exists := c.identityAliases[key]; exists {
return alias
}
base := identity.Name
if identity.Kind == responsesToolSearch {
base = "grok2api_tool_search"
} else if identity.Kind == responsesApplyPatchTool {
base = "grok2api_apply_patch"
} else if identity.Namespace != "" {
separator := "__"
if strings.HasSuffix(identity.Namespace, separator) {
separator = ""
}
base = identity.Namespace + separator + identity.Name
}
alias := truncateToolAlias(base, key)
if existing, collision := c.aliases[alias]; collision && existing.key() != key {
alias = hashedToolAlias(base, key)
}
c.aliases[alias] = identity
c.identityAliases[key] = alias
return alias
}
func truncateToolAlias(base, key string) string {
if len(base) <= maxBuildToolAliasLength {
return base
}
return hashedToolAlias(base, key)
}
func hashedToolAlias(base, key string) string {
suffix := "__" + shortToolHash(key)
limit := maxBuildToolAliasLength - len(suffix)
if len(base) > limit {
base = base[:limit]
}
return base + suffix
}
func shortToolHash(value string) string {
sum := sha256.Sum256([]byte(value))
return hex.EncodeToString(sum[:])[:9]
}
func stringField(value map[string]any, key string) string {
text, _ := value[key].(string)
return text
}
func cloneJSONArray(values []any) []any {
cloned := make([]any, len(values))
for index, value := range values {
cloned[index] = cloneJSONValue(value)
}
return cloned
}
func cloneJSONObject(value map[string]any) map[string]any {
cloned := make(map[string]any, len(value))
for key, item := range value {
cloned[key] = cloneJSONValue(item)
}
return cloned
}
func cloneJSONValue(value any) any {
data, err := json.Marshal(value)
if err != nil {
return value
}
var cloned any
if json.Unmarshal(data, &cloned) != nil {
return value
}
return cloned
}
@@ -1,718 +0,0 @@
package cli
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
)
const (
maxBuildToolAliasLength = 128
maxToolSearchDescriptionBytes = 16 << 10
)
type responsesToolKind uint8
const (
responsesFunctionTool responsesToolKind = iota
responsesCustomTool
responsesToolSearch
responsesApplyPatchTool
)
type responsesToolIdentity struct {
Kind responsesToolKind
Namespace string
Name string
}
func (i responsesToolIdentity) key() string {
return fmt.Sprintf("%d\x00%s\x00%s", i.Kind, i.Namespace, i.Name)
}
// responsesToolCompatibility 保存一次请求内的工具别名,避免跨请求共享可变协议状态。
type responsesToolCompatibility struct {
aliases map[string]responsesToolIdentity
identityAliases map[string]string
visibleTools []any
deferredSurfaces []string
clientSearchTool map[string]any
clientSearchParam string
streamCalls map[string]*responsesStreamCall
legacyLocalShell bool
nativeShell bool
webSearchDisabled bool
warnings []string
warningSet map[string]struct{}
changed bool
}
// responsesRequestError 表示可直接映射为 OpenAI 错误结构的 Provider 请求错误。
type responsesRequestError struct {
Message string
Param string
Code string
}
func (e *responsesRequestError) Error() string { return e.Message }
func newResponsesToolCompatibility() *responsesToolCompatibility {
return &responsesToolCompatibility{
aliases: make(map[string]responsesToolIdentity),
identityAliases: make(map[string]string),
streamCalls: make(map[string]*responsesStreamCall),
warningSet: make(map[string]struct{}),
}
}
// normalizeResponsesTools 将 namespace 和客户端 Tool Search 收敛为 Grok Build 支持的普通函数协议。
func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesToolCompatibility, error) {
compatibility := newResponsesToolCompatibility()
tools, hasTools, err := decodeOptionalArray(payload["tools"], "tools")
if err != nil {
return nil, err
}
if hasTools {
compatibility.visibleTools = cloneJSONArray(tools)
}
clientSearch, err := inspectToolSearch(tools)
if err != nil {
return nil, err
}
if err := compatibility.normalizeClientToolSearchParallel(payload, clientSearch); err != nil {
return nil, err
}
normalizedTools := make([]any, 0, len(tools))
for index, rawTool := range tools {
converted, convertErr := compatibility.normalizeTool(rawTool, "", clientSearch, false, fmt.Sprintf("tools[%d]", index))
if convertErr != nil {
return nil, convertErr
}
normalizedTools = append(normalizedTools, converted...)
}
if rawInput := payload["input"]; !isEmptyJSON(rawInput) {
var input any
if err := json.Unmarshal(rawInput, &input); err != nil {
return nil, &responsesRequestError{Message: "input 必须是字符串或数组", Param: "input", Code: "invalid_parameter"}
}
if items, ok := input.([]any); ok {
rewritten, loadedTools, visibleTools, rewriteErr := compatibility.normalizeInputItems(items)
if rewriteErr != nil {
return nil, rewriteErr
}
normalizedTools = append(normalizedTools, loadedTools...)
compatibility.visibleTools = append(compatibility.visibleTools, visibleTools...)
payload["input"] = mustJSON(rewritten)
}
}
if compatibility.clientSearchTool != nil {
searchTool, searchErr := compatibility.buildClientSearchFunction()
if searchErr != nil {
return nil, searchErr
}
normalizedTools = append(normalizedTools, searchTool)
}
normalizedTools = dedupeNormalizedTools(normalizedTools)
if len(normalizedTools) > 0 {
payload["tools"] = mustJSON(normalizedTools)
} else if hasTools && compatibility.webSearchDisabled {
delete(payload, "tools")
compatibility.changed = true
}
if err := compatibility.normalizeToolChoice(payload, normalizedTools); err != nil {
return nil, err
}
if !compatibility.changed {
return nil, nil
}
return compatibility, nil
}
// normalizeClientToolSearchParallel 保证搜索函数先独立完成,再由客户端选择并回传工具定义。
func (c *responsesToolCompatibility) normalizeClientToolSearchParallel(payload map[string]json.RawMessage, clientSearch bool) error {
if !clientSearch {
return nil
}
raw, exists := payload["parallel_tool_calls"]
if !exists || isEmptyJSON(raw) {
payload["parallel_tool_calls"] = mustJSON(false)
c.changed = true
return nil
}
var parallel bool
if err := json.Unmarshal(raw, &parallel); err != nil {
return &responsesRequestError{
Message: "parallel_tool_calls 必须是布尔值",
Param: "parallel_tool_calls", Code: "invalid_parameter",
}
}
if parallel {
return &responsesRequestError{
Message: "客户端 tool_search 暂不支持并行工具调用",
Param: "parallel_tool_calls", Code: "unsupported_parameter",
}
}
return nil
}
func decodeOptionalArray(raw json.RawMessage, param string) ([]any, bool, error) {
if isEmptyJSON(raw) {
return nil, false, nil
}
var values []any
if err := json.Unmarshal(raw, &values); err != nil {
return nil, false, &responsesRequestError{Message: param + " 必须是数组", Param: param, Code: "invalid_parameter"}
}
return values, true, nil
}
func inspectToolSearch(tools []any) (bool, error) {
clientSearch := false
for index, rawTool := range tools {
tool, ok := rawTool.(map[string]any)
if !ok {
return false, &responsesRequestError{Message: fmt.Sprintf("tools[%d] 必须是对象", index), Param: fmt.Sprintf("tools[%d]", index), Code: "invalid_parameter"}
}
if stringField(tool, "type") != "tool_search" {
continue
}
param := fmt.Sprintf("tools[%d]", index)
execution := strings.ToLower(strings.TrimSpace(stringField(tool, "execution")))
if execution == "" || execution == "server" {
return false, &responsesRequestError{
Message: "Grok Build 上游不支持服务端 tool_search;请使用 execution: \"client\"",
Param: param + ".execution", Code: "unsupported_parameter",
}
}
if execution != "client" {
return false, &responsesRequestError{Message: "tool_search.execution 只支持 client", Param: param + ".execution", Code: "unsupported_parameter"}
}
if clientSearch {
return false, &responsesRequestError{Message: "单次请求只能声明一个客户端 tool_search", Param: param, Code: "invalid_parameter"}
}
clientSearch = true
}
return clientSearch, nil
}
func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, clientSearch, force bool, param string) ([]any, error) {
tool, ok := raw.(map[string]any)
if !ok {
return nil, &responsesRequestError{Message: param + " 必须是对象", Param: param, Code: "invalid_parameter"}
}
kind := strings.TrimSpace(stringField(tool, "type"))
switch kind {
case "function":
name := strings.TrimSpace(stringField(tool, "name"))
if name == "" {
return nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"}
}
deferred, _ := tool["defer_loading"].(bool)
if deferred && !clientSearch && !force {
return nil, &responsesRequestError{
Message: "defer_loading: true 需要 execution: \"client\" 的 tool_search",
Param: param + ".defer_loading", Code: "invalid_parameter",
}
}
if deferred && clientSearch && !force {
c.changed = true
if namespace == "" {
c.deferredSurfaces = append(c.deferredSurfaces, describeDeferredTool(name, stringField(tool, "description")))
}
return nil, nil
}
converted := cloneJSONObject(tool)
identity := responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}
alias := c.alias(identity)
converted["name"] = alias
if namespace != "" || alias != name {
c.changed = true
}
if _, exists := converted["defer_loading"]; exists {
delete(converted, "defer_loading")
c.changed = true
}
return []any{converted}, nil
case "namespace":
name := strings.TrimSpace(stringField(tool, "name"))
if name == "" {
return nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"}
}
children, ok := tool["tools"].([]any)
if !ok {
return nil, &responsesRequestError{Message: param + ".tools 必须是数组", Param: param + ".tools", Code: "invalid_parameter"}
}
c.changed = true
c.addWarning("namespace_flattened")
if clientSearch && !force && namespaceHasDeferredFunctions(children) {
c.deferredSurfaces = append(c.deferredSurfaces, describeDeferredTool(name, stringField(tool, "description")))
}
converted := make([]any, 0, len(children))
for index, rawChild := range children {
child, childOK := rawChild.(map[string]any)
childParam := fmt.Sprintf("%s.tools[%d]", param, index)
if !childOK {
return nil, &responsesRequestError{Message: childParam + " 必须是对象", Param: childParam, Code: "invalid_parameter"}
}
if stringField(child, "type") != "function" {
return nil, &responsesRequestError{Message: "namespace 内只支持 function 工具", Param: childParam + ".type", Code: "unsupported_parameter"}
}
items, err := c.normalizeTool(child, name, clientSearch, force, childParam)
if err != nil {
return nil, err
}
converted = append(converted, items...)
}
return converted, nil
case "tool_search":
if force {
return nil, &responsesRequestError{Message: "tool_search_output.tools 不能再次声明 tool_search", Param: param, Code: "unsupported_parameter"}
}
c.changed = true
c.addWarning("client_tool_search_emulated")
c.clientSearchTool = cloneJSONObject(tool)
c.clientSearchParam = param
return nil, nil
case "custom":
return c.normalizeCustomTool(tool, namespace, param)
case "web_search", "web_search_preview", "web_search_preview_2025_03_11", "web_search_2025_08_26":
return c.normalizeWebSearchTool(tool, kind, param)
case "mcp":
return c.normalizeMCPTool(tool, clientSearch, force, param)
case "shell":
return c.normalizeShellTool(tool, param)
case "local_shell":
return c.normalizeLegacyLocalShellTool(tool, param)
case "apply_patch":
return c.normalizeApplyPatchTool(tool, namespace, param)
case "x_search", "image_generation", "collections_search", "file_search", "code_execution", "code_interpreter":
return c.normalizeNativeTool(tool, param)
case "computer_use_preview":
return nil, unsupportedBuildToolError(kind, param)
default:
if kind == "" {
return nil, &responsesRequestError{Message: param + ".type 不能为空", Param: param + ".type", Code: "invalid_parameter"}
}
return nil, unsupportedBuildToolError(kind, param)
}
}
func namespaceHasDeferredFunctions(children []any) bool {
for _, rawChild := range children {
child, ok := rawChild.(map[string]any)
if !ok || stringField(child, "type") != "function" {
continue
}
if deferred, _ := child["defer_loading"].(bool); deferred {
return true
}
}
return false
}
func describeDeferredTool(name, description string) string {
description = strings.TrimSpace(description)
if description == "" {
return name
}
if len(description) > 240 {
description = description[:240]
}
return name + ": " + description
}
func (c *responsesToolCompatibility) buildClientSearchFunction() (map[string]any, error) {
identity := responsesToolIdentity{Kind: responsesToolSearch, Name: "tool_search"}
description := strings.TrimSpace(stringField(c.clientSearchTool, "description"))
if description == "" {
description = "Search for tools needed to continue the task."
}
if len(c.deferredSurfaces) > 0 {
description += "\nDeferred tool surfaces available to search:\n- " + strings.Join(c.deferredSurfaces, "\n- ")
}
if len(description) > maxToolSearchDescriptionBytes {
description = description[:maxToolSearchDescriptionBytes]
}
parameters, exists := c.clientSearchTool["parameters"]
if !exists {
parameters = map[string]any{"type": "object", "properties": map[string]any{}, "additionalProperties": true}
} else if _, ok := parameters.(map[string]any); !ok {
return nil, &responsesRequestError{Message: "tool_search.parameters 必须是对象", Param: c.clientSearchParam + ".parameters", Code: "invalid_parameter"}
}
return map[string]any{
"type": "function", "name": c.alias(identity), "description": description,
"parameters": cloneJSONValue(parameters),
}, nil
}
func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, []any, []any, error) {
rewritten := make([]any, 0, len(items))
loadedTools := make([]any, 0)
visibleTools := make([]any, 0)
for index, rawItem := range items {
item, ok := rawItem.(map[string]any)
if !ok {
rewritten = append(rewritten, rawItem)
continue
}
param := fmt.Sprintf("input[%d]", index)
switch stringField(item, "type") {
case "function_call":
namespace := strings.TrimSpace(stringField(item, "namespace"))
if namespace == "" {
rewritten = append(rewritten, cloneJSONValue(item))
continue
}
name := strings.TrimSpace(stringField(item, "name"))
if name == "" {
return nil, nil, nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"}
}
converted := cloneJSONObject(item)
converted["name"] = c.alias(responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name})
delete(converted, "namespace")
c.changed = true
rewritten = append(rewritten, converted)
case "tool_search_call":
callID := strings.TrimSpace(stringField(item, "call_id"))
if callID == "" {
return nil, nil, nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"}
}
arguments, err := encodeFunctionArguments(item["arguments"])
if err != nil {
return nil, nil, nil, &responsesRequestError{Message: param + ".arguments 无法编码", Param: param + ".arguments", Code: "invalid_parameter"}
}
converted := map[string]any{
"type": "function_call", "call_id": callID,
"name": c.alias(responsesToolIdentity{Kind: responsesToolSearch, Name: "tool_search"}), "arguments": arguments,
}
c.changed = true
rewritten = append(rewritten, converted)
case "tool_search_output":
execution := strings.ToLower(strings.TrimSpace(stringField(item, "execution")))
if execution != "client" {
return nil, nil, nil, &responsesRequestError{Message: "Grok Build 只兼容客户端 tool_search_output", Param: param + ".execution", Code: "unsupported_parameter"}
}
callID := strings.TrimSpace(stringField(item, "call_id"))
if callID == "" {
return nil, nil, nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"}
}
tools, ok := item["tools"].([]any)
if !ok {
return nil, nil, nil, &responsesRequestError{Message: param + ".tools 必须是数组", Param: param + ".tools", Code: "invalid_parameter"}
}
for toolIndex, rawTool := range tools {
converted, err := c.normalizeTool(rawTool, "", false, true, fmt.Sprintf("%s.tools[%d]", param, toolIndex))
if err != nil {
return nil, nil, nil, err
}
loadedTools = append(loadedTools, converted...)
}
visibleTools = append(visibleTools, cloneJSONArray(tools)...)
c.changed = true
rewritten = append(rewritten, map[string]any{
"type": "function_call_output", "call_id": callID,
"output": fmt.Sprintf("Tool search completed; %d selected tool definitions are now available.", len(tools)),
})
case "custom_tool_call":
name := strings.TrimSpace(stringField(item, "name"))
if name == "" {
return nil, nil, nil, &responsesRequestError{Message: param + ".name 不能为空", Param: param + ".name", Code: "invalid_parameter"}
}
input, ok := item["input"].(string)
if !ok {
return nil, nil, nil, &responsesRequestError{Message: param + ".input 必须是字符串", Param: param + ".input", Code: "invalid_parameter"}
}
arguments, err := encodeCustomToolArguments(input)
if err != nil {
return nil, nil, nil, err
}
namespace := strings.TrimSpace(stringField(item, "namespace"))
converted := cloneJSONObject(item)
converted["type"] = "function_call"
converted["name"] = c.alias(responsesToolIdentity{Kind: responsesCustomTool, Namespace: namespace, Name: name})
converted["arguments"] = arguments
delete(converted, "input")
delete(converted, "namespace")
c.changed = true
rewritten = append(rewritten, converted)
case "custom_tool_call_output":
converted := cloneJSONObject(item)
converted["type"] = "function_call_output"
delete(converted, "name")
delete(converted, "namespace")
c.changed = true
rewritten = append(rewritten, converted)
case "apply_patch_call":
converted, err := c.normalizeApplyPatchCallInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "apply_patch_call_output":
converted, err := normalizeApplyPatchOutputInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "agent_message":
if _, visible := textInputContent(item["content"]); !visible {
c.addWarning("opaque_agent_message_redacted")
}
converted, err := normalizeAgentMessageInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "local_shell_call":
converted, err := normalizeLegacyLocalShellCallInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "local_shell_call_output":
converted, err := normalizeLegacyLocalShellOutputInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "mcp_tool_call_output":
converted, err := normalizeMCPOutputInput(item, param)
if err != nil {
return nil, nil, nil, err
}
c.changed = true
rewritten = append(rewritten, converted)
case "compaction_trigger":
c.changed = true
c.addWarning("compaction_boundary_preserved")
rewritten = append(rewritten, compatibilityBoundaryMessage("Codex context compaction boundary reached."))
case "additional_tools":
marker, additional, visible, err := c.normalizeAdditionalToolsInput(item, param)
if err != nil {
return nil, nil, nil, err
}
loadedTools = append(loadedTools, additional...)
visibleTools = append(visibleTools, visible...)
c.changed = true
rewritten = append(rewritten, marker)
default:
rewritten = append(rewritten, cloneJSONValue(item))
}
}
return rewritten, loadedTools, visibleTools, nil
}
func encodeFunctionArguments(value any) (string, error) {
if text, ok := value.(string); ok {
return text, nil
}
if value == nil {
return "{}", nil
}
encoded, err := json.Marshal(value)
if err != nil {
return "", err
}
return string(encoded), nil
}
func (c *responsesToolCompatibility) normalizeToolChoice(payload map[string]json.RawMessage, normalizedTools []any) error {
raw := payload["tool_choice"]
if isEmptyJSON(raw) {
return nil
}
var choice any
if err := json.Unmarshal(raw, &choice); err != nil {
return &responsesRequestError{Message: "tool_choice 格式无效", Param: "tool_choice", Code: "invalid_parameter"}
}
object, ok := choice.(map[string]any)
if !ok {
if value, isString := choice.(string); isString && (value == "auto" || value == "required") && c.webSearchDisabled && len(normalizedTools) == 0 {
payload["tool_choice"] = mustJSON("none")
c.changed = true
c.addWarning("web_search_tool_choice_disabled")
}
return nil
}
kind := stringField(object, "type")
if c.webSearchDisabled && normalizeHostedToolChoiceKind(kind) == "web_search" && !hasToolType(normalizedTools, "web_search") {
payload["tool_choice"] = mustJSON("none")
c.changed = true
c.addWarning("web_search_tool_choice_disabled")
return nil
}
if kind == "tool_search" {
if c.clientSearchTool == nil {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 tool_search", Param: "tool_choice", Code: "invalid_parameter"}
}
object = map[string]any{
"type": "function",
"name": c.alias(responsesToolIdentity{Kind: responsesToolSearch, Name: "tool_search"}),
}
c.changed = true
payload["tool_choice"] = mustJSON(object)
return nil
}
if kind == "custom" {
name := strings.TrimSpace(stringField(object, "name"))
namespace := strings.TrimSpace(stringField(object, "namespace"))
if name == "" {
return &responsesRequestError{Message: "tool_choice.name 不能为空", Param: "tool_choice.name", Code: "invalid_parameter"}
}
identity := responsesToolIdentity{Kind: responsesCustomTool, Namespace: namespace, Name: name}
alias, exists := c.identityAliases[identity.key()]
if !exists {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 custom 工具", Param: "tool_choice.name", Code: "invalid_parameter"}
}
object["type"] = "function"
object["name"] = alias
delete(object, "namespace")
c.changed = true
payload["tool_choice"] = mustJSON(object)
return nil
}
if kind == "apply_patch" {
identity := responsesToolIdentity{Kind: responsesApplyPatchTool, Name: "apply_patch"}
alias, exists := c.identityAliases[identity.key()]
if !exists {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 apply_patch 工具", Param: "tool_choice", Code: "invalid_parameter"}
}
payload["tool_choice"] = mustJSON(map[string]any{"type": "function", "name": alias})
c.changed = true
return nil
}
if normalizedKind := normalizeHostedToolChoiceKind(kind); normalizedKind != "" {
if !hasSingleToolType(normalizedTools, normalizedKind) {
return &responsesRequestError{
Message: "Grok Build 仅能在请求中只有一个匹配工具时兼容 hosted tool_choice",
Param: "tool_choice", Code: "unsupported_parameter",
}
}
payload["tool_choice"] = mustJSON("required")
c.changed = true
return nil
}
if kind != "function" {
return &responsesRequestError{Message: fmt.Sprintf("Grok Build 不支持 tool_choice.type=%q", kind), Param: "tool_choice.type", Code: "unsupported_parameter"}
}
name := strings.TrimSpace(stringField(object, "name"))
namespace := strings.TrimSpace(stringField(object, "namespace"))
if function, nested := object["function"].(map[string]any); nested {
name = strings.TrimSpace(stringField(function, "name"))
namespace = strings.TrimSpace(stringField(function, "namespace"))
if name != "" && namespace != "" {
identity := responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}
alias, exists := c.identityAliases[identity.key()]
if !exists {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 namespace 函数", Param: "tool_choice.function.name", Code: "invalid_parameter"}
}
function["name"] = alias
delete(function, "namespace")
c.changed = true
payload["tool_choice"] = mustJSON(object)
}
return nil
}
if name == "" || namespace == "" {
return nil
}
identity := responsesToolIdentity{Kind: responsesFunctionTool, Namespace: namespace, Name: name}
alias, exists := c.identityAliases[identity.key()]
if !exists {
return &responsesRequestError{Message: "tool_choice 引用了未声明的 namespace 函数", Param: "tool_choice.name", Code: "invalid_parameter"}
}
object["name"] = alias
delete(object, "namespace")
c.changed = true
payload["tool_choice"] = mustJSON(object)
return nil
}
func (c *responsesToolCompatibility) alias(identity responsesToolIdentity) string {
key := identity.key()
if alias, exists := c.identityAliases[key]; exists {
return alias
}
base := identity.Name
if identity.Kind == responsesToolSearch {
base = "grok2api_tool_search"
} else if identity.Kind == responsesApplyPatchTool {
base = "grok2api_apply_patch"
} else if identity.Namespace != "" {
separator := "__"
if strings.HasSuffix(identity.Namespace, separator) {
separator = ""
}
base = identity.Namespace + separator + identity.Name
}
alias := truncateToolAlias(base, key)
if existing, collision := c.aliases[alias]; collision && existing.key() != key {
alias = hashedToolAlias(base, key)
}
c.aliases[alias] = identity
c.identityAliases[key] = alias
return alias
}
func truncateToolAlias(base, key string) string {
if len(base) <= maxBuildToolAliasLength {
return base
}
return hashedToolAlias(base, key)
}
func hashedToolAlias(base, key string) string {
suffix := "__" + shortToolHash(key)
limit := maxBuildToolAliasLength - len(suffix)
if len(base) > limit {
base = base[:limit]
}
return base + suffix
}
func shortToolHash(value string) string {
sum := sha256.Sum256([]byte(value))
return hex.EncodeToString(sum[:])[:9]
}
func stringField(value map[string]any, key string) string {
text, _ := value[key].(string)
return text
}
func cloneJSONArray(values []any) []any {
cloned := make([]any, len(values))
for index, value := range values {
cloned[index] = cloneJSONValue(value)
}
return cloned
}
func cloneJSONObject(value map[string]any) map[string]any {
cloned := make(map[string]any, len(value))
for key, item := range value {
cloned[key] = cloneJSONValue(item)
}
return cloned
}
func cloneJSONValue(value any) any {
switch typed := value.(type) {
case map[string]any:
return cloneJSONObject(typed)
case []any:
return cloneJSONArray(typed)
default:
return value
}
}
@@ -34,27 +34,14 @@ type Adapter struct {
}
func NewAdapter(cfg Config, egress *infraegress.Manager, cipher *security.Cipher) *Adapter {
return &Adapter{cfg: normalizedConfig(cfg), egress: egress, cipher: cipher}
}
func normalizedConfig(cfg Config) Config {
if strings.TrimSpace(cfg.BaseURL) == "" {
cfg.BaseURL = "https://console.x.ai"
}
if strings.TrimSpace(cfg.UserAgent) == "" {
cfg.UserAgent = infraegress.DefaultUserAgent
}
if cfg.TimeoutSeconds <= 0 {
cfg.TimeoutSeconds = 300
}
return cfg
return &Adapter{cfg: cfg, egress: egress, cipher: cipher}
}
func (a *Adapter) Provider() account.Provider { return account.ProviderConsole }
func (a *Adapter) UpdateConfig(cfg Config) {
a.mu.Lock()
a.cfg = normalizedConfig(cfg)
a.cfg = cfg
a.mu.Unlock()
}
@@ -238,7 +238,7 @@ func newConsoleTestAdapter(t *testing.T, baseURL string) (*Adapter, account.Cred
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{BaseURL: baseURL}, infraegress.NewManager(consoleEgressRepositoryStub{}, cipher), cipher)
adapter := NewAdapter(Config{BaseURL: baseURL, UserAgent: "console-test", TimeoutSeconds: 5}, infraegress.NewManager(consoleEgressRepositoryStub{}, cipher), cipher)
credential := account.Credential{ID: 1, Provider: account.ProviderConsole, AuthType: account.AuthTypeSSO, EncryptedAccessToken: encrypted}
return adapter, credential
}
@@ -0,0 +1,216 @@
package conversation
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
)
// convertChatRequest 将 Chat Completions 请求完整转换为标准 Responses 输入。
func convertChatRequest(body []byte, model string) ([]byte, error) {
var source map[string]json.RawMessage
if err := json.Unmarshal(body, &source); err != nil {
return nil, fmt.Errorf("解析 Chat Completions 请求: %w", err)
}
var messages []chatMessage
if err := json.Unmarshal(source["messages"], &messages); err != nil || len(messages) == 0 {
return nil, errors.New("messages 必须是非空数组")
}
input, err := convertChatMessages(messages)
if err != nil {
return nil, err
}
target := map[string]json.RawMessage{"model": mustJSON(model), "input": mustJSON(input)}
copyFields(target, source, "stream", "temperature", "top_p", "presence_penalty", "frequency_penalty", "seed", "user", "parallel_tool_calls", "metadata", "store", "service_tier", "stop")
if raw := firstJSON(source["max_completion_tokens"], source["max_tokens"]); !isEmptyJSON(raw) {
target["max_output_tokens"] = raw
}
if raw := source["response_format"]; !isEmptyJSON(raw) {
format, err := convertResponseFormat(raw)
if err != nil {
return nil, err
}
target["text"] = mustJSON(map[string]json.RawMessage{"format": format})
}
if raw := source["reasoning_effort"]; !isEmptyJSON(raw) {
target["reasoning"] = mustJSON(map[string]json.RawMessage{"effort": raw})
}
if raw := source["tools"]; !isEmptyJSON(raw) {
tools, err := convertChatTools(raw)
if err != nil {
return nil, err
}
target["tools"] = mustJSON(tools)
}
if raw := source["tool_choice"]; !isEmptyJSON(raw) {
choice, err := convertChatToolChoice(raw)
if err != nil {
return nil, err
}
target["tool_choice"] = choice
}
return json.Marshal(target)
}
type chatMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
ToolCalls json.RawMessage `json:"tool_calls"`
ToolCallID string `json:"tool_call_id"`
Name string `json:"name"`
}
func convertChatMessages(messages []chatMessage) ([]any, error) {
input := make([]any, 0, len(messages))
for _, message := range messages {
role := strings.ToLower(strings.TrimSpace(message.Role))
switch role {
case "system", "developer", "user", "assistant":
if !isEmptyJSON(message.Content) && !bytes.Equal(bytes.TrimSpace(message.Content), []byte("null")) {
content, err := convertChatContent(message.Content)
if err != nil {
return nil, fmt.Errorf("%s 消息内容无效: %w", role, err)
}
input = append(input, map[string]any{"type": "message", "role": role, "content": content})
}
if role == "assistant" && !isEmptyJSON(message.ToolCalls) {
calls, err := convertAssistantToolCalls(message.ToolCalls)
if err != nil {
return nil, err
}
input = append(input, calls...)
}
case "tool":
if strings.TrimSpace(message.ToolCallID) == "" {
return nil, errors.New("tool 消息缺少 tool_call_id")
}
output, err := contentAsText(message.Content)
if err != nil {
return nil, err
}
input = append(input, map[string]any{"type": "function_call_output", "call_id": message.ToolCallID, "output": output})
default:
return nil, fmt.Errorf("不支持 messages.role=%q", message.Role)
}
}
if len(input) == 0 {
return nil, errors.New("messages 中没有可发送内容")
}
return input, nil
}
func convertChatContent(raw json.RawMessage) (any, error) {
var text string
if json.Unmarshal(raw, &text) == nil {
return text, nil
}
var parts []map[string]json.RawMessage
if err := json.Unmarshal(raw, &parts); err != nil {
return nil, errors.New("content 必须是字符串或内容数组")
}
result := make([]any, 0, len(parts))
for _, part := range parts {
var typeName string
_ = json.Unmarshal(part["type"], &typeName)
switch typeName {
case "text", "input_text", "output_text":
var value string
if json.Unmarshal(part["text"], &value) != nil {
return nil, errors.New("text 内容无效")
}
result = append(result, map[string]any{"type": "input_text", "text": value})
case "image_url", "input_image":
imageURL, err := parseImageURL(part)
if err != nil {
return nil, err
}
result = append(result, map[string]any{"type": "input_image", "image_url": imageURL})
default:
return nil, fmt.Errorf("不支持 content.type=%q", typeName)
}
}
return result, nil
}
func parseImageURL(part map[string]json.RawMessage) (string, error) {
raw := firstJSON(part["image_url"], part["url"])
var value string
if json.Unmarshal(raw, &value) == nil && strings.TrimSpace(value) != "" {
return value, nil
}
var nested struct {
URL string `json:"url"`
}
if json.Unmarshal(raw, &nested) == nil && strings.TrimSpace(nested.URL) != "" {
return nested.URL, nil
}
return "", errors.New("image_url 缺少有效 url")
}
func convertAssistantToolCalls(raw json.RawMessage) ([]any, error) {
var calls []struct {
ID string `json:"id"`
Type string `json:"type"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
if err := json.Unmarshal(raw, &calls); err != nil {
return nil, errors.New("assistant.tool_calls 格式无效")
}
result := make([]any, 0, len(calls))
for _, call := range calls {
if strings.TrimSpace(call.ID) == "" || strings.TrimSpace(call.Function.Name) == "" || !json.Valid([]byte(call.Function.Arguments)) {
return nil, errors.New("assistant.tool_calls 缺少有效 id、name 或 arguments")
}
result = append(result, map[string]any{"type": "function_call", "call_id": call.ID, "name": call.Function.Name, "arguments": call.Function.Arguments})
}
return result, nil
}
func convertChatTools(raw json.RawMessage) ([]any, error) {
var tools []map[string]json.RawMessage
if err := json.Unmarshal(raw, &tools); err != nil {
return nil, errors.New("tools 必须是数组")
}
result := make([]any, 0, len(tools))
for _, tool := range tools {
var typeName string
_ = json.Unmarshal(tool["type"], &typeName)
if typeName != "function" {
var value any
_ = json.Unmarshal(mustJSON(tool), &value)
result = append(result, value)
continue
}
var function map[string]any
if json.Unmarshal(tool["function"], &function) != nil {
return nil, errors.New("function tool 格式无效")
}
function["type"] = "function"
result = append(result, function)
}
return result, nil
}
func convertChatToolChoice(raw json.RawMessage) (json.RawMessage, error) {
var value map[string]json.RawMessage
if json.Unmarshal(raw, &value) != nil {
return raw, nil
}
var typeName string
_ = json.Unmarshal(value["type"], &typeName)
if typeName != "function" {
return raw, nil
}
var function struct {
Name string `json:"name"`
}
if json.Unmarshal(value["function"], &function) != nil || strings.TrimSpace(function.Name) == "" {
return nil, errors.New("tool_choice.function.name 无效")
}
return mustJSON(map[string]any{"type": "function", "name": function.Name}), nil
}
@@ -0,0 +1,45 @@
package conversation
import "strings"
func chatResponse(value parsedResponse) map[string]any {
message := map[string]any{"role": "assistant", "content": value.Text}
if value.Reasoning != "" {
message["reasoning_content"] = value.Reasoning
}
finishReason := "stop"
if len(value.Calls) > 0 {
finishReason = "tool_calls"
if value.Text == "" {
message["content"] = nil
}
calls := make([]any, 0, len(value.Calls))
for _, call := range value.Calls {
calls = append(calls, map[string]any{
"id": call.CallID, "type": "function",
"function": map[string]any{"name": call.Name, "arguments": call.Arguments},
})
}
message["tool_calls"] = calls
} else if value.Status == "incomplete" {
finishReason = "length"
}
if value.Refusal != "" {
message["refusal"] = value.Refusal
}
id := strings.Replace(value.ID, "resp_", "chatcmpl_", 1)
return map[string]any{
"id": id, "object": "chat.completion", "created": value.CreatedAt, "model": value.Model,
"choices": []any{map[string]any{"index": 0, "message": message, "finish_reason": finishReason}},
"usage": chatUsage(value.Usage),
}
}
func chatUsage(value responseUsage) map[string]any {
return map[string]any{
"prompt_tokens": value.InputTokens, "completion_tokens": value.OutputTokens,
"total_tokens": value.InputTokens + value.OutputTokens,
"prompt_tokens_details": map[string]any{"cached_tokens": value.InputTokensDetails.CachedTokens},
"completion_tokens_details": map[string]any{"reasoning_tokens": value.OutputTokensDetails.ReasoningTokens},
}
}
@@ -0,0 +1,96 @@
package conversation
import (
"encoding/json"
"io"
"strings"
)
func (c *streamConverter) startChat() error {
return c.writeData(map[string]any{
"id": strings.Replace(c.id, "resp_", "chatcmpl_", 1), "object": "chat.completion.chunk",
"created": c.created, "model": c.model,
"choices": []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant"}, "finish_reason": nil}},
})
}
func (c *streamConverter) textDeltaChat(delta string) error {
return c.chatDelta(map[string]any{"content": delta})
}
func (c *streamConverter) chatDelta(delta map[string]any) error {
if err := c.start(); err != nil {
return err
}
return c.writeData(map[string]any{
"id": strings.Replace(c.id, "resp_", "chatcmpl_", 1), "object": "chat.completion.chunk", "created": c.created, "model": c.model,
"choices": []any{map[string]any{"index": 0, "delta": delta, "finish_reason": nil}},
})
}
func (c *streamConverter) toolStartChat(item responseItem, outputIndex int) error {
if err := c.start(); err != nil {
return err
}
tool := streamTool{Index: outputIndex, ID: item.CallID, Name: item.Name, Arguments: item.Arguments}
c.tools[item.ID] = tool
return c.chatDelta(map[string]any{"tool_calls": []any{map[string]any{
"index": tool.Index, "id": tool.ID, "type": "function", "function": map[string]any{"name": tool.Name, "arguments": ""},
}}})
}
func (c *streamConverter) toolDeltaChat(itemID, delta string) error {
tool, ok := c.tools[itemID]
if !ok {
return nil
}
tool.SentArgs = true
c.tools[itemID] = tool
return c.chatDelta(map[string]any{"tool_calls": []any{map[string]any{"index": tool.Index, "function": map[string]any{"arguments": delta}}}})
}
func (c *streamConverter) toolArgumentsDoneChat(itemID, arguments string) error {
tool, ok := c.tools[itemID]
if !ok || tool.Closed {
return nil
}
if !tool.SentArgs {
if arguments == "" {
arguments = tool.Arguments
}
if arguments != "" {
if err := c.chatDelta(map[string]any{"tool_calls": []any{map[string]any{"index": tool.Index, "function": map[string]any{"arguments": arguments}}}}); err != nil {
return err
}
tool.SentArgs = true
}
}
c.tools[itemID] = tool
return nil
}
func (c *streamConverter) doneChat(status string) error {
finishReason := "stop"
if len(c.tools) > 0 {
finishReason = "tool_calls"
} else if status == "incomplete" {
finishReason = "length"
}
if err := c.writeData(map[string]any{
"id": strings.Replace(c.id, "resp_", "chatcmpl_", 1), "object": "chat.completion.chunk", "created": c.created, "model": c.model,
"choices": []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": finishReason}}, "usage": chatUsage(c.usage),
}); err != nil {
return err
}
c.finished = true
_, err := io.WriteString(c.writer, "data: [DONE]\n\n")
return err
}
func (c *streamConverter) streamErrorChat(data []byte) error {
if err := c.writeData(json.RawMessage(data)); err != nil {
return err
}
_, err := io.WriteString(c.writer, "data: [DONE]\n\n")
return err
}
@@ -0,0 +1,612 @@
package conversation
import (
"encoding/json"
"errors"
"fmt"
"strings"
)
func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, error) {
var request anthropicRequest
if err := json.Unmarshal(body, &request); err != nil {
return nil, ResponseOptions{}, fmt.Errorf("解析 Messages 请求: %w", err)
}
if len(request.Messages) == 0 {
return nil, ResponseOptions{}, errors.New("messages 必须是非空数组")
}
if request.MaxTokens <= 0 {
return nil, ResponseOptions{}, errors.New("max_tokens 必须是正整数")
}
for name, value := range map[string]*float64{"temperature": request.Temperature, "top_p": request.TopP} {
if value != nil && (*value < 0 || *value > 1) {
return nil, ResponseOptions{}, fmt.Errorf("%s 必须在 0 到 1 之间", name)
}
}
for index, sequence := range request.StopSequences {
if sequence == "" {
return nil, ResponseOptions{}, fmt.Errorf("stop_sequences[%d] 不能为空", index)
}
}
if !isEmptyJSON(request.TopK) {
return nil, ResponseOptions{}, errors.New("Messages top_k 无法等价映射到 Responses API")
}
thinkingEnabled := false
if request.Thinking != nil {
switch request.Thinking.Type {
case "", "disabled":
case "enabled", "adaptive":
thinkingEnabled = true
default:
return nil, ResponseOptions{}, fmt.Errorf("不支持 thinking.type=%q", request.Thinking.Type)
}
}
input, inlineInstructions, err := convertAnthropicMessages(request.Messages, anthropicDeclaredToolNames(request.Tools))
if err != nil {
return nil, ResponseOptions{}, err
}
if len(input) == 0 {
return nil, ResponseOptions{}, errors.New("messages 中没有可发送的 user 或 assistant 内容")
}
target := map[string]any{
"model": model, "input": input, "stream": request.Stream,
"max_output_tokens": request.MaxTokens, "store": false,
}
instructions := make([]string, 0, len(inlineInstructions))
if system, err := anthropicSystemText(request.System); err != nil {
return nil, ResponseOptions{}, err
} else if system != "" {
instructions = append(instructions, system)
}
instructions = append(instructions, inlineInstructions...)
if len(instructions) > 0 {
target["instructions"] = strings.Join(instructions, "\n\n")
}
copyOptionalNumber(target, "temperature", request.Temperature)
copyOptionalNumber(target, "top_p", request.TopP)
if request.Metadata != nil {
if userID, _ := request.Metadata["user_id"].(string); strings.TrimSpace(userID) != "" {
target["safety_identifier"] = strings.TrimSpace(userID)
}
}
if request.OutputConfig != nil && request.OutputConfig.Format != nil {
if request.OutputConfig.Format.Type != "json_schema" || request.OutputConfig.Format.Schema == nil {
return nil, ResponseOptions{}, errors.New("output_config.format 必须是带 schema 的 json_schema")
}
target["text"] = map[string]any{"format": map[string]any{"type": "json_schema", "name": "anthropic_output", "schema": request.OutputConfig.Format.Schema}}
}
if thinkingEnabled {
effort := anthropicThinkingEffort(request.Thinking.BudgetTokens)
if request.OutputConfig != nil && request.OutputConfig.Effort != "" {
effort = request.OutputConfig.Effort
}
switch effort {
case "minimal":
effort = "low"
case "max", "xhigh":
effort = "high"
case "low", "medium", "high":
default:
return nil, ResponseOptions{}, fmt.Errorf("不支持 output_config.effort=%q", effort)
}
target["reasoning"] = map[string]any{"effort": effort, "summary": "detailed"}
target["include"] = []any{"reasoning.encrypted_content"}
}
if len(request.Tools) > 0 {
tools, err := convertAnthropicTools(request.Tools)
if err != nil {
return nil, ResponseOptions{}, err
}
target["tools"] = tools
}
if len(request.MCPServers) > 0 {
servers, err := convertAnthropicMCPServers(request.MCPServers)
if err != nil {
return nil, ResponseOptions{}, err
}
existing, _ := target["tools"].([]any)
target["tools"] = append(existing, servers...)
}
if request.ToolChoice != nil {
choice, parallel, err := convertAnthropicToolChoice(*request.ToolChoice)
if err != nil {
return nil, ResponseOptions{}, err
}
target["tool_choice"] = choice
target["parallel_tool_calls"] = parallel
}
converted, err := json.Marshal(target)
return converted, ResponseOptions{
AnthropicThinking: thinkingEnabled,
StopSequences: append([]string(nil), request.StopSequences...),
}, err
}
type anthropicRequest struct {
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
Messages []anthropicMessage `json:"messages"`
System json.RawMessage `json:"system"`
Stream bool `json:"stream"`
Temperature *float64 `json:"temperature"`
TopP *float64 `json:"top_p"`
StopSequences []string `json:"stop_sequences"`
Metadata map[string]any `json:"metadata"`
Thinking *struct {
Type string `json:"type"`
BudgetTokens int `json:"budget_tokens"`
} `json:"thinking"`
TopK json.RawMessage `json:"top_k"`
MCPServers []anthropicMCPServer `json:"mcp_servers"`
OutputConfig *struct {
Effort string `json:"effort"`
Format *struct {
Type string `json:"type"`
Schema map[string]any `json:"schema"`
} `json:"format"`
} `json:"output_config"`
Tools []map[string]json.RawMessage `json:"tools"`
ToolChoice *anthropicToolChoice `json:"tool_choice"`
}
type anthropicMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
}
type anthropicToolChoice struct {
Type string `json:"type"`
Name string `json:"name"`
DisableParallelToolUse bool `json:"disable_parallel_tool_use"`
}
func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[string]struct{}) ([]any, []string, error) {
input := make([]any, 0, len(messages))
instructions := make([]string, 0)
pendingCalls := make(map[string]struct{})
usedCalls := make(map[string]struct{})
for messageIndex, message := range messages {
role := strings.ToLower(strings.TrimSpace(message.Role))
if role == "system" || role == "developer" {
text, err := anthropicSystemText(message.Content)
if err != nil {
return nil, nil, fmt.Errorf("messages[%d] %s 内容无效: %w", messageIndex, role, err)
}
if text != "" {
instructions = append(instructions, text)
}
continue
}
if role != "user" && role != "assistant" {
return nil, nil, fmt.Errorf("Messages API 不支持 role=%q", message.Role)
}
if len(pendingCalls) > 0 && role != "user" {
return nil, nil, fmt.Errorf("messages[%d] 必须是包含 tool_result 的 user 消息", messageIndex)
}
var text string
if json.Unmarshal(message.Content, &text) == nil {
if len(pendingCalls) > 0 {
return nil, nil, fmt.Errorf("messages[%d] 必须返回全部待处理 tool_use", messageIndex)
}
input = append(input, map[string]any{"type": "message", "role": role, "content": text})
continue
}
var blocks []map[string]json.RawMessage
if json.Unmarshal(message.Content, &blocks) != nil {
return nil, nil, fmt.Errorf("messages[%d].content 必须是字符串或内容块数组", messageIndex)
}
hadPending := len(pendingCalls) > 0
regularBeforeResult := false
messageParts := make([]any, 0, len(blocks))
flushMessage := func() {
if len(messageParts) > 0 {
input = append(input, map[string]any{"type": "message", "role": role, "content": messageParts})
messageParts = nil
}
}
for blockIndex, block := range blocks {
path := fmt.Sprintf("messages[%d].content[%d]", messageIndex, blockIndex)
var typeName string
_ = json.Unmarshal(block["type"], &typeName)
switch typeName {
case "text":
regularBeforeResult = regularBeforeResult || len(pendingCalls) > 0
var value string
if json.Unmarshal(block["text"], &value) != nil {
return nil, nil, fmt.Errorf("%s.text 无效", path)
}
messageParts = append(messageParts, map[string]any{"type": "input_text", "text": value})
case "image":
regularBeforeResult = regularBeforeResult || len(pendingCalls) > 0
imageURL, err := anthropicImageURL(block["source"])
if err != nil {
return nil, nil, fmt.Errorf("%s: %w", path, err)
}
messageParts = append(messageParts, map[string]any{"type": "input_image", "image_url": imageURL})
case "document":
regularBeforeResult = regularBeforeResult || len(pendingCalls) > 0
document, err := anthropicDocument(block)
if err != nil {
return nil, nil, fmt.Errorf("%s: %w", path, err)
}
messageParts = append(messageParts, document)
case "tool_use":
if role != "assistant" {
return nil, nil, fmt.Errorf("%s tool_use 只允许出现在 assistant 消息", path)
}
flushMessage()
var value struct {
ID string `json:"id"`
Name string `json:"name"`
Input map[string]any `json:"input"`
}
if encoded, _ := json.Marshal(block); json.Unmarshal(encoded, &value) != nil || strings.TrimSpace(value.ID) == "" || strings.TrimSpace(value.Name) == "" || value.Input == nil {
return nil, nil, fmt.Errorf("%s 缺少有效 id、name 或 object input", path)
}
if _, exists := usedCalls[value.ID]; exists {
return nil, nil, fmt.Errorf("%s 包含重复 tool_use id %q", path, value.ID)
}
arguments, _ := json.Marshal(value.Input)
input = append(input, map[string]any{"type": "function_call", "call_id": value.ID, "name": value.Name, "arguments": string(arguments)})
pendingCalls[value.ID] = struct{}{}
usedCalls[value.ID] = struct{}{}
case "tool_result":
if role != "user" {
return nil, nil, fmt.Errorf("%s tool_result 只允许出现在 user 消息", path)
}
flushMessage()
var toolUseID string
_ = json.Unmarshal(block["tool_use_id"], &toolUseID)
if _, exists := pendingCalls[toolUseID]; strings.TrimSpace(toolUseID) == "" || !exists {
return nil, nil, fmt.Errorf("%s.tool_use_id %q 未匹配待处理 tool_use", path, toolUseID)
}
if regularBeforeResult {
return nil, nil, fmt.Errorf("%s tool_result 必须位于文本、图片或文档块之前", path)
}
output, err := anthropicToolResult(block["content"], declaredTools)
if err != nil {
return nil, nil, fmt.Errorf("%s.content: %w", path, err)
}
if raw := block["is_error"]; !isEmptyJSON(raw) {
var isError bool
if json.Unmarshal(raw, &isError) != nil {
return nil, nil, fmt.Errorf("%s.is_error 必须是布尔值", path)
}
if isError {
output = markAnthropicToolError(output)
}
}
input = append(input, map[string]any{"type": "function_call_output", "call_id": toolUseID, "output": output})
delete(pendingCalls, toolUseID)
case "thinking":
if role != "assistant" {
return nil, nil, fmt.Errorf("%s thinking 只允许出现在 assistant 消息", path)
}
flushMessage()
var thinking, signature string
_ = json.Unmarshal(block["thinking"], &thinking)
_ = json.Unmarshal(block["signature"], &signature)
item := map[string]any{"type": "reasoning", "summary": []any{map[string]any{"type": "summary_text", "text": thinking}}}
if signature != "" {
item["encrypted_content"] = signature
}
input = append(input, item)
case "redacted_thinking":
if role != "assistant" {
return nil, nil, fmt.Errorf("%s redacted_thinking 只允许出现在 assistant 消息", path)
}
flushMessage()
var data string
if json.Unmarshal(block["data"], &data) != nil || data == "" {
return nil, nil, fmt.Errorf("%s.data 无效", path)
}
input = append(input, map[string]any{"type": "reasoning", "encrypted_content": data})
default:
return nil, nil, fmt.Errorf("当前不支持 Anthropic content.type=%q", typeName)
}
}
flushMessage()
if hadPending && len(pendingCalls) > 0 {
return nil, nil, fmt.Errorf("messages[%d] 必须返回全部待处理 tool_use", messageIndex)
}
}
if len(pendingCalls) > 0 {
return nil, nil, errors.New("messages 必须为每个 tool_use 提供 tool_result")
}
return input, instructions, nil
}
func anthropicSystemText(raw json.RawMessage) (string, error) {
if isEmptyJSON(raw) {
return "", nil
}
var text string
if json.Unmarshal(raw, &text) == nil {
return text, nil
}
var blocks []struct {
Type string `json:"type"`
Text string `json:"text"`
}
if json.Unmarshal(raw, &blocks) != nil {
return "", errors.New("system 必须是字符串或 text block 数组")
}
parts := make([]string, 0, len(blocks))
for _, block := range blocks {
if block.Type != "text" {
return "", fmt.Errorf("system 不支持 type=%q", block.Type)
}
parts = append(parts, block.Text)
}
return strings.Join(parts, "\n\n"), nil
}
func anthropicImageURL(raw json.RawMessage) (string, error) {
var source struct {
Type string `json:"type"`
MediaType string `json:"media_type"`
Data string `json:"data"`
URL string `json:"url"`
}
if json.Unmarshal(raw, &source) != nil {
return "", errors.New("image.source 无效")
}
switch source.Type {
case "base64":
if source.MediaType == "" || source.Data == "" {
return "", errors.New("base64 image 缺少 media_type 或 data")
}
return "data:" + source.MediaType + ";base64," + source.Data, nil
case "url":
if strings.TrimSpace(source.URL) == "" {
return "", errors.New("url image 缺少 url")
}
return source.URL, nil
default:
return "", fmt.Errorf("不支持 image.source.type=%q", source.Type)
}
}
func anthropicDocument(block map[string]json.RawMessage) (map[string]any, error) {
var source struct {
Type string `json:"type"`
MediaType string `json:"media_type"`
Data string `json:"data"`
URL string `json:"url"`
}
if json.Unmarshal(block["source"], &source) != nil {
return nil, errors.New("document.source 无效")
}
var title string
_ = json.Unmarshal(block["title"], &title)
switch source.Type {
case "text":
if source.Data == "" {
return nil, errors.New("text document 缺少 data")
}
return map[string]any{"type": "input_text", "text": source.Data}, nil
case "url":
if strings.TrimSpace(source.URL) == "" {
return nil, errors.New("url document 缺少 url")
}
value := map[string]any{"type": "input_file", "file_url": source.URL}
if title != "" {
value["filename"] = title
}
return value, nil
case "base64":
if source.MediaType == "" || source.Data == "" {
return nil, errors.New("base64 document 缺少 media_type 或 data")
}
value := map[string]any{"type": "input_file", "file_data": "data:" + source.MediaType + ";base64," + source.Data}
if title != "" {
value["filename"] = title
}
return value, nil
default:
return nil, fmt.Errorf("不支持 document.source.type=%q", source.Type)
}
}
func anthropicToolResult(raw json.RawMessage, declaredTools map[string]struct{}) (any, error) {
if isEmptyJSON(raw) {
return "", nil
}
var text string
if json.Unmarshal(raw, &text) == nil {
return text, nil
}
var blocks []map[string]json.RawMessage
if json.Unmarshal(raw, &blocks) != nil {
return "", errors.New("tool_result.content 无效")
}
parts := make([]any, 0, len(blocks))
for _, block := range blocks {
var typeName string
_ = json.Unmarshal(block["type"], &typeName)
switch typeName {
case "text":
var value string
if json.Unmarshal(block["text"], &value) != nil {
return nil, errors.New("tool_result text 无效")
}
parts = append(parts, map[string]any{"type": "input_text", "text": value})
case "image":
imageURL, err := anthropicImageURL(block["source"])
if err != nil {
return nil, err
}
parts = append(parts, map[string]any{"type": "input_image", "image_url": imageURL})
case "document":
document, err := anthropicDocument(block)
if err != nil {
return nil, err
}
parts = append(parts, document)
case "tool_reference":
var toolName string
if json.Unmarshal(block["tool_name"], &toolName) != nil || strings.TrimSpace(toolName) == "" {
return nil, errors.New("tool_reference.tool_name 无效")
}
toolName = strings.TrimSpace(toolName)
if _, exists := declaredTools[toolName]; !exists {
return nil, fmt.Errorf("tool_reference 引用了未声明的工具 %q", toolName)
}
// Responses 没有 Anthropic tool_reference 内容块。Messages 请求中的全部
// 工具定义已发送给上游,因此用确定性的结果文本保留“搜索命中”语义。
parts = append(parts, map[string]any{
"type": "input_text",
"text": fmt.Sprintf("Tool search matched declared tool %q; its definition is available in this request.", toolName),
})
default:
return nil, fmt.Errorf("tool_result 暂不支持 type=%q", typeName)
}
}
return parts, nil
}
func anthropicDeclaredToolNames(tools []map[string]json.RawMessage) map[string]struct{} {
declared := make(map[string]struct{}, len(tools))
for _, tool := range tools {
var name string
_ = json.Unmarshal(tool["name"], &name)
if name = strings.TrimSpace(name); name != "" {
declared[name] = struct{}{}
}
}
return declared
}
func markAnthropicToolError(output any) any {
const prefix = "Tool execution failed: "
if text, ok := output.(string); ok {
return prefix + text
}
parts, _ := output.([]any)
return append([]any{map[string]any{"type": "input_text", "text": prefix}}, parts...)
}
func convertAnthropicTools(tools []map[string]json.RawMessage) ([]any, error) {
result := make([]any, 0, len(tools))
for index, tool := range tools {
var typeName string
_ = json.Unmarshal(tool["type"], &typeName)
if strings.HasPrefix(typeName, "web_search_") {
converted, err := convertAnthropicWebSearchTool(tool, index)
if err != nil {
return nil, err
}
result = append(result, converted)
continue
}
if typeName != "" && typeName != "custom" {
return nil, fmt.Errorf("当前不支持 Anthropic server tool type=%q", typeName)
}
var name, description string
_ = json.Unmarshal(tool["name"], &name)
_ = json.Unmarshal(tool["description"], &description)
if strings.TrimSpace(name) == "" {
return nil, errors.New("Anthropic tool 缺少 name")
}
var schema any = map[string]any{"type": "object", "properties": map[string]any{}}
if raw := tool["input_schema"]; !isEmptyJSON(raw) {
if json.Unmarshal(raw, &schema) != nil {
return nil, fmt.Errorf("tool %q 的 input_schema 无效", name)
}
}
converted := map[string]any{"type": "function", "name": name, "description": description, "parameters": schema}
var strict bool
if raw := tool["strict"]; !isEmptyJSON(raw) {
if json.Unmarshal(raw, &strict) != nil {
return nil, fmt.Errorf("tool %q 的 strict 必须是布尔值", name)
}
converted["strict"] = strict
}
result = append(result, converted)
}
return result, nil
}
func convertAnthropicWebSearchTool(tool map[string]json.RawMessage, index int) (map[string]any, error) {
converted := map[string]any{"type": "web_search"}
for key, raw := range tool {
switch key {
case "type", "name", "cache_control":
continue
case "max_uses", "allowed_domains", "blocked_domains", "user_location":
var value any
if json.Unmarshal(raw, &value) != nil {
return nil, fmt.Errorf("tools[%d].%s 无效", index, key)
}
if key == "allowed_domains" || key == "blocked_domains" {
domains, ok := value.([]any)
if !ok {
return nil, fmt.Errorf("tools[%d].%s 必须是字符串数组", index, key)
}
if len(domains) > 5 {
return nil, fmt.Errorf("tools[%d].%s 不能超过 5 个域名", index, key)
}
for domainIndex, domain := range domains {
if text, ok := domain.(string); !ok || strings.TrimSpace(text) == "" {
return nil, fmt.Errorf("tools[%d].%s[%d] 必须是非空字符串", index, key, domainIndex)
}
}
}
converted[key] = value
default:
return nil, fmt.Errorf("Grok Build 0.2.99 不支持 Anthropic web search 字段 tools[%d].%s", index, key)
}
}
return converted, nil
}
type anthropicMCPServer struct {
Name string `json:"name"`
URL string `json:"url"`
AuthorizationToken string `json:"authorization_token"`
}
func convertAnthropicMCPServers(servers []anthropicMCPServer) ([]any, error) {
result := make([]any, 0, len(servers))
for index, server := range servers {
name := strings.TrimSpace(server.Name)
url := strings.TrimSpace(server.URL)
if name == "" || url == "" {
return nil, fmt.Errorf("mcp_servers[%d] 缺少 name 或 url", index)
}
tool := map[string]any{"type": "mcp", "server_label": name, "server_url": url}
if server.AuthorizationToken != "" {
tool["authorization"] = server.AuthorizationToken
}
result = append(result, tool)
}
return result, nil
}
func anthropicThinkingEffort(budget int) string {
switch {
case budget > 0 && budget <= 2048:
return "low"
case budget > 10000:
return "high"
default:
return "medium"
}
}
func convertAnthropicToolChoice(choice anthropicToolChoice) (any, bool, error) {
parallel := !choice.DisableParallelToolUse
switch choice.Type {
case "auto", "none":
return choice.Type, parallel, nil
case "any":
return "required", parallel, nil
case "tool":
if strings.TrimSpace(choice.Name) == "" {
return nil, false, errors.New("tool_choice.tool 缺少 name")
}
return map[string]any{"type": "function", "name": choice.Name}, parallel, nil
default:
return nil, false, fmt.Errorf("不支持 tool_choice.type=%q", choice.Type)
}
}
@@ -0,0 +1,146 @@
package conversation
import (
"encoding/json"
"fmt"
"strings"
"time"
)
func messagesResponse(value parsedResponse, options ResponseOptions) map[string]any {
content := make([]any, 0, len(value.Calls))
if options.AnthropicThinking && (value.Reasoning != "" || value.Signature != "") {
if value.Reasoning == "" {
content = append(content, map[string]any{"type": "redacted_thinking", "data": value.Signature})
} else {
thinking := map[string]any{"type": "thinking", "thinking": value.Reasoning}
if value.Signature != "" {
thinking["signature"] = value.Signature
}
content = append(content, thinking)
}
}
if value.Text != "" || len(value.Calls) == 0 {
content = append(content, map[string]any{"type": "text", "text": value.Text})
}
for _, call := range value.Calls {
var input any = map[string]any{}
if json.Unmarshal([]byte(call.Arguments), &input) != nil {
input = map[string]any{}
}
content = append(content, map[string]any{"type": "tool_use", "id": anthropicToolUseID(call.CallID), "name": call.Name, "input": input})
}
stopReason := "end_turn"
if len(value.Calls) > 0 {
stopReason = "tool_use"
} else if value.StopSequence != "" {
stopReason = "stop_sequence"
} else if value.Status == "incomplete" {
stopReason = "max_tokens"
} else if value.Refusal != "" {
stopReason = "refusal"
}
return map[string]any{
"id": anthropicMessageID(value.ID), "type": "message", "role": "assistant",
"model": value.Model, "content": content, "stop_reason": stopReason, "stop_sequence": nullableAnthropicString(value.StopSequence),
"usage": anthropicUsage(value.Usage),
}
}
func applyAnthropicStopSequences(text string, sequences []string) (string, string) {
matchAt := -1
matched := ""
for _, sequence := range sequences {
if sequence == "" {
continue
}
if index := strings.Index(text, sequence); index >= 0 && (matchAt < 0 || index < matchAt) {
matchAt = index
matched = sequence
}
}
if matchAt < 0 {
return text, ""
}
return text[:matchAt], matched
}
func anthropicMessageID(value string) string {
if strings.HasPrefix(value, "msg_") {
return value
}
if strings.HasPrefix(value, "resp_") {
return "msg_" + strings.TrimPrefix(value, "resp_")
}
if value == "" {
return fmt.Sprintf("msg_%d", time.Now().UnixNano())
}
return "msg_" + value
}
func anthropicToolUseID(value string) string {
if strings.HasPrefix(value, "toolu_") {
return value
}
if value == "" {
return fmt.Sprintf("toolu_%d", time.Now().UnixNano())
}
return "toolu_" + value
}
func nullableAnthropicString(value string) any {
if value == "" {
return nil
}
return value
}
func anthropicUsage(value responseUsage) map[string]any {
return map[string]any{
"input_tokens": value.InputTokens, "output_tokens": value.OutputTokens,
"cache_creation_input_tokens": 0, "cache_read_input_tokens": value.InputTokensDetails.CachedTokens,
}
}
func anthropicErrorJSON(value any) []byte {
message := "Upstream request failed"
errorType := "api_error"
if object, ok := value.(map[string]any); ok {
if text, ok := object["message"].(string); ok && text != "" {
message = text
}
errorType = normalizeAnthropicErrorType(object)
} else if text, ok := value.(string); ok && strings.TrimSpace(text) != "" {
message = text
}
data, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": errorType, "message": message}})
return data
}
func normalizeAnthropicErrorType(object map[string]any) string {
for _, field := range []string{"type", "code"} {
value, _ := object[field].(string)
switch strings.ToLower(strings.TrimSpace(value)) {
case "invalid_request_error", "authentication_error", "billing_error", "permission_error",
"not_found_error", "rate_limit_error", "timeout_error", "overloaded_error", "api_error":
return strings.ToLower(strings.TrimSpace(value))
case "unsupported_parameter", "invalid_parameter", "bad_request", "invalid_request":
return "invalid_request_error"
case "unauthorized", "authentication_failed":
return "authentication_error"
case "forbidden":
return "permission_error"
case "not_found":
return "not_found_error"
case "rate_limit_exceeded", "too_many_requests":
return "rate_limit_error"
case "request_timeout", "timeout":
return "timeout_error"
case "service_unavailable", "overloaded":
return "overloaded_error"
case "server_error", "internal_error":
return "api_error"
}
}
return "api_error"
}
@@ -0,0 +1,264 @@
package conversation
import (
"sort"
"strings"
)
func (c *streamConverter) startMessages() error {
return c.writeEvent("message_start", map[string]any{
"type": "message_start", "message": map[string]any{
"id": anthropicMessageID(c.id), "type": "message", "role": "assistant",
"model": c.model, "content": []any{}, "stop_reason": nil, "stop_sequence": nil,
"usage": anthropicUsage(c.usage),
},
})
}
func (c *streamConverter) textDeltaMessages(delta string) error {
if !c.textStarted {
c.textStarted = true
c.textIndex = c.nextIndex
c.nextIndex++
if err := c.writeEvent("content_block_start", map[string]any{"type": "content_block_start", "index": c.textIndex, "content_block": map[string]any{"type": "text", "text": ""}}); err != nil {
return err
}
}
emit, matched := c.stopFilter.Push(delta)
if matched != "" {
c.stopSequence = matched
}
if emit == "" {
return nil
}
return c.writeEvent("content_block_delta", map[string]any{"type": "content_block_delta", "index": c.textIndex, "delta": map[string]any{"type": "text_delta", "text": emit}})
}
func (c *streamConverter) thinkingStart(itemID string) error {
if !c.options.AnthropicThinking || c.thinkingStarted {
return nil
}
if err := c.start(); err != nil {
return err
}
c.thinkingStarted = true
c.thinkingIndex = c.nextIndex
c.nextIndex++
c.thinkingItemID = itemID
return c.writeEvent("content_block_start", map[string]any{
"type": "content_block_start", "index": c.thinkingIndex,
"content_block": map[string]any{"type": "thinking", "thinking": ""},
})
}
func (c *streamConverter) thinkingDelta(delta string) error {
if c.operation != OperationMessages || !c.options.AnthropicThinking {
return nil
}
if err := c.thinkingStart(""); err != nil {
return err
}
return c.writeEvent("content_block_delta", map[string]any{
"type": "content_block_delta", "index": c.thinkingIndex,
"delta": map[string]any{"type": "thinking_delta", "thinking": delta},
})
}
func (c *streamConverter) thinkingDone(item responseItem) error {
if c.operation != OperationMessages || !c.options.AnthropicThinking || !c.thinkingStarted || c.thinkingClosed {
return nil
}
if item.Encrypted != "" {
if err := c.writeEvent("content_block_delta", map[string]any{
"type": "content_block_delta", "index": c.thinkingIndex,
"delta": map[string]any{"type": "signature_delta", "signature": item.Encrypted},
}); err != nil {
return err
}
}
c.thinkingClosed = true
return c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": c.thinkingIndex})
}
func (c *streamConverter) textDeltaWithoutFilter(delta string) error {
if delta == "" {
return nil
}
if !c.textStarted {
c.textStarted = true
c.textIndex = c.nextIndex
c.nextIndex++
if err := c.writeEvent("content_block_start", map[string]any{"type": "content_block_start", "index": c.textIndex, "content_block": map[string]any{"type": "text", "text": ""}}); err != nil {
return err
}
}
return c.writeEvent("content_block_delta", map[string]any{"type": "content_block_delta", "index": c.textIndex, "delta": map[string]any{"type": "text_delta", "text": delta}})
}
type anthropicStreamStopFilter struct {
sequences []string
pending string
matched string
}
func newAnthropicStreamStopFilter(sequences []string) *anthropicStreamStopFilter {
filtered := make([]string, 0, len(sequences))
for _, sequence := range sequences {
if sequence != "" {
filtered = append(filtered, sequence)
}
}
return &anthropicStreamStopFilter{sequences: filtered}
}
func (f *anthropicStreamStopFilter) Push(delta string) (string, string) {
if f == nil || len(f.sequences) == 0 {
return delta, ""
}
if f.matched != "" {
return "", f.matched
}
f.pending += delta
matchAt := -1
matched := ""
for _, sequence := range f.sequences {
if index := strings.Index(f.pending, sequence); index >= 0 && (matchAt < 0 || index < matchAt) {
matchAt = index
matched = sequence
}
}
if matchAt >= 0 {
emit := f.pending[:matchAt]
f.pending = ""
f.matched = matched
return emit, matched
}
hold := 0
for _, sequence := range f.sequences {
maxPrefix := min(len(sequence)-1, len(f.pending))
for size := maxPrefix; size > hold; size-- {
if strings.HasSuffix(f.pending, sequence[:size]) {
hold = size
break
}
}
}
emitAt := len(f.pending) - hold
emit := f.pending[:emitAt]
f.pending = f.pending[emitAt:]
return emit, ""
}
func (f *anthropicStreamStopFilter) Flush() string {
if f == nil || f.matched != "" {
return ""
}
value := f.pending
f.pending = ""
return value
}
func (c *streamConverter) toolStartMessages(item responseItem) error {
if err := c.start(); err != nil {
return err
}
tool := streamTool{Index: c.nextIndex, ID: anthropicToolUseID(item.CallID), Name: item.Name, Arguments: item.Arguments}
c.nextIndex++
c.tools[item.ID] = tool
return c.writeEvent("content_block_start", map[string]any{
"type": "content_block_start", "index": tool.Index,
"content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}},
})
}
func (c *streamConverter) toolDeltaMessages(itemID, delta string) error {
tool, ok := c.tools[itemID]
if !ok {
return nil
}
tool.SentArgs = true
c.tools[itemID] = tool
return c.writeEvent("content_block_delta", map[string]any{
"type": "content_block_delta", "index": tool.Index,
"delta": map[string]any{"type": "input_json_delta", "partial_json": delta},
})
}
func (c *streamConverter) toolArgumentsDoneMessages(itemID, arguments string) error {
tool, ok := c.tools[itemID]
if !ok || tool.Closed {
return nil
}
if !tool.SentArgs {
if arguments == "" {
arguments = tool.Arguments
}
if arguments != "" {
if err := c.writeEvent("content_block_delta", map[string]any{
"type": "content_block_delta", "index": tool.Index,
"delta": map[string]any{"type": "input_json_delta", "partial_json": arguments},
}); err != nil {
return err
}
tool.SentArgs = true
}
}
tool.Closed = true
c.tools[itemID] = tool
return c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": tool.Index})
}
func (c *streamConverter) doneMessages(status string) error {
if c.stopSequence == "" {
if pending := c.stopFilter.Flush(); pending != "" {
if err := c.textDeltaWithoutFilter(pending); err != nil {
return err
}
}
}
if c.thinkingStarted && !c.thinkingClosed {
c.thinkingClosed = true
if err := c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": c.thinkingIndex}); err != nil {
return err
}
}
if c.textStarted {
if err := c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": c.textIndex}); err != nil {
return err
}
}
openTools := make([]streamTool, 0)
for itemID, tool := range c.tools {
if !tool.Closed {
tool.Closed = true
c.tools[itemID] = tool
openTools = append(openTools, tool)
}
}
sort.Slice(openTools, func(i, j int) bool { return openTools[i].Index < openTools[j].Index })
for _, tool := range openTools {
if err := c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": tool.Index}); err != nil {
return err
}
}
stopReason := "end_turn"
if len(c.tools) > 0 {
stopReason = "tool_use"
} else if c.stopSequence != "" {
stopReason = "stop_sequence"
} else if status == "incomplete" {
stopReason = "max_tokens"
}
if err := c.writeEvent("message_delta", map[string]any{
"type": "message_delta", "delta": map[string]any{"stop_reason": stopReason, "stop_sequence": nullableAnthropicString(c.stopSequence)},
"usage": map[string]any{"input_tokens": c.usage.InputTokens, "output_tokens": c.usage.OutputTokens},
}); err != nil {
return err
}
c.finished = true
return c.writeEvent("message_stop", map[string]any{"type": "message_stop"})
}
func (c *streamConverter) streamErrorMessages(data []byte) error {
return c.writeEvent("error", map[string]any{"type": "error", "error": map[string]any{"type": "api_error", "message": string(data)}})
}
@@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"strings"
)
const (
@@ -43,816 +42,6 @@ func replaceModel(body []byte, model string) ([]byte, error) {
return json.Marshal(payload)
}
func convertChatRequest(body []byte, model string) ([]byte, error) {
var source map[string]json.RawMessage
if err := json.Unmarshal(body, &source); err != nil {
return nil, fmt.Errorf("解析 Chat Completions 请求: %w", err)
}
var messages []chatMessage
if err := json.Unmarshal(source["messages"], &messages); err != nil || len(messages) == 0 {
return nil, errors.New("messages 必须是非空数组")
}
input, err := convertChatMessages(messages)
if err != nil {
return nil, err
}
target := map[string]json.RawMessage{"model": mustJSON(model), "input": mustJSON(input)}
copyFields(target, source, "stream", "temperature", "top_p", "presence_penalty", "frequency_penalty", "seed", "user", "parallel_tool_calls", "metadata", "store", "service_tier", "stop")
if raw := firstJSON(source["max_completion_tokens"], source["max_tokens"]); !isEmptyJSON(raw) {
target["max_output_tokens"] = raw
}
if raw := source["response_format"]; !isEmptyJSON(raw) {
format, err := convertResponseFormat(raw)
if err != nil {
return nil, err
}
target["text"] = mustJSON(map[string]json.RawMessage{"format": format})
}
if raw := source["reasoning_effort"]; !isEmptyJSON(raw) {
target["reasoning"] = mustJSON(map[string]json.RawMessage{"effort": raw})
}
if raw := source["tools"]; !isEmptyJSON(raw) {
tools, err := convertChatTools(raw)
if err != nil {
return nil, err
}
target["tools"] = mustJSON(tools)
}
if raw := source["tool_choice"]; !isEmptyJSON(raw) {
choice, err := convertChatToolChoice(raw)
if err != nil {
return nil, err
}
target["tool_choice"] = choice
}
return json.Marshal(target)
}
type chatMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
ToolCalls json.RawMessage `json:"tool_calls"`
ToolCallID string `json:"tool_call_id"`
Name string `json:"name"`
}
func convertChatMessages(messages []chatMessage) ([]any, error) {
input := make([]any, 0, len(messages))
for _, message := range messages {
role := strings.ToLower(strings.TrimSpace(message.Role))
switch role {
case "system", "developer", "user", "assistant":
if !isEmptyJSON(message.Content) && !bytes.Equal(bytes.TrimSpace(message.Content), []byte("null")) {
content, err := convertChatContent(message.Content)
if err != nil {
return nil, fmt.Errorf("%s 消息内容无效: %w", role, err)
}
input = append(input, map[string]any{"type": "message", "role": role, "content": content})
}
if role == "assistant" && !isEmptyJSON(message.ToolCalls) {
calls, err := convertAssistantToolCalls(message.ToolCalls)
if err != nil {
return nil, err
}
input = append(input, calls...)
}
case "tool":
if strings.TrimSpace(message.ToolCallID) == "" {
return nil, errors.New("tool 消息缺少 tool_call_id")
}
output, err := contentAsText(message.Content)
if err != nil {
return nil, err
}
input = append(input, map[string]any{"type": "function_call_output", "call_id": message.ToolCallID, "output": output})
default:
return nil, fmt.Errorf("不支持 messages.role=%q", message.Role)
}
}
if len(input) == 0 {
return nil, errors.New("messages 中没有可发送内容")
}
return input, nil
}
func convertChatContent(raw json.RawMessage) (any, error) {
var text string
if json.Unmarshal(raw, &text) == nil {
return text, nil
}
var parts []map[string]json.RawMessage
if err := json.Unmarshal(raw, &parts); err != nil {
return nil, errors.New("content 必须是字符串或内容数组")
}
result := make([]any, 0, len(parts))
for _, part := range parts {
var typeName string
_ = json.Unmarshal(part["type"], &typeName)
switch typeName {
case "text", "input_text", "output_text":
var value string
if json.Unmarshal(part["text"], &value) != nil {
return nil, errors.New("text 内容无效")
}
result = append(result, map[string]any{"type": "input_text", "text": value})
case "image_url", "input_image":
imageURL, err := parseImageURL(part)
if err != nil {
return nil, err
}
result = append(result, map[string]any{"type": "input_image", "image_url": imageURL})
default:
return nil, fmt.Errorf("不支持 content.type=%q", typeName)
}
}
return result, nil
}
func parseImageURL(part map[string]json.RawMessage) (string, error) {
raw := firstJSON(part["image_url"], part["url"])
var value string
if json.Unmarshal(raw, &value) == nil && strings.TrimSpace(value) != "" {
return value, nil
}
var nested struct {
URL string `json:"url"`
}
if json.Unmarshal(raw, &nested) == nil && strings.TrimSpace(nested.URL) != "" {
return nested.URL, nil
}
return "", errors.New("image_url 缺少有效 url")
}
func convertAssistantToolCalls(raw json.RawMessage) ([]any, error) {
var calls []struct {
ID string `json:"id"`
Type string `json:"type"`
Function struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
} `json:"function"`
}
if err := json.Unmarshal(raw, &calls); err != nil {
return nil, errors.New("assistant.tool_calls 格式无效")
}
result := make([]any, 0, len(calls))
for _, call := range calls {
if strings.TrimSpace(call.ID) == "" || strings.TrimSpace(call.Function.Name) == "" || !json.Valid([]byte(call.Function.Arguments)) {
return nil, errors.New("assistant.tool_calls 缺少有效 id、name 或 arguments")
}
result = append(result, map[string]any{"type": "function_call", "call_id": call.ID, "name": call.Function.Name, "arguments": call.Function.Arguments})
}
return result, nil
}
func convertChatTools(raw json.RawMessage) ([]any, error) {
var tools []map[string]json.RawMessage
if err := json.Unmarshal(raw, &tools); err != nil {
return nil, errors.New("tools 必须是数组")
}
result := make([]any, 0, len(tools))
for _, tool := range tools {
var typeName string
_ = json.Unmarshal(tool["type"], &typeName)
if typeName != "function" {
var value any
_ = json.Unmarshal(mustJSON(tool), &value)
result = append(result, value)
continue
}
var function map[string]any
if json.Unmarshal(tool["function"], &function) != nil {
return nil, errors.New("function tool 格式无效")
}
function["type"] = "function"
result = append(result, function)
}
return result, nil
}
func convertChatToolChoice(raw json.RawMessage) (json.RawMessage, error) {
var value map[string]json.RawMessage
if json.Unmarshal(raw, &value) != nil {
return raw, nil
}
var typeName string
_ = json.Unmarshal(value["type"], &typeName)
if typeName != "function" {
return raw, nil
}
var function struct {
Name string `json:"name"`
}
if json.Unmarshal(value["function"], &function) != nil || strings.TrimSpace(function.Name) == "" {
return nil, errors.New("tool_choice.function.name 无效")
}
return mustJSON(map[string]any{"type": "function", "name": function.Name}), nil
}
func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, error) {
var request anthropicRequest
if err := json.Unmarshal(body, &request); err != nil {
return nil, ResponseOptions{}, fmt.Errorf("解析 Messages 请求: %w", err)
}
if len(request.Messages) == 0 {
return nil, ResponseOptions{}, errors.New("messages 必须是非空数组")
}
if request.MaxTokens <= 0 {
return nil, ResponseOptions{}, errors.New("max_tokens 必须是正整数")
}
for name, value := range map[string]*float64{"temperature": request.Temperature, "top_p": request.TopP} {
if value != nil && (*value < 0 || *value > 1) {
return nil, ResponseOptions{}, fmt.Errorf("%s 必须在 0 到 1 之间", name)
}
}
for index, sequence := range request.StopSequences {
if sequence == "" {
return nil, ResponseOptions{}, fmt.Errorf("stop_sequences[%d] 不能为空", index)
}
}
if !isEmptyJSON(request.TopK) {
return nil, ResponseOptions{}, errors.New("Messages top_k 无法等价映射到 Responses API")
}
thinkingEnabled := false
if request.Thinking != nil {
switch request.Thinking.Type {
case "", "disabled":
case "enabled", "adaptive":
thinkingEnabled = true
default:
return nil, ResponseOptions{}, fmt.Errorf("不支持 thinking.type=%q", request.Thinking.Type)
}
}
input, inlineInstructions, err := convertAnthropicMessages(request.Messages, anthropicDeclaredToolNames(request.Tools))
if err != nil {
return nil, ResponseOptions{}, err
}
if len(input) == 0 {
return nil, ResponseOptions{}, errors.New("messages 中没有可发送的 user 或 assistant 内容")
}
target := map[string]any{
"model": model, "input": input, "stream": request.Stream,
"max_output_tokens": request.MaxTokens, "store": false,
}
instructions := make([]string, 0, len(inlineInstructions))
if system, err := anthropicSystemText(request.System); err != nil {
return nil, ResponseOptions{}, err
} else if system != "" {
instructions = append(instructions, system)
}
instructions = append(instructions, inlineInstructions...)
if len(instructions) > 0 {
target["instructions"] = strings.Join(instructions, "\n\n")
}
copyOptionalNumber(target, "temperature", request.Temperature)
copyOptionalNumber(target, "top_p", request.TopP)
if request.Metadata != nil {
if userID, _ := request.Metadata["user_id"].(string); strings.TrimSpace(userID) != "" {
target["safety_identifier"] = strings.TrimSpace(userID)
}
}
if request.OutputConfig != nil && request.OutputConfig.Format != nil {
if request.OutputConfig.Format.Type != "json_schema" || request.OutputConfig.Format.Schema == nil {
return nil, ResponseOptions{}, errors.New("output_config.format 必须是带 schema 的 json_schema")
}
target["text"] = map[string]any{"format": map[string]any{"type": "json_schema", "name": "anthropic_output", "schema": request.OutputConfig.Format.Schema}}
}
if thinkingEnabled {
effort := anthropicThinkingEffort(request.Thinking.BudgetTokens)
if request.OutputConfig != nil && request.OutputConfig.Effort != "" {
effort = request.OutputConfig.Effort
}
switch effort {
case "minimal":
effort = "low"
case "max", "xhigh":
effort = "high"
case "low", "medium", "high":
default:
return nil, ResponseOptions{}, fmt.Errorf("不支持 output_config.effort=%q", effort)
}
target["reasoning"] = map[string]any{"effort": effort, "summary": "detailed"}
target["include"] = []any{"reasoning.encrypted_content"}
}
if len(request.Tools) > 0 {
tools, err := convertAnthropicTools(request.Tools)
if err != nil {
return nil, ResponseOptions{}, err
}
target["tools"] = tools
}
if len(request.MCPServers) > 0 {
servers, err := convertAnthropicMCPServers(request.MCPServers)
if err != nil {
return nil, ResponseOptions{}, err
}
existing, _ := target["tools"].([]any)
target["tools"] = append(existing, servers...)
}
if request.ToolChoice != nil {
choice, parallel, err := convertAnthropicToolChoice(*request.ToolChoice)
if err != nil {
return nil, ResponseOptions{}, err
}
target["tool_choice"] = choice
target["parallel_tool_calls"] = parallel
}
converted, err := json.Marshal(target)
return converted, ResponseOptions{
AnthropicThinking: thinkingEnabled,
StopSequences: append([]string(nil), request.StopSequences...),
}, err
}
type anthropicRequest struct {
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
Messages []anthropicMessage `json:"messages"`
System json.RawMessage `json:"system"`
Stream bool `json:"stream"`
Temperature *float64 `json:"temperature"`
TopP *float64 `json:"top_p"`
StopSequences []string `json:"stop_sequences"`
Metadata map[string]any `json:"metadata"`
Thinking *struct {
Type string `json:"type"`
BudgetTokens int `json:"budget_tokens"`
} `json:"thinking"`
TopK json.RawMessage `json:"top_k"`
MCPServers []anthropicMCPServer `json:"mcp_servers"`
OutputConfig *struct {
Effort string `json:"effort"`
Format *struct {
Type string `json:"type"`
Schema map[string]any `json:"schema"`
} `json:"format"`
} `json:"output_config"`
Tools []map[string]json.RawMessage `json:"tools"`
ToolChoice *anthropicToolChoice `json:"tool_choice"`
}
type anthropicMessage struct {
Role string `json:"role"`
Content json.RawMessage `json:"content"`
}
type anthropicToolChoice struct {
Type string `json:"type"`
Name string `json:"name"`
DisableParallelToolUse bool `json:"disable_parallel_tool_use"`
}
func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[string]struct{}) ([]any, []string, error) {
input := make([]any, 0, len(messages))
instructions := make([]string, 0)
pendingCalls := make(map[string]struct{})
usedCalls := make(map[string]struct{})
for messageIndex, message := range messages {
role := strings.ToLower(strings.TrimSpace(message.Role))
if role == "system" || role == "developer" {
text, err := anthropicSystemText(message.Content)
if err != nil {
return nil, nil, fmt.Errorf("messages[%d] %s 内容无效: %w", messageIndex, role, err)
}
if text != "" {
instructions = append(instructions, text)
}
continue
}
if role != "user" && role != "assistant" {
return nil, nil, fmt.Errorf("Messages API 不支持 role=%q", message.Role)
}
if len(pendingCalls) > 0 && role != "user" {
return nil, nil, fmt.Errorf("messages[%d] 必须是包含 tool_result 的 user 消息", messageIndex)
}
var text string
if json.Unmarshal(message.Content, &text) == nil {
if len(pendingCalls) > 0 {
return nil, nil, fmt.Errorf("messages[%d] 必须返回全部待处理 tool_use", messageIndex)
}
input = append(input, map[string]any{"type": "message", "role": role, "content": text})
continue
}
var blocks []map[string]json.RawMessage
if json.Unmarshal(message.Content, &blocks) != nil {
return nil, nil, fmt.Errorf("messages[%d].content 必须是字符串或内容块数组", messageIndex)
}
hadPending := len(pendingCalls) > 0
regularBeforeResult := false
messageParts := make([]any, 0, len(blocks))
flushMessage := func() {
if len(messageParts) > 0 {
input = append(input, map[string]any{"type": "message", "role": role, "content": messageParts})
messageParts = nil
}
}
for blockIndex, block := range blocks {
path := fmt.Sprintf("messages[%d].content[%d]", messageIndex, blockIndex)
var typeName string
_ = json.Unmarshal(block["type"], &typeName)
switch typeName {
case "text":
regularBeforeResult = regularBeforeResult || len(pendingCalls) > 0
var value string
if json.Unmarshal(block["text"], &value) != nil {
return nil, nil, fmt.Errorf("%s.text 无效", path)
}
messageParts = append(messageParts, map[string]any{"type": "input_text", "text": value})
case "image":
regularBeforeResult = regularBeforeResult || len(pendingCalls) > 0
imageURL, err := anthropicImageURL(block["source"])
if err != nil {
return nil, nil, fmt.Errorf("%s: %w", path, err)
}
messageParts = append(messageParts, map[string]any{"type": "input_image", "image_url": imageURL})
case "document":
regularBeforeResult = regularBeforeResult || len(pendingCalls) > 0
document, err := anthropicDocument(block)
if err != nil {
return nil, nil, fmt.Errorf("%s: %w", path, err)
}
messageParts = append(messageParts, document)
case "tool_use":
if role != "assistant" {
return nil, nil, fmt.Errorf("%s tool_use 只允许出现在 assistant 消息", path)
}
flushMessage()
var value struct {
ID string `json:"id"`
Name string `json:"name"`
Input map[string]any `json:"input"`
}
if encoded, _ := json.Marshal(block); json.Unmarshal(encoded, &value) != nil || strings.TrimSpace(value.ID) == "" || strings.TrimSpace(value.Name) == "" || value.Input == nil {
return nil, nil, fmt.Errorf("%s 缺少有效 id、name 或 object input", path)
}
if _, exists := usedCalls[value.ID]; exists {
return nil, nil, fmt.Errorf("%s 包含重复 tool_use id %q", path, value.ID)
}
arguments, _ := json.Marshal(value.Input)
input = append(input, map[string]any{"type": "function_call", "call_id": value.ID, "name": value.Name, "arguments": string(arguments)})
pendingCalls[value.ID] = struct{}{}
usedCalls[value.ID] = struct{}{}
case "tool_result":
if role != "user" {
return nil, nil, fmt.Errorf("%s tool_result 只允许出现在 user 消息", path)
}
flushMessage()
var toolUseID string
_ = json.Unmarshal(block["tool_use_id"], &toolUseID)
if _, exists := pendingCalls[toolUseID]; strings.TrimSpace(toolUseID) == "" || !exists {
return nil, nil, fmt.Errorf("%s.tool_use_id %q 未匹配待处理 tool_use", path, toolUseID)
}
if regularBeforeResult {
return nil, nil, fmt.Errorf("%s tool_result 必须位于文本、图片或文档块之前", path)
}
output, err := anthropicToolResult(block["content"], declaredTools)
if err != nil {
return nil, nil, fmt.Errorf("%s.content: %w", path, err)
}
if raw := block["is_error"]; !isEmptyJSON(raw) {
var isError bool
if json.Unmarshal(raw, &isError) != nil {
return nil, nil, fmt.Errorf("%s.is_error 必须是布尔值", path)
}
if isError {
output = markAnthropicToolError(output)
}
}
input = append(input, map[string]any{"type": "function_call_output", "call_id": toolUseID, "output": output})
delete(pendingCalls, toolUseID)
case "thinking":
if role != "assistant" {
return nil, nil, fmt.Errorf("%s thinking 只允许出现在 assistant 消息", path)
}
flushMessage()
var thinking, signature string
_ = json.Unmarshal(block["thinking"], &thinking)
_ = json.Unmarshal(block["signature"], &signature)
item := map[string]any{"type": "reasoning", "summary": []any{map[string]any{"type": "summary_text", "text": thinking}}}
if signature != "" {
item["encrypted_content"] = signature
}
input = append(input, item)
case "redacted_thinking":
if role != "assistant" {
return nil, nil, fmt.Errorf("%s redacted_thinking 只允许出现在 assistant 消息", path)
}
flushMessage()
var data string
if json.Unmarshal(block["data"], &data) != nil || data == "" {
return nil, nil, fmt.Errorf("%s.data 无效", path)
}
input = append(input, map[string]any{"type": "reasoning", "encrypted_content": data})
default:
return nil, nil, fmt.Errorf("当前不支持 Anthropic content.type=%q", typeName)
}
}
flushMessage()
if hadPending && len(pendingCalls) > 0 {
return nil, nil, fmt.Errorf("messages[%d] 必须返回全部待处理 tool_use", messageIndex)
}
}
if len(pendingCalls) > 0 {
return nil, nil, errors.New("messages 必须为每个 tool_use 提供 tool_result")
}
return input, instructions, nil
}
func anthropicSystemText(raw json.RawMessage) (string, error) {
if isEmptyJSON(raw) {
return "", nil
}
var text string
if json.Unmarshal(raw, &text) == nil {
return text, nil
}
var blocks []struct {
Type string `json:"type"`
Text string `json:"text"`
}
if json.Unmarshal(raw, &blocks) != nil {
return "", errors.New("system 必须是字符串或 text block 数组")
}
parts := make([]string, 0, len(blocks))
for _, block := range blocks {
if block.Type != "text" {
return "", fmt.Errorf("system 不支持 type=%q", block.Type)
}
parts = append(parts, block.Text)
}
return strings.Join(parts, "\n\n"), nil
}
func anthropicImageURL(raw json.RawMessage) (string, error) {
var source struct {
Type string `json:"type"`
MediaType string `json:"media_type"`
Data string `json:"data"`
URL string `json:"url"`
}
if json.Unmarshal(raw, &source) != nil {
return "", errors.New("image.source 无效")
}
switch source.Type {
case "base64":
if source.MediaType == "" || source.Data == "" {
return "", errors.New("base64 image 缺少 media_type 或 data")
}
return "data:" + source.MediaType + ";base64," + source.Data, nil
case "url":
if strings.TrimSpace(source.URL) == "" {
return "", errors.New("url image 缺少 url")
}
return source.URL, nil
default:
return "", fmt.Errorf("不支持 image.source.type=%q", source.Type)
}
}
func anthropicDocument(block map[string]json.RawMessage) (map[string]any, error) {
var source struct {
Type string `json:"type"`
MediaType string `json:"media_type"`
Data string `json:"data"`
URL string `json:"url"`
}
if json.Unmarshal(block["source"], &source) != nil {
return nil, errors.New("document.source 无效")
}
var title string
_ = json.Unmarshal(block["title"], &title)
switch source.Type {
case "text":
if source.Data == "" {
return nil, errors.New("text document 缺少 data")
}
return map[string]any{"type": "input_text", "text": source.Data}, nil
case "url":
if strings.TrimSpace(source.URL) == "" {
return nil, errors.New("url document 缺少 url")
}
value := map[string]any{"type": "input_file", "file_url": source.URL}
if title != "" {
value["filename"] = title
}
return value, nil
case "base64":
if source.MediaType == "" || source.Data == "" {
return nil, errors.New("base64 document 缺少 media_type 或 data")
}
value := map[string]any{"type": "input_file", "file_data": "data:" + source.MediaType + ";base64," + source.Data}
if title != "" {
value["filename"] = title
}
return value, nil
default:
return nil, fmt.Errorf("不支持 document.source.type=%q", source.Type)
}
}
func anthropicToolResult(raw json.RawMessage, declaredTools map[string]struct{}) (any, error) {
if isEmptyJSON(raw) {
return "", nil
}
var text string
if json.Unmarshal(raw, &text) == nil {
return text, nil
}
var blocks []map[string]json.RawMessage
if json.Unmarshal(raw, &blocks) != nil {
return "", errors.New("tool_result.content 无效")
}
parts := make([]any, 0, len(blocks))
for _, block := range blocks {
var typeName string
_ = json.Unmarshal(block["type"], &typeName)
switch typeName {
case "text":
var value string
if json.Unmarshal(block["text"], &value) != nil {
return nil, errors.New("tool_result text 无效")
}
parts = append(parts, map[string]any{"type": "input_text", "text": value})
case "image":
imageURL, err := anthropicImageURL(block["source"])
if err != nil {
return nil, err
}
parts = append(parts, map[string]any{"type": "input_image", "image_url": imageURL})
case "document":
document, err := anthropicDocument(block)
if err != nil {
return nil, err
}
parts = append(parts, document)
case "tool_reference":
var toolName string
if json.Unmarshal(block["tool_name"], &toolName) != nil || strings.TrimSpace(toolName) == "" {
return nil, errors.New("tool_reference.tool_name 无效")
}
toolName = strings.TrimSpace(toolName)
if _, exists := declaredTools[toolName]; !exists {
return nil, fmt.Errorf("tool_reference 引用了未声明的工具 %q", toolName)
}
// Responses 没有 Anthropic tool_reference 内容块。Messages 请求中的全部
// 工具定义已发送给上游,因此用确定性的结果文本保留“搜索命中”语义。
parts = append(parts, map[string]any{
"type": "input_text",
"text": fmt.Sprintf("Tool search matched declared tool %q; its definition is available in this request.", toolName),
})
default:
return nil, fmt.Errorf("tool_result 暂不支持 type=%q", typeName)
}
}
return parts, nil
}
func anthropicDeclaredToolNames(tools []map[string]json.RawMessage) map[string]struct{} {
declared := make(map[string]struct{}, len(tools))
for _, tool := range tools {
var name string
_ = json.Unmarshal(tool["name"], &name)
if name = strings.TrimSpace(name); name != "" {
declared[name] = struct{}{}
}
}
return declared
}
func markAnthropicToolError(output any) any {
const prefix = "Tool execution failed: "
if text, ok := output.(string); ok {
return prefix + text
}
parts, _ := output.([]any)
return append([]any{map[string]any{"type": "input_text", "text": prefix}}, parts...)
}
func convertAnthropicTools(tools []map[string]json.RawMessage) ([]any, error) {
result := make([]any, 0, len(tools))
for index, tool := range tools {
var typeName string
_ = json.Unmarshal(tool["type"], &typeName)
if strings.HasPrefix(typeName, "web_search_") {
converted, err := convertAnthropicWebSearchTool(tool, index)
if err != nil {
return nil, err
}
result = append(result, converted)
continue
}
if typeName != "" && typeName != "custom" {
return nil, fmt.Errorf("当前不支持 Anthropic server tool type=%q", typeName)
}
var name, description string
_ = json.Unmarshal(tool["name"], &name)
_ = json.Unmarshal(tool["description"], &description)
if strings.TrimSpace(name) == "" {
return nil, errors.New("Anthropic tool 缺少 name")
}
var schema any = map[string]any{"type": "object", "properties": map[string]any{}}
if raw := tool["input_schema"]; !isEmptyJSON(raw) {
if json.Unmarshal(raw, &schema) != nil {
return nil, fmt.Errorf("tool %q 的 input_schema 无效", name)
}
}
converted := map[string]any{"type": "function", "name": name, "description": description, "parameters": schema}
var strict bool
if raw := tool["strict"]; !isEmptyJSON(raw) {
if json.Unmarshal(raw, &strict) != nil {
return nil, fmt.Errorf("tool %q 的 strict 必须是布尔值", name)
}
converted["strict"] = strict
}
result = append(result, converted)
}
return result, nil
}
func convertAnthropicWebSearchTool(tool map[string]json.RawMessage, index int) (map[string]any, error) {
converted := map[string]any{"type": "web_search"}
for key, raw := range tool {
switch key {
case "type", "name", "cache_control":
continue
case "max_uses", "allowed_domains", "blocked_domains", "user_location":
var value any
if json.Unmarshal(raw, &value) != nil {
return nil, fmt.Errorf("tools[%d].%s 无效", index, key)
}
if key == "allowed_domains" || key == "blocked_domains" {
domains, ok := value.([]any)
if !ok {
return nil, fmt.Errorf("tools[%d].%s 必须是字符串数组", index, key)
}
if len(domains) > 5 {
return nil, fmt.Errorf("tools[%d].%s 不能超过 5 个域名", index, key)
}
for domainIndex, domain := range domains {
if text, ok := domain.(string); !ok || strings.TrimSpace(text) == "" {
return nil, fmt.Errorf("tools[%d].%s[%d] 必须是非空字符串", index, key, domainIndex)
}
}
}
converted[key] = value
default:
return nil, fmt.Errorf("Grok Build 0.2.99 不支持 Anthropic web search 字段 tools[%d].%s", index, key)
}
}
return converted, nil
}
type anthropicMCPServer struct {
Name string `json:"name"`
URL string `json:"url"`
AuthorizationToken string `json:"authorization_token"`
}
func convertAnthropicMCPServers(servers []anthropicMCPServer) ([]any, error) {
result := make([]any, 0, len(servers))
for index, server := range servers {
name := strings.TrimSpace(server.Name)
url := strings.TrimSpace(server.URL)
if name == "" || url == "" {
return nil, fmt.Errorf("mcp_servers[%d] 缺少 name 或 url", index)
}
tool := map[string]any{"type": "mcp", "server_label": name, "server_url": url}
if server.AuthorizationToken != "" {
tool["authorization"] = server.AuthorizationToken
}
result = append(result, tool)
}
return result, nil
}
func anthropicThinkingEffort(budget int) string {
switch {
case budget > 0 && budget <= 2048:
return "low"
case budget > 10000:
return "high"
default:
return "medium"
}
}
func convertAnthropicToolChoice(choice anthropicToolChoice) (any, bool, error) {
parallel := !choice.DisableParallelToolUse
switch choice.Type {
case "auto", "none":
return choice.Type, parallel, nil
case "any":
return "required", parallel, nil
case "tool":
if strings.TrimSpace(choice.Name) == "" {
return nil, false, errors.New("tool_choice.tool 缺少 name")
}
return map[string]any{"type": "function", "name": choice.Name}, parallel, nil
default:
return nil, false, fmt.Errorf("不支持 tool_choice.type=%q", choice.Type)
}
}
func convertResponseFormat(raw json.RawMessage) (json.RawMessage, error) {
var format map[string]json.RawMessage
if json.Unmarshal(raw, &format) != nil {
@@ -3,7 +3,6 @@ package conversation
import (
"encoding/json"
"fmt"
"strings"
"time"
)
@@ -130,183 +129,3 @@ func parseResponse(value responseEnvelope) parsedResponse {
}
return parsed
}
func chatResponse(value parsedResponse) map[string]any {
message := map[string]any{"role": "assistant", "content": value.Text}
if value.Reasoning != "" {
message["reasoning_content"] = value.Reasoning
}
finishReason := "stop"
if len(value.Calls) > 0 {
finishReason = "tool_calls"
if value.Text == "" {
message["content"] = nil
}
calls := make([]any, 0, len(value.Calls))
for _, call := range value.Calls {
calls = append(calls, map[string]any{
"id": call.CallID, "type": "function",
"function": map[string]any{"name": call.Name, "arguments": call.Arguments},
})
}
message["tool_calls"] = calls
} else if value.Status == "incomplete" {
finishReason = "length"
}
if value.Refusal != "" {
message["refusal"] = value.Refusal
}
id := strings.Replace(value.ID, "resp_", "chatcmpl_", 1)
return map[string]any{
"id": id, "object": "chat.completion", "created": value.CreatedAt, "model": value.Model,
"choices": []any{map[string]any{"index": 0, "message": message, "finish_reason": finishReason}},
"usage": chatUsage(value.Usage),
}
}
func messagesResponse(value parsedResponse, options ResponseOptions) map[string]any {
content := make([]any, 0, len(value.Calls)+2)
if options.AnthropicThinking && (value.Reasoning != "" || value.Signature != "") {
if value.Reasoning == "" {
content = append(content, map[string]any{"type": "redacted_thinking", "data": value.Signature})
} else {
thinking := map[string]any{"type": "thinking", "thinking": value.Reasoning}
if value.Signature != "" {
thinking["signature"] = value.Signature
}
content = append(content, thinking)
}
}
if value.Text != "" || len(value.Calls) == 0 {
content = append(content, map[string]any{"type": "text", "text": value.Text})
}
for _, call := range value.Calls {
var input any = map[string]any{}
if json.Unmarshal([]byte(call.Arguments), &input) != nil {
input = map[string]any{}
}
content = append(content, map[string]any{"type": "tool_use", "id": anthropicToolUseID(call.CallID), "name": call.Name, "input": input})
}
stopReason := "end_turn"
if len(value.Calls) > 0 {
stopReason = "tool_use"
} else if value.StopSequence != "" {
stopReason = "stop_sequence"
} else if value.Status == "incomplete" {
stopReason = "max_tokens"
} else if value.Refusal != "" {
stopReason = "refusal"
}
return map[string]any{
"id": anthropicMessageID(value.ID), "type": "message", "role": "assistant",
"model": value.Model, "content": content, "stop_reason": stopReason, "stop_sequence": nullableAnthropicString(value.StopSequence),
"usage": anthropicUsage(value.Usage),
}
}
func applyAnthropicStopSequences(text string, sequences []string) (string, string) {
matchAt := -1
matched := ""
for _, sequence := range sequences {
if sequence == "" {
continue
}
if index := strings.Index(text, sequence); index >= 0 && (matchAt < 0 || index < matchAt) {
matchAt = index
matched = sequence
}
}
if matchAt < 0 {
return text, ""
}
return text[:matchAt], matched
}
func anthropicMessageID(value string) string {
if strings.HasPrefix(value, "msg_") {
return value
}
if strings.HasPrefix(value, "resp_") {
return "msg_" + strings.TrimPrefix(value, "resp_")
}
if value == "" {
return fmt.Sprintf("msg_%d", time.Now().UnixNano())
}
return "msg_" + value
}
func anthropicToolUseID(value string) string {
if strings.HasPrefix(value, "toolu_") {
return value
}
if value == "" {
return fmt.Sprintf("toolu_%d", time.Now().UnixNano())
}
return "toolu_" + value
}
func nullableAnthropicString(value string) any {
if value == "" {
return nil
}
return value
}
func chatUsage(value responseUsage) map[string]any {
return map[string]any{
"prompt_tokens": value.InputTokens, "completion_tokens": value.OutputTokens,
"total_tokens": value.InputTokens + value.OutputTokens,
"prompt_tokens_details": map[string]any{"cached_tokens": value.InputTokensDetails.CachedTokens},
"completion_tokens_details": map[string]any{"reasoning_tokens": value.OutputTokensDetails.ReasoningTokens},
}
}
func anthropicUsage(value responseUsage) map[string]any {
return map[string]any{
"input_tokens": value.InputTokens, "output_tokens": value.OutputTokens,
"cache_creation_input_tokens": 0, "cache_read_input_tokens": value.InputTokensDetails.CachedTokens,
}
}
func anthropicErrorJSON(value any) []byte {
message := "Upstream request failed"
errorType := "api_error"
if object, ok := value.(map[string]any); ok {
if text, ok := object["message"].(string); ok && text != "" {
message = text
}
errorType = normalizeAnthropicErrorType(object)
} else if text, ok := value.(string); ok && strings.TrimSpace(text) != "" {
message = text
}
data, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": errorType, "message": message}})
return data
}
func normalizeAnthropicErrorType(object map[string]any) string {
for _, field := range []string{"type", "code"} {
value, _ := object[field].(string)
switch strings.ToLower(strings.TrimSpace(value)) {
case "invalid_request_error", "authentication_error", "billing_error", "permission_error",
"not_found_error", "rate_limit_error", "timeout_error", "overloaded_error", "api_error":
return strings.ToLower(strings.TrimSpace(value))
case "unsupported_parameter", "invalid_parameter", "bad_request", "invalid_request":
return "invalid_request_error"
case "unauthorized", "authentication_failed":
return "authentication_error"
case "forbidden":
return "permission_error"
case "not_found":
return "not_found_error"
case "rate_limit_exceeded", "too_many_requests":
return "rate_limit_error"
case "request_timeout", "timeout":
return "timeout_error"
case "service_unavailable", "overloaded":
return "overloaded_error"
case "server_error", "internal_error":
return "api_error"
}
}
return "api_error"
}
@@ -6,7 +6,6 @@ import (
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"time"
)
@@ -187,167 +186,37 @@ func (c *streamConverter) start() error {
c.id = "resp_" + fmt.Sprint(time.Now().UnixNano())
}
if c.operation == OperationChat {
return c.writeData(map[string]any{
"id": strings.Replace(c.id, "resp_", "chatcmpl_", 1), "object": "chat.completion.chunk",
"created": c.created, "model": c.model,
"choices": []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant"}, "finish_reason": nil}},
})
return c.startChat()
}
return c.writeEvent("message_start", map[string]any{
"type": "message_start", "message": map[string]any{
"id": anthropicMessageID(c.id), "type": "message", "role": "assistant",
"model": c.model, "content": []any{}, "stop_reason": nil, "stop_sequence": nil,
"usage": anthropicUsage(c.usage),
},
})
return c.startMessages()
}
func (c *streamConverter) textDelta(delta string) error {
if c.operation == OperationChat {
return c.chatDelta(map[string]any{"content": delta})
return c.textDeltaChat(delta)
}
if !c.textStarted {
c.textStarted = true
c.textIndex = c.nextIndex
c.nextIndex++
if err := c.writeEvent("content_block_start", map[string]any{"type": "content_block_start", "index": c.textIndex, "content_block": map[string]any{"type": "text", "text": ""}}); err != nil {
return err
}
}
emit, matched := c.stopFilter.Push(delta)
if matched != "" {
c.stopSequence = matched
}
if emit == "" {
return nil
}
return c.writeEvent("content_block_delta", map[string]any{"type": "content_block_delta", "index": c.textIndex, "delta": map[string]any{"type": "text_delta", "text": emit}})
}
func (c *streamConverter) thinkingStart(itemID string) error {
if !c.options.AnthropicThinking || c.thinkingStarted {
return nil
}
if err := c.start(); err != nil {
return err
}
c.thinkingStarted = true
c.thinkingIndex = c.nextIndex
c.nextIndex++
c.thinkingItemID = itemID
return c.writeEvent("content_block_start", map[string]any{
"type": "content_block_start", "index": c.thinkingIndex,
"content_block": map[string]any{"type": "thinking", "thinking": ""},
})
}
func (c *streamConverter) thinkingDelta(delta string) error {
if c.operation != OperationMessages || !c.options.AnthropicThinking {
return nil
}
if err := c.thinkingStart(""); err != nil {
return err
}
return c.writeEvent("content_block_delta", map[string]any{
"type": "content_block_delta", "index": c.thinkingIndex,
"delta": map[string]any{"type": "thinking_delta", "thinking": delta},
})
}
func (c *streamConverter) thinkingDone(item responseItem) error {
if c.operation != OperationMessages || !c.options.AnthropicThinking || !c.thinkingStarted || c.thinkingClosed {
return nil
}
if item.Encrypted != "" {
if err := c.writeEvent("content_block_delta", map[string]any{
"type": "content_block_delta", "index": c.thinkingIndex,
"delta": map[string]any{"type": "signature_delta", "signature": item.Encrypted},
}); err != nil {
return err
}
}
c.thinkingClosed = true
return c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": c.thinkingIndex})
}
func (c *streamConverter) chatDelta(delta map[string]any) error {
if err := c.start(); err != nil {
return err
}
return c.writeData(map[string]any{
"id": strings.Replace(c.id, "resp_", "chatcmpl_", 1), "object": "chat.completion.chunk", "created": c.created, "model": c.model,
"choices": []any{map[string]any{"index": 0, "delta": delta, "finish_reason": nil}},
})
return c.textDeltaMessages(delta)
}
func (c *streamConverter) toolStart(item responseItem, outputIndex int) error {
if err := c.start(); err != nil {
return err
}
tool := streamTool{Index: outputIndex, ID: item.CallID, Name: item.Name, Arguments: item.Arguments}
if c.operation == OperationMessages {
tool.Index = c.nextIndex
tool.ID = anthropicToolUseID(tool.ID)
c.nextIndex++
return c.toolStartMessages(item)
}
c.tools[item.ID] = tool
if c.operation == OperationChat {
return c.chatDelta(map[string]any{"tool_calls": []any{map[string]any{
"index": tool.Index, "id": tool.ID, "type": "function", "function": map[string]any{"name": tool.Name, "arguments": ""},
}}})
}
return c.writeEvent("content_block_start", map[string]any{
"type": "content_block_start", "index": tool.Index,
"content_block": map[string]any{"type": "tool_use", "id": tool.ID, "name": tool.Name, "input": map[string]any{}},
})
return c.toolStartChat(item, outputIndex)
}
func (c *streamConverter) toolDelta(itemID, delta string) error {
tool, ok := c.tools[itemID]
if !ok {
return nil
}
tool.SentArgs = true
c.tools[itemID] = tool
if c.operation == OperationChat {
return c.chatDelta(map[string]any{"tool_calls": []any{map[string]any{"index": tool.Index, "function": map[string]any{"arguments": delta}}}})
return c.toolDeltaChat(itemID, delta)
}
return c.writeEvent("content_block_delta", map[string]any{
"type": "content_block_delta", "index": tool.Index,
"delta": map[string]any{"type": "input_json_delta", "partial_json": delta},
})
return c.toolDeltaMessages(itemID, delta)
}
func (c *streamConverter) toolArgumentsDone(itemID, arguments string) error {
tool, ok := c.tools[itemID]
if !ok || tool.Closed {
return nil
if c.operation == OperationChat {
return c.toolArgumentsDoneChat(itemID, arguments)
}
if !tool.SentArgs {
if arguments == "" {
arguments = tool.Arguments
}
if arguments != "" {
if c.operation == OperationChat {
if err := c.chatDelta(map[string]any{"tool_calls": []any{map[string]any{"index": tool.Index, "function": map[string]any{"arguments": arguments}}}}); err != nil {
return err
}
} else if err := c.writeEvent("content_block_delta", map[string]any{
"type": "content_block_delta", "index": tool.Index,
"delta": map[string]any{"type": "input_json_delta", "partial_json": arguments},
}); err != nil {
return err
}
tool.SentArgs = true
}
}
if c.operation != OperationMessages {
c.tools[itemID] = tool
return nil
}
tool.Closed = true
c.tools[itemID] = tool
return c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": tool.Index})
return c.toolArgumentsDoneMessages(itemID, arguments)
}
func (c *streamConverter) done(status string) error {
@@ -358,97 +227,17 @@ func (c *streamConverter) done(status string) error {
return err
}
if c.operation == OperationChat {
finishReason := "stop"
if len(c.tools) > 0 {
finishReason = "tool_calls"
} else if status == "incomplete" {
finishReason = "length"
}
if err := c.writeData(map[string]any{
"id": strings.Replace(c.id, "resp_", "chatcmpl_", 1), "object": "chat.completion.chunk", "created": c.created, "model": c.model,
"choices": []any{map[string]any{"index": 0, "delta": map[string]any{}, "finish_reason": finishReason}}, "usage": chatUsage(c.usage),
}); err != nil {
return err
}
c.finished = true
_, err := io.WriteString(c.writer, "data: [DONE]\n\n")
return err
return c.doneChat(status)
}
if c.operation == OperationMessages && c.stopSequence == "" {
if pending := c.stopFilter.Flush(); pending != "" {
if err := c.textDeltaWithoutFilter(pending); err != nil {
return err
}
}
}
if c.thinkingStarted && !c.thinkingClosed {
c.thinkingClosed = true
if err := c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": c.thinkingIndex}); err != nil {
return err
}
}
if c.textStarted {
if err := c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": c.textIndex}); err != nil {
return err
}
}
openTools := make([]streamTool, 0)
for itemID, tool := range c.tools {
if c.operation == OperationMessages && !tool.Closed {
tool.Closed = true
c.tools[itemID] = tool
openTools = append(openTools, tool)
}
}
sort.Slice(openTools, func(i, j int) bool { return openTools[i].Index < openTools[j].Index })
for _, tool := range openTools {
if err := c.writeEvent("content_block_stop", map[string]any{"type": "content_block_stop", "index": tool.Index}); err != nil {
return err
}
}
stopReason := "end_turn"
if len(c.tools) > 0 {
stopReason = "tool_use"
} else if c.stopSequence != "" {
stopReason = "stop_sequence"
} else if status == "incomplete" {
stopReason = "max_tokens"
}
if err := c.writeEvent("message_delta", map[string]any{
"type": "message_delta", "delta": map[string]any{"stop_reason": stopReason, "stop_sequence": nullableAnthropicString(c.stopSequence)},
"usage": map[string]any{"input_tokens": c.usage.InputTokens, "output_tokens": c.usage.OutputTokens},
}); err != nil {
return err
}
c.finished = true
return c.writeEvent("message_stop", map[string]any{"type": "message_stop"})
}
func (c *streamConverter) textDeltaWithoutFilter(delta string) error {
if delta == "" {
return nil
}
if !c.textStarted {
c.textStarted = true
c.textIndex = c.nextIndex
c.nextIndex++
if err := c.writeEvent("content_block_start", map[string]any{"type": "content_block_start", "index": c.textIndex, "content_block": map[string]any{"type": "text", "text": ""}}); err != nil {
return err
}
}
return c.writeEvent("content_block_delta", map[string]any{"type": "content_block_delta", "index": c.textIndex, "delta": map[string]any{"type": "text_delta", "text": delta}})
return c.doneMessages(status)
}
func (c *streamConverter) streamError(data []byte) error {
c.finished = true
if c.operation == OperationMessages {
return c.writeEvent("error", map[string]any{"type": "error", "error": map[string]any{"type": "api_error", "message": string(data)}})
return c.streamErrorMessages(data)
}
if err := c.writeData(json.RawMessage(data)); err != nil {
return err
}
_, err := io.WriteString(c.writer, "data: [DONE]\n\n")
return err
return c.streamErrorChat(data)
}
func (c *streamConverter) finish() error {
@@ -476,69 +265,6 @@ func (c *streamConverter) writeEvent(event string, value any) error {
return err
}
type anthropicStreamStopFilter struct {
sequences []string
pending string
matched string
}
func newAnthropicStreamStopFilter(sequences []string) *anthropicStreamStopFilter {
filtered := make([]string, 0, len(sequences))
for _, sequence := range sequences {
if sequence != "" {
filtered = append(filtered, sequence)
}
}
return &anthropicStreamStopFilter{sequences: filtered}
}
func (f *anthropicStreamStopFilter) Push(delta string) (string, string) {
if f == nil || len(f.sequences) == 0 {
return delta, ""
}
if f.matched != "" {
return "", f.matched
}
f.pending += delta
matchAt := -1
matched := ""
for _, sequence := range f.sequences {
if index := strings.Index(f.pending, sequence); index >= 0 && (matchAt < 0 || index < matchAt) {
matchAt = index
matched = sequence
}
}
if matchAt >= 0 {
emit := f.pending[:matchAt]
f.pending = ""
f.matched = matched
return emit, matched
}
hold := 0
for _, sequence := range f.sequences {
maxPrefix := min(len(sequence)-1, len(f.pending))
for size := maxPrefix; size > hold; size-- {
if strings.HasSuffix(f.pending, sequence[:size]) {
hold = size
break
}
}
}
emitAt := len(f.pending) - hold
emit := f.pending[:emitAt]
f.pending = f.pending[emitAt:]
return emit, ""
}
func (f *anthropicStreamStopFilter) Flush() string {
if f == nil || f.matched != "" {
return ""
}
value := f.pending
f.pending = ""
return value
}
func consumeSSE(source io.Reader, handle func(string, []byte) error) error {
reader := bufio.NewReaderSize(source, 64<<10)
var event string
+44 -6
View File
@@ -21,6 +21,22 @@ var (
ErrUnauthorized = errors.New("upstream credential unauthorized")
)
// HTTPStatusError 允许流式或异步 Provider 在无法返回 Response 时保留上游状态码。
type HTTPStatusError interface {
error
HTTPStatusCode() int
}
// ErrorHTTPStatus 从 Provider 错误链中提取上游 HTTP 状态。
func ErrorHTTPStatus(err error) (int, bool) {
var statusError HTTPStatusError
if !errors.As(err, &statusError) {
return 0, false
}
status := statusError.HTTPStatusCode()
return status, status > 0
}
// MediaPostProcessingStage 标识媒体已经生成后失败的本地处理阶段。
type MediaPostProcessingStage string
@@ -271,9 +287,15 @@ type QuotaAdapter interface {
SyncQuotaMode(ctx context.Context, credential account.Credential, mode string) (account.QuotaWindow, error)
}
type ImageAdapter interface {
// ImageGenerationAdapter 定义 Provider 可选的图片生成能力。
type ImageGenerationAdapter interface {
Adapter
GenerateImage(ctx context.Context, request ImageGenerationRequest) (*Response, error)
}
// ImageEditAdapter 定义 Provider 可选的图片编辑能力。
type ImageEditAdapter interface {
Adapter
EditImage(ctx context.Context, request ImageEditRequest) (*Response, error)
}
@@ -454,9 +476,14 @@ func (r *Registry) Validate() error {
return fmt.Errorf("Provider %s 声明 Device OAuth 但未实现适配器", value)
}
}
if definition.Media.ImageGeneration || definition.Media.ImageEdit {
if _, ok := adapter.(ImageAdapter); !ok {
return fmt.Errorf("Provider %s 声明图像能力但未实现适配器", value)
if definition.Media.ImageGeneration {
if _, ok := adapter.(ImageGenerationAdapter); !ok {
return fmt.Errorf("Provider %s 声明图像生成能力但未实现适配器", value)
}
}
if definition.Media.ImageEdit {
if _, ok := adapter.(ImageEditAdapter); !ok {
return fmt.Errorf("Provider %s 声明图像编辑能力但未实现适配器", value)
}
}
if definition.Media.VideoGeneration {
@@ -620,12 +647,23 @@ func (r *Registry) PricingModel(value account.Provider, upstreamModel string) st
return upstreamModel
}
func (r *Registry) Images(value account.Provider) (ImageAdapter, bool) {
// ImageGeneration 返回 Provider 注册的图片生成能力。
func (r *Registry) ImageGeneration(value account.Provider) (ImageGenerationAdapter, bool) {
adapter, ok := r.Get(value)
if !ok {
return nil, false
}
result, ok := adapter.(ImageAdapter)
result, ok := adapter.(ImageGenerationAdapter)
return result, ok
}
// ImageEdit 返回 Provider 注册的图片编辑能力。
func (r *Registry) ImageEdit(value account.Provider) (ImageEditAdapter, bool) {
adapter, ok := r.Get(value)
if !ok {
return nil, false
}
result, ok := adapter.(ImageEditAdapter)
return result, ok
}
+1 -1
View File
@@ -1171,7 +1171,7 @@ func buildOpenAIResult(operation, responseID, model string, parsed parsedChat, s
}
if operation == conversation.OperationMessages {
visibleText, stopSequence := applyWebStopSequences(parsed.Text.String(), options.StopSequences)
content := make([]any, 0, len(parsed.ToolCalls)+2)
content := make([]any, 0, len(parsed.ToolCalls))
if options.AnthropicThinking && parsed.Reasoning.Len() > 0 {
content = append(content, map[string]any{"type": "thinking", "thinking": parsed.Reasoning.String()})
}
@@ -628,6 +628,15 @@ func TestParseVideoStreamFixture(t *testing.T) {
}
}
func TestParseVideoStreamPreservesUpstreamStatus(t *testing.T) {
response := &http.Response{StatusCode: http.StatusTooManyRequests, Body: io.NopCloser(strings.NewReader("limited"))}
_, _, err := parseVideoStream(response, nil)
status, ok := provider.ErrorHTTPStatus(err)
if !ok || status != http.StatusTooManyRequests {
t.Fatalf("status = %d, ok = %v, err = %v", status, ok, err)
}
}
func TestParseVideoConcatenatedJSONFixture(t *testing.T) {
fixture := `{"result":{"conversation":{"conversationId":"conversation_1"}}}` +
`{"result":{"response":{"streamingVideoGenerationResponse":{"videoId":"video_1","progress":1,"videoPostId":"post_1","resolutionName":"720p"}}}}` +
+25 -9
View File
@@ -5,6 +5,7 @@ import (
"context"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"math"
@@ -21,30 +22,45 @@ import (
const weeklyQuotaMode = "weekly"
func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) (provider.QuotaSnapshot, error) {
weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential)
windows := make([]account.QuotaWindow, 0, 2)
if autoWindow, autoErr := a.SyncQuotaMode(ctx, credential, "auto"); autoErr == nil {
autoWindow, autoErr := a.SyncQuotaMode(ctx, credential, "auto")
if errors.Is(autoErr, provider.ErrUnauthorized) {
return provider.QuotaSnapshot{}, autoErr
}
if autoErr == nil {
windows = append(windows, autoWindow)
}
fastWindow, fastErr := a.SyncQuotaMode(ctx, credential, "fast")
if errors.Is(fastErr, provider.ErrUnauthorized) {
return provider.QuotaSnapshot{}, fastErr
}
if fastErr == nil {
windows = append(windows, fastWindow)
}
if len(windows) > 0 {
tier, useWeekly := resolveWebTierFromQuota(credential.WebTier, windows, weeklyErr == nil)
if useWeekly {
windows = []account.QuotaWindow{weekly}
tier, _ := resolveWebTierFromQuota(credential.WebTier, windows, false)
// Basic/未知账号没有付费周池,避免为每次完整同步额外访问付费端点。
// 只有模式额度已经确认付费等级时才读取 weekly 作为权威额度。
if tier == account.WebTierSuper || tier == account.WebTierHeavy {
if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil {
windows = []account.QuotaWindow{weekly}
}
}
return provider.QuotaSnapshot{Tier: tier, Windows: windows, SyncedAt: time.Now().UTC()}, nil
}
if weeklyErr == nil {
tier, _ := resolveWebTierFromQuota(credential.WebTier, nil, true)
return provider.QuotaSnapshot{Tier: tier, Windows: []account.QuotaWindow{weekly}, SyncedAt: time.Now().UTC()}, nil
// 模式端点暂不可用时,仅已确认的付费账号允许用 weekly 兜底;
// Basic/Auto 不能凭周额度探测提权,也不应制造无意义的付费端点流量。
if credential.WebTier == account.WebTierSuper || credential.WebTier == account.WebTierHeavy {
if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil {
return provider.QuotaSnapshot{Tier: credential.WebTier, Windows: []account.QuotaWindow{weekly}, SyncedAt: time.Now().UTC()}, nil
} else {
return provider.QuotaSnapshot{}, weeklyErr
}
}
if fastErr != nil {
return provider.QuotaSnapshot{}, fastErr
}
return provider.QuotaSnapshot{}, weeklyErr
return provider.QuotaSnapshot{}, autoErr
}
func resolveWebTierFromQuota(current account.WebTier, windows []account.QuotaWindow, weeklyAvailable bool) (account.WebTier, bool) {
@@ -5,19 +5,24 @@ import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"math"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/chenyme/grok2api/backend/internal/domain/account"
infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress"
"github.com/chenyme/grok2api/backend/internal/infra/provider"
"github.com/chenyme/grok2api/backend/internal/infra/security"
)
const capturedWeeklyCreditsHex = "00000000630a610d0000304112001a00220c089abbccd2061080f2d1fc012a0c089ab0f1d2061080f2d1fc013a07080515000020413a070804150000803f3a020802421e0802120c089abbccd2061080f2d1fc011a0c089ab0f1d2061080f2d1fc01580162006801800000000f677270632d7374617475733a300d0a"
func TestParseCapturedWeeklyCreditsResponse(t *testing.T) {
body, err := hex.DecodeString("00000000630a610d0000304112001a00220c089abbccd2061080f2d1fc012a0c089ab0f1d2061080f2d1fc013a07080515000020413a070804150000803f3a020802421e0802120c089abbccd2061080f2d1fc011a0c089ab0f1d2061080f2d1fc01580162006801800000000f677270632d7374617475733a300d0a")
body, err := hex.DecodeString(capturedWeeklyCreditsHex)
if err != nil {
t.Fatal(err)
}
@@ -37,6 +42,83 @@ func TestParseCapturedWeeklyCreditsResponse(t *testing.T) {
}
}
func TestSyncQuotaFetchesWeeklyOnlyAfterPaidTierIsConfirmed(t *testing.T) {
weeklyBody, err := hex.DecodeString(capturedWeeklyCreditsHex)
if err != nil {
t.Fatal(err)
}
var weeklyCalls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
switch request.URL.Path {
case "/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig":
weeklyCalls.Add(1)
writer.Header().Set("Content-Type", "application/grpc-web+proto")
_, _ = writer.Write(weeklyBody)
case "/rest/rate-limits":
var payload struct {
ModelName string `json:"modelName"`
}
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
t.Errorf("quota payload: %v", err)
}
total := map[string]int{"auto": 50, "fast": 140}[payload.ModelName]
_ = json.NewEncoder(writer).Encode(map[string]any{
"windowSizeSeconds": 7200, "remainingQueries": total, "totalQueries": total,
})
default:
http.NotFound(writer, request)
}
}))
defer server.Close()
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
if err != nil {
t.Fatal(err)
}
encrypted, err := cipher.Encrypt("test-sso")
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{
BaseURL: server.URL, StatsigMode: "manual", StatsigManualValue: "test-signature",
}, infraegress.NewManager(egressRepositoryStub{}, cipher), cipher, nil, nil)
snapshot, err := adapter.SyncQuota(context.Background(), account.Credential{ID: 2, WebTier: account.WebTierAuto, EncryptedAccessToken: encrypted})
if err != nil {
t.Fatal(err)
}
if snapshot.Tier != account.WebTierSuper || len(snapshot.Windows) != 1 || snapshot.Windows[0].Mode != weeklyQuotaMode || weeklyCalls.Load() != 1 {
t.Fatalf("snapshot = %#v, weekly calls = %d", snapshot, weeklyCalls.Load())
}
}
func TestSyncQuotaStopsAfterFirstUnauthorizedMode(t *testing.T) {
var calls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
calls.Add(1)
http.Error(writer, "unauthorized", http.StatusUnauthorized)
}))
defer server.Close()
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
if err != nil {
t.Fatal(err)
}
encrypted, err := cipher.Encrypt("expired-sso")
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{
BaseURL: server.URL, StatsigMode: "manual", StatsigManualValue: "test-signature",
}, infraegress.NewManager(egressRepositoryStub{}, cipher), cipher, nil, nil)
_, err = adapter.SyncQuota(context.Background(), account.Credential{ID: 3, WebTier: account.WebTierAuto, EncryptedAccessToken: encrypted})
if !errors.Is(err, provider.ErrUnauthorized) {
t.Fatalf("err = %v", err)
}
if calls.Load() != 1 {
t.Fatalf("unauthorized credential made %d quota requests", calls.Load())
}
}
func TestInferWebTierFromUpstreamQuota(t *testing.T) {
tests := []struct {
name string
@@ -103,9 +185,11 @@ func TestResolveWebTierUsesFreshWebQuotaOverStoredTier(t *testing.T) {
}
func TestSyncQuotaCorrectsStoredSuperFromFreshWebQuota(t *testing.T) {
var weeklyCalls atomic.Int64
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
switch request.URL.Path {
case "/grok_api_v2.GrokBuildBilling/GetGrokCreditsConfig":
weeklyCalls.Add(1)
http.Error(writer, "not available", http.StatusNotFound)
case "/rest/rate-limits":
var payload struct {
@@ -154,4 +238,7 @@ func TestSyncQuotaCorrectsStoredSuperFromFreshWebQuota(t *testing.T) {
if snapshot.Tier != account.WebTierBasic || len(snapshot.Windows) != 2 || snapshot.Windows[0].Mode != "auto" || snapshot.Windows[0].Total != 7 || snapshot.Windows[1].Mode != "fast" || snapshot.Windows[1].Total != 30 {
t.Fatalf("snapshot = %#v", snapshot)
}
if weeklyCalls.Load() != 0 {
t.Fatalf("basic account probed weekly endpoint %d times", weeklyCalls.Load())
}
}
+12 -1
View File
@@ -15,6 +15,17 @@ import (
"github.com/chenyme/grok2api/backend/internal/infra/provider"
)
type videoUpstreamError struct {
status int
body string
}
func (e *videoUpstreamError) Error() string {
return fmt.Sprintf("视频上游返回 %d: %s", e.status, e.body)
}
func (e *videoUpstreamError) HTTPStatusCode() int { return e.status }
func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) {
cfg := a.config()
token, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken)
@@ -93,7 +104,7 @@ func parseVideoStream(response *http.Response, progress func(int)) (provider.Vid
if response.StatusCode == http.StatusUnauthorized {
return provider.VideoResult{}, "", provider.ErrUnauthorized
}
return provider.VideoResult{}, "", fmt.Errorf("视频上游返回 %d: %s", response.StatusCode, strings.TrimSpace(string(body)))
return provider.VideoResult{}, "", &videoUpstreamError{status: response.StatusCode, body: strings.TrimSpace(string(body))}
}
var result provider.VideoResult
var postID string
+43 -3
View File
@@ -84,7 +84,8 @@ func cleanupRateShard(shard *rateShard, now time.Time) {
// ConcurrencyLimiter 提供单实例并发租约。
type ConcurrencyLimiter struct {
shards [shardCount]concurrencyShard
shards [shardCount]concurrencyShard
indicesCache sync.Pool
}
type concurrencyShard struct {
@@ -97,6 +98,7 @@ func NewConcurrencyLimiter() *ConcurrencyLimiter {
for index := range limiter.shards {
limiter.shards[index].counts = make(map[string]int)
}
limiter.indicesCache.New = func() any { return make([]int, 0, 256) }
return limiter
}
@@ -135,10 +137,48 @@ func (l *ConcurrencyLimiter) Current(_ context.Context, key string) (int, error)
func (l *ConcurrencyLimiter) CurrentMany(_ context.Context, keys []string) (map[string]int, error) {
values := make(map[string]int, len(keys))
if len(keys) == 0 {
return values, nil
}
// 选号会一次读取整个候选池。先按分片聚合下标,避免同一分片在一次快照中
// 被反复加锁数千次,并缩短高并发请求之间的锁竞争窗口。
var counts [shardCount]int
for _, key := range keys {
shard := &l.shards[shardIndex(key)]
counts[shardIndex(key)]++
}
var offsets [shardCount + 1]int
for index := range shardCount {
offsets[index+1] = offsets[index] + counts[index]
}
cursors := offsets
grouped := l.indicesCache.Get().([]int)
if cap(grouped) < len(keys) {
grouped = make([]int, len(keys))
} else {
grouped = grouped[:len(keys)]
}
defer func() {
// 不保留异常大的候选池缓冲,避免一次峰值长期占用进程内存。
if cap(grouped) <= maxEntries {
l.indicesCache.Put(grouped[:0])
}
}()
for keyIndex, key := range keys {
shard := int(shardIndex(key))
grouped[cursors[shard]] = keyIndex
cursors[shard]++
}
for shardIndex := range shardCount {
if offsets[shardIndex] == offsets[shardIndex+1] {
continue
}
shard := &l.shards[shardIndex]
shard.mu.Lock()
values[key] = shard.counts[key]
for _, keyIndex := range grouped[offsets[shardIndex]:offsets[shardIndex+1]] {
key := keys[keyIndex]
values[key] = shard.counts[key]
}
shard.mu.Unlock()
}
return values, nil
@@ -38,6 +38,38 @@ func TestRateAndConcurrencyLimits(t *testing.T) {
}
}
func BenchmarkConcurrencyLimiterCurrentMany(b *testing.B) {
ctx := context.Background()
limiter := NewConcurrencyLimiter()
keys := make([]string, 3000)
releases := make([]func(), 0, len(keys))
for index := range keys {
key := fmt.Sprintf("account:%d", index+1)
keys[index] = key
release, acquired, err := limiter.Acquire(ctx, key, 8)
if err != nil || !acquired {
b.Fatalf("预置并发租约失败: acquired=%v err=%v", acquired, err)
}
releases = append(releases, release)
}
defer func() {
for _, release := range releases {
release()
}
}()
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(parallel *testing.PB) {
for parallel.Next() {
values, err := limiter.CurrentMany(ctx, keys)
if err != nil || len(values) != len(keys) {
b.Fatalf("并发快照数量 = %d, err = %v", len(values), err)
}
}
})
}
func TestStickyStoreExpires(t *testing.T) {
ctx := context.Background()
store := NewStickyStore()
+20 -6
View File
@@ -30,6 +30,7 @@ type Pool struct {
shared LeaseLimiter
key string
active atomic.Int64
queued atomic.Int64
peak atomic.Int64
jitter atomic.Int64
}
@@ -41,6 +42,7 @@ type LeaseLimiter interface {
type PoolSnapshot struct {
Limit int
Active int
Queued int
Peak int
}
@@ -109,6 +111,13 @@ func (p *Pool) Do(ctx context.Context, work func(context.Context) error) (err er
if err := p.waitJitter(ctx); err != nil {
return err
}
p.queued.Add(1)
started := false
defer func() {
if !started {
p.queued.Add(-1)
}
}()
if err := p.acquireSlot(ctx); err != nil {
return err
}
@@ -133,17 +142,22 @@ func (p *Pool) Do(ctx context.Context, work func(context.Context) error) (err er
}
}
}
p.begin()
defer p.end()
defer func() {
if releaseShared != nil {
releaseShared()
}
}()
if p.parent != nil {
return p.parent.Do(ctx, work)
run := func(workCtx context.Context) error {
started = true
p.queued.Add(-1)
p.begin()
defer p.end()
return invoke(workCtx, work)
}
return invoke(ctx, work)
if p.parent != nil {
return p.parent.Do(ctx, run)
}
return run(ctx)
}
func (p *Pool) waitJitter(ctx context.Context) error {
@@ -223,7 +237,7 @@ func (p *Pool) Snapshot() PoolSnapshot {
if p == nil {
return PoolSnapshot{}
}
return PoolSnapshot{Limit: p.Limit(), Active: int(p.active.Load()), Peak: int(p.peak.Load())}
return PoolSnapshot{Limit: p.Limit(), Active: int(p.active.Load()), Queued: int(p.queued.Load()), Peak: int(p.peak.Load())}
}
// Do 隔离单个任务 panic,适用于长驻 Worker 和后台任务监督器。
+140
View File
@@ -3,6 +3,7 @@ package batch
import (
"context"
"errors"
"runtime"
"sync"
"sync/atomic"
"testing"
@@ -136,6 +137,87 @@ func TestSharedChildPoolBoundsCategoryAcrossProcesses(t *testing.T) {
}
}
func TestChildPoolsBoundConcurrentRequestsByCategoryAndGlobalLimit(t *testing.T) {
global := NewPool(3)
refresh := NewChildPool(2, global)
syncPool := NewChildPool(2, global)
var globalActive atomic.Int64
var globalPeak atomic.Int64
var refreshActive atomic.Int64
var refreshPeak atomic.Int64
var syncActive atomic.Int64
var syncPeak atomic.Int64
trackPeak := func(active, peak *atomic.Int64) {
current := active.Add(1)
for {
value := peak.Load()
if current <= value || peak.CompareAndSwap(value, current) {
return
}
}
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
start := make(chan struct{})
work := func(active, peak *atomic.Int64) func(context.Context, int) error {
return func(workCtx context.Context, _ int) error {
trackPeak(&globalActive, &globalPeak)
trackPeak(active, peak)
defer globalActive.Add(-1)
defer active.Add(-1)
select {
case <-start:
return nil
case <-workCtx.Done():
return workCtx.Err()
}
}
}
var wait sync.WaitGroup
for _, operation := range []struct {
pool *Pool
active *atomic.Int64
peak *atomic.Int64
}{
{pool: refresh, active: &refreshActive, peak: &refreshPeak},
{pool: refresh, active: &refreshActive, peak: &refreshPeak},
{pool: syncPool, active: &syncActive, peak: &syncPeak},
{pool: syncPool, active: &syncActive, peak: &syncPeak},
} {
operation := operation
wait.Add(1)
go func() {
defer wait.Done()
_, summary, err := Run(ctx, make([]int, 3), Options{Workers: 3, Pool: operation.pool}, work(operation.active, operation.peak))
if err != nil || summary.Succeeded != 3 {
t.Errorf("summary = %#v, err = %v", summary, err)
}
}()
}
deadline := time.After(time.Second)
for globalPeak.Load() < 3 {
select {
case <-deadline:
t.Fatal("并发任务未填满全局容量")
default:
runtime.Gosched()
}
}
close(start)
wait.Wait()
if globalPeak.Load() != 3 {
t.Fatalf("global peak = %d", globalPeak.Load())
}
if refreshPeak.Load() > 2 || syncPeak.Load() > 2 {
t.Fatalf("refresh peak = %d, sync peak = %d", refreshPeak.Load(), syncPeak.Load())
}
}
func TestMapIsolatesFailureAndPanic(t *testing.T) {
results, summary, err := Map(context.Background(), []int{1, 2, 3}, Options{Workers: 3}, func(_ context.Context, value int) (int, error) {
switch value {
@@ -233,6 +315,64 @@ func TestPoolHotResizeAndChildLimit(t *testing.T) {
}
}
func TestChildSnapshotSeparatesQueuedFromActiveWork(t *testing.T) {
global := NewPool(1)
child := NewChildPool(1, global)
blockerStarted := make(chan struct{})
releaseBlocker := make(chan struct{})
blockerDone := make(chan error, 1)
go func() {
blockerDone <- global.Do(context.Background(), func(context.Context) error {
close(blockerStarted)
<-releaseBlocker
return nil
})
}()
<-blockerStarted
childStarted := make(chan struct{})
childDone := make(chan error, 1)
go func() {
childDone <- child.Do(context.Background(), func(context.Context) error {
close(childStarted)
return nil
})
}()
deadline := time.After(time.Second)
for {
snapshot := child.Snapshot()
if snapshot.Queued == 1 {
if snapshot.Active != 0 {
t.Fatalf("waiting child snapshot = %#v", snapshot)
}
break
}
select {
case <-deadline:
t.Fatal("child task was not reported as queued")
default:
runtime.Gosched()
}
}
close(releaseBlocker)
if err := <-blockerDone; err != nil {
t.Fatal(err)
}
select {
case <-childStarted:
case <-time.After(time.Second):
t.Fatal("queued child task did not start")
}
if err := <-childDone; err != nil {
t.Fatal(err)
}
if snapshot := child.Snapshot(); snapshot.Active != 0 || snapshot.Queued != 0 || snapshot.Peak != 1 {
t.Fatalf("completed child snapshot = %#v", snapshot)
}
}
func TestPoolJitterHonorsCancellationBeforeWork(t *testing.T) {
pool := NewPool(2)
pool.UpdateJitter(time.Hour)
+1 -1
View File
@@ -38,7 +38,7 @@ type DeviceSessionRepository interface {
Delete(ctx context.Context, id string) error
}
// DistributedLock 定义跨实例的短期互斥租约,用于避免同一凭据被并发刷新。
// DistributedLock 定义跨实例的短期互斥租约,用于避免同一账号维护任务被并发执行。
type DistributedLock interface {
Acquire(ctx context.Context, key string, ttl time.Duration) (release func(), acquired bool, err error)
}
@@ -0,0 +1,56 @@
package middleware
import (
"net/http"
"sync"
"github.com/gin-gonic/gin"
)
// ConcurrencyGate 为单实例推理入口提供可热更新、立即拒绝的总容量保护。
type ConcurrencyGate struct {
mu sync.Mutex
limit int
active int
}
// NewConcurrencyGate 创建指定上限的推理入口并发闸门。
func NewConcurrencyGate(limit int) *ConcurrencyGate {
if limit < 1 {
panic("middleware: 并发上限必须大于零")
}
return &ConcurrencyGate{limit: limit}
}
// UpdateLimit 热更新并发上限;降低上限不会中断正在执行的请求。
func (g *ConcurrencyGate) UpdateLimit(limit int) {
if limit < 1 {
panic("middleware: 并发上限必须大于零")
}
g.mu.Lock()
g.limit = limit
g.mu.Unlock()
}
// Middleware 返回绑定当前 Gate 状态的 Gin 中间件。
func (g *ConcurrencyGate) Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
g.mu.Lock()
if g.active >= g.limit {
g.mu.Unlock()
c.Header("Retry-After", "1")
c.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{
"code": "server_overloaded", "message": "服务并发已达到上限,请稍后重试", "param": nil, "type": "server_error",
}})
return
}
g.active++
g.mu.Unlock()
defer func() {
g.mu.Lock()
g.active--
g.mu.Unlock()
}()
c.Next()
}
}
@@ -0,0 +1,68 @@
package middleware
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
)
func TestConcurrencyGateHotReloadsAndReleasesCapacity(t *testing.T) {
gin.SetMode(gin.TestMode)
started := make(chan struct{})
release := make(chan struct{})
router := gin.New()
gate := NewConcurrencyGate(1)
router.Use(gate.Middleware())
router.GET("/v1/responses", func(c *gin.Context) {
if c.Query("block") == "true" {
close(started)
<-release
}
c.Status(http.StatusOK)
})
firstDone := make(chan struct{})
go func() {
defer close(firstDone)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/v1/responses?block=true", nil))
if recorder.Code != http.StatusOK {
t.Errorf("first status = %d", recorder.Code)
}
}()
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("first request did not acquire capacity")
}
overflow := httptest.NewRecorder()
router.ServeHTTP(overflow, httptest.NewRequest(http.MethodGet, "/v1/responses", nil))
if overflow.Code != http.StatusServiceUnavailable || overflow.Header().Get("Retry-After") != "1" {
t.Fatalf("overflow status = %d, retry-after = %q", overflow.Code, overflow.Header().Get("Retry-After"))
}
gate.UpdateLimit(2)
expanded := httptest.NewRecorder()
router.ServeHTTP(expanded, httptest.NewRequest(http.MethodGet, "/v1/responses", nil))
if expanded.Code != http.StatusOK {
t.Fatalf("expanded status = %d", expanded.Code)
}
gate.UpdateLimit(1)
reduced := httptest.NewRecorder()
router.ServeHTTP(reduced, httptest.NewRequest(http.MethodGet, "/v1/responses", nil))
if reduced.Code != http.StatusServiceUnavailable {
t.Fatalf("reduced status = %d", reduced.Code)
}
close(release)
<-firstDone
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/v1/responses", nil))
if recorder.Code != http.StatusOK {
t.Fatalf("released status = %d", recorder.Code)
}
}
@@ -39,6 +39,7 @@ type Dependencies struct {
Logger *slog.Logger
RequestTimeout time.Duration
MaxBodyBytes int64
ConcurrencyGate *middleware.ConcurrencyGate
SecureCookies bool
SwaggerEnabled bool
PublicAPIBaseURL string
@@ -100,6 +101,9 @@ type ReadinessSnapshot struct {
// New 创建完整 HTTP 路由并明确区分公共、管理员和客户端鉴权边界。
func New(deps Dependencies) *gin.Engine {
if deps.ConcurrencyGate == nil {
panic("httpserver: ConcurrencyGate 不能为空")
}
gin.SetMode(gin.ReleaseMode)
if deps.Logger == nil {
deps.Logger = slog.Default()
@@ -151,6 +155,7 @@ func New(deps Dependencies) *gin.Engine {
}).Register(adminProtected)
v1 := router.Group("/v1")
v1.Use(deps.ConcurrencyGate.Middleware())
if deps.TrafficReady != nil {
v1.Use(func(c *gin.Context) {
if deps.TrafficReady() {
+38 -20
View File
@@ -11,22 +11,26 @@ import (
"strings"
"testing"
"time"
"github.com/chenyme/grok2api/backend/internal/transport/http/middleware"
)
func testDependencies() Dependencies {
return Dependencies{RequestTimeout: time.Second, MaxBodyBytes: 1024, ConcurrencyGate: middleware.NewConcurrencyGate(1024)}
}
func TestReadinessEndpointReturnsStructuredDegradedStateAsReady(t *testing.T) {
router := New(Dependencies{
RequestTimeout: time.Second,
MaxBodyBytes: 1024,
Readiness: func(context.Context) ReadinessSnapshot {
return ReadinessSnapshot{
Ready: true, State: "degraded", UpdatedAt: time.Now().UTC(),
Components: map[string]ReadinessComponent{
"grok_build": {State: "ready"},
"grok_web": {State: "unavailable"},
},
}
},
})
deps := testDependencies()
deps.Readiness = func(context.Context) ReadinessSnapshot {
return ReadinessSnapshot{
Ready: true, State: "degraded", UpdatedAt: time.Now().UTC(),
Components: map[string]ReadinessComponent{
"grok_build": {State: "ready"},
"grok_web": {State: "unavailable"},
},
}
}
router := New(deps)
request := httptest.NewRequest(http.MethodGet, "/readyz", nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
@@ -43,9 +47,11 @@ func TestReadinessEndpointReturnsStructuredDegradedStateAsReady(t *testing.T) {
}
func TestReadinessEndpointReturns503WhileReconciling(t *testing.T) {
router := New(Dependencies{RequestTimeout: time.Second, MaxBodyBytes: 1024, Readiness: func(context.Context) ReadinessSnapshot {
deps := testDependencies()
deps.Readiness = func(context.Context) ReadinessSnapshot {
return ReadinessSnapshot{Ready: false, State: "reconciling", UpdatedAt: time.Now().UTC()}
}})
}
router := New(deps)
request := httptest.NewRequest(http.MethodGet, "/readyz", nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
@@ -55,7 +61,9 @@ func TestReadinessEndpointReturns503WhileReconciling(t *testing.T) {
}
func TestInferenceTrafficIsRejectedWhileReconciling(t *testing.T) {
router := New(Dependencies{RequestTimeout: time.Second, MaxBodyBytes: 1024, TrafficReady: func() bool { return false }})
deps := testDependencies()
deps.TrafficReady = func() bool { return false }
router := New(deps)
request := httptest.NewRequest(http.MethodGet, "/v1/models", nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
@@ -65,7 +73,9 @@ func TestInferenceTrafficIsRejectedWhileReconciling(t *testing.T) {
}
func TestSystemInfoRequiresAdminAuthentication(t *testing.T) {
router := New(Dependencies{RequestTimeout: time.Second, MaxBodyBytes: 1024, PublicAPIBaseURL: "https://api.example.com"})
deps := testDependencies()
deps.PublicAPIBaseURL = "https://api.example.com"
router := New(deps)
request := httptest.NewRequest(http.MethodGet, "/api/admin/v1/system", nil)
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
@@ -85,7 +95,10 @@ func TestFrontendStaticFilesAndSPAFallback(t *testing.T) {
if err := os.WriteFile(filepath.Join(root, "assets", "app.js"), []byte("console.log('app')"), 0o600); err != nil {
t.Fatal(err)
}
router := New(Dependencies{Logger: slog.Default(), RequestTimeout: time.Second, MaxBodyBytes: 1024, FrontendStaticPath: root})
deps := testDependencies()
deps.Logger = slog.Default()
deps.FrontendStaticPath = root
router := New(deps)
for _, test := range []struct {
path string
@@ -117,7 +130,9 @@ func TestFrontendStaticFilesAndSPAFallback(t *testing.T) {
}
func TestSwaggerRegistrationFollowsStartupConfig(t *testing.T) {
disabled := New(Dependencies{Logger: slog.Default(), RequestTimeout: time.Second, MaxBodyBytes: 1024})
disabledDeps := testDependencies()
disabledDeps.Logger = slog.Default()
disabled := New(disabledDeps)
disabledRequest := httptest.NewRequest(http.MethodGet, "/swagger/doc.json", nil)
disabledRecorder := httptest.NewRecorder()
disabled.ServeHTTP(disabledRecorder, disabledRequest)
@@ -125,7 +140,10 @@ func TestSwaggerRegistrationFollowsStartupConfig(t *testing.T) {
t.Fatalf("disabled swagger status = %d, want %d", disabledRecorder.Code, http.StatusNotFound)
}
enabled := New(Dependencies{Logger: slog.Default(), RequestTimeout: time.Second, MaxBodyBytes: 1024, SwaggerEnabled: true})
enabledDeps := testDependencies()
enabledDeps.Logger = slog.Default()
enabledDeps.SwaggerEnabled = true
enabled := New(enabledDeps)
enabledRequest := httptest.NewRequest(http.MethodGet, "/swagger/doc.json", nil)
enabledRecorder := httptest.NewRecorder()
enabled.ServeHTTP(enabledRecorder, enabledRequest)
@@ -21,6 +21,7 @@ func (h *Handler) Register(router *gin.RouterGroup) {
}
type settingsConfigDTO struct {
Server serverConfigDTO `json:"server"`
ProviderBuild providerBuildConfigDTO `json:"providerBuild"`
ProviderWeb providerWebConfigDTO `json:"providerWeb"`
ProviderConsole providerConsoleConfigDTO `json:"providerConsole"`
@@ -32,6 +33,10 @@ type settingsConfigDTO struct {
ClientKeyDefaults clientKeyDefaultsConfigDTO `json:"clientKeyDefaults"`
}
type serverConfigDTO struct {
MaxConcurrentRequests int `json:"maxConcurrentRequests"`
}
type providerConsoleConfigDTO struct {
BaseURL string `json:"baseURL"`
UserAgent string `json:"userAgent"`
@@ -147,6 +152,7 @@ func (h *Handler) update(c *gin.Context) {
func (value settingsConfigDTO) toApplication() settingsapp.EditableConfig {
return settingsapp.EditableConfig{
Server: settingsapp.ServerConfig{MaxConcurrentRequests: value.Server.MaxConcurrentRequests},
ProviderBuild: settingsapp.ProviderBuildConfig{
BaseURL: value.ProviderBuild.BaseURL, ClientVersion: value.ProviderBuild.ClientVersion,
ClientIdentifier: value.ProviderBuild.ClientIdentifier, TokenAuth: value.ProviderBuild.TokenAuth,
@@ -194,6 +200,7 @@ func newSettingsResponse(value settingsapp.Snapshot) settingsResponse {
config := value.Config
return settingsResponse{
Config: settingsConfigDTO{
Server: serverConfigDTO{MaxConcurrentRequests: config.Server.MaxConcurrentRequests},
ProviderBuild: providerBuildConfigDTO{
BaseURL: config.ProviderBuild.BaseURL, ClientVersion: config.ProviderBuild.ClientVersion,
ClientIdentifier: config.ProviderBuild.ClientIdentifier, TokenAuthConfigured: strings.TrimSpace(config.ProviderBuild.TokenAuth) != "",
+7 -19
View File
@@ -15,6 +15,13 @@ server:
# [按需修改] 仅在本地或受信任环境开启,生产环境保持 false。
swaggerEnabled: false
auth:
# [通常不要修改] 管理端访问与刷新令牌有效期。
accessTokenTTL: 15m
refreshTokenTTL: 720h
# [按需修改] 外部地址使用 HTTPS 时必须设为 true。
secureCookies: false
secrets:
# [必须修改] 至少 32 个字符。快速生成:openssl rand -hex 32
jwtSecret: "replace-with-at-least-32-characters"
@@ -29,9 +36,6 @@ bootstrapAdmin:
password: "replace-with-a-strong-password"
frontend:
# [按需修改] 管理端公共 API 地址留空时使用此值;本项也留空则回退到 http://127.0.0.1:8000。
# 生产环境建议填写外部 HTTPS 地址,例如 https://api.example.com。
publicApiBaseURL: "http://127.0.0.1:8000"
# [通常不要修改] Go 服务同源托管的前端构建目录。
staticPath: "./frontend/dist"
@@ -62,22 +66,6 @@ runtimeStore:
# [按需修改] Redis 使用 TLS 时设为 true。
tls: false
auth:
# [通常不要修改] 管理端访问与刷新令牌有效期。
accessTokenTTL: 15m
refreshTokenTTL: 720h
# [按需修改] 外部地址使用 HTTPS 时必须设为 true。
secureCookies: false
provider:
console:
# [通常不要修改] Grok Console Responses API 地址。
baseURL: "https://console.x.ai"
# [通常不要修改] 必须与 Console 出口节点的浏览器指纹保持一致。
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36"
# [按需修改] Console 单次对话超时。
chatTimeout: 5m
media:
# [通常不要修改] 当前仅支持 local;容量和清理策略在管理端设置。
driver: local
@@ -79,7 +79,7 @@ export function AccountsPage() {
const { t, i18n } = useTranslation();
const queryClient = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null);
const syncAbortRef = useRef<AbortController | null>(null);
const quotaSyncAbortRef = useRef<AbortController | null>(null);
const renewalAbortRef = useRef<AbortController | null>(null);
const conversionAbortRef = useRef<AbortController | null>(null);
const webConsoleSyncAbortRef = useRef<AbortController | null>(null);
@@ -97,7 +97,7 @@ export function AccountsPage() {
const [batchDeleteOpen, setBatchDeleteOpen] = useState(false);
const [exportOpen, setExportOpen] = useState(false);
const [syncAllOpen, setSyncAllOpen] = useState(false);
const [syncProgress, setSyncProgress] = useState<AccountTaskProgressDTO | null>(null);
const [quotaSyncProgress, setQuotaSyncProgress] = useState<AccountTaskProgressDTO | null>(null);
const [conversionTargets, setConversionTargets] = useState<string[] | "all" | null>(null);
const [conversionProgress, setConversionProgress] = useState<BuildConversionProgressState | null>(null);
const [webConsoleSyncTargets, setWebConsoleSyncTargets] = useState<string[] | "all" | null>(null);
@@ -114,7 +114,7 @@ export function AccountsPage() {
const debouncedSearch = useDebouncedValue(search);
useEffect(() => () => {
syncAbortRef.current?.abort();
quotaSyncAbortRef.current?.abort();
renewalAbortRef.current?.abort();
conversionAbortRef.current?.abort();
webConsoleSyncAbortRef.current?.abort();
@@ -201,21 +201,6 @@ export function AccountsPage() {
onError: showError,
});
const allBillingMutation = useMutation({
mutationFn: () => {
const controller = new AbortController();
syncAbortRef.current = controller;
setSyncProgress(null);
return refreshAllAccountBilling(setSyncProgress, controller.signal);
},
onSuccess: (result) => {
setSyncAllOpen(false);
toast.success(t("accounts.allBillingRefreshed", result));
},
onError: (error) => { if (!isAbortError(error)) showError(error); },
onSettled: () => { syncAbortRef.current = null; setSyncProgress(null); invalidateAccountData(); },
});
const allTokenMutation = useMutation({
mutationFn: () => {
const controller = new AbortController();
@@ -231,34 +216,21 @@ export function AccountsPage() {
onSettled: () => { renewalAbortRef.current = null; setRenewalProgress(null); invalidateAccountData(); },
});
const allWebQuotaMutation = useMutation({
mutationFn: () => {
const quotaSyncMutation = useMutation({
mutationFn: (targetProvider: AccountProvider) => {
const controller = new AbortController();
syncAbortRef.current = controller;
setSyncProgress(null);
return refreshAllWebAccountQuotas(setSyncProgress, controller.signal);
quotaSyncAbortRef.current = controller;
setQuotaSyncProgress(null);
if (targetProvider === "grok_web") return refreshAllWebAccountQuotas(setQuotaSyncProgress, controller.signal);
if (targetProvider === "grok_console") return refreshAllConsoleAccountQuotas(setQuotaSyncProgress, controller.signal);
return refreshAllAccountBilling(setQuotaSyncProgress, controller.signal);
},
onSuccess: (result) => {
setSyncAllOpen(false);
toast.success(t("accounts.allBillingRefreshed", result));
},
onError: (error) => { if (!isAbortError(error)) showError(error); },
onSettled: () => { syncAbortRef.current = null; setSyncProgress(null); invalidateAccountData(); },
});
const allConsoleQuotaMutation = useMutation({
mutationFn: () => {
const controller = new AbortController();
syncAbortRef.current = controller;
setSyncProgress(null);
return refreshAllConsoleAccountQuotas(setSyncProgress, controller.signal);
},
onSuccess: (result) => {
setSyncAllOpen(false);
toast.success(t("accounts.allBillingRefreshed", result));
},
onError: (error) => { if (!isAbortError(error)) showError(error); },
onSettled: () => { syncAbortRef.current = null; setSyncProgress(null); invalidateAccountData(); },
onSettled: () => { quotaSyncAbortRef.current = null; setQuotaSyncProgress(null); invalidateAccountData(); },
});
const conversionMutation = useMutation({
mutationFn: (input: BuildConversionInput) => {
@@ -519,7 +491,14 @@ export function AccountsPage() {
const summaryUnavailable = summaryQuery.isError;
const providerAccountTotal = provider === "grok_build" ? buildSummary.total : provider === "grok_web" ? webSummary.total : consoleSummary.total;
const hasProviderAccounts = providerAccountTotal > 0 || (result?.total ?? 0) > 0;
const syncAllPending = allBillingMutation.isPending || allWebQuotaMutation.isPending || allConsoleQuotaMutation.isPending;
const bulkTaskPending = quotaSyncMutation.isPending
|| allTokenMutation.isPending
|| conversionMutation.isPending
|| webConsoleSyncMutation.isPending
|| importMutation.isPending
|| batchUpdateMutation.isPending
|| batchBillingMutation.isPending
|| batchDeleteMutation.isPending;
return (
<div className="space-y-8">
@@ -592,25 +571,25 @@ export function AccountsPage() {
{selected.size > 0 ? (
<div className="flex flex-wrap items-center gap-1.5">
<span className="mr-1 text-xs text-muted-foreground">{t("common.selectedCount", { count: selected.size })}</span>
<Button variant="secondary" size="sm" onClick={() => batchUpdateMutation.mutate(true)}>{t("common.enable")}</Button>
<Button variant="secondary" size="sm" onClick={() => batchUpdateMutation.mutate(false)}>{t("common.disable")}</Button>
{provider === "grok_web" ? <Button variant="secondary" size="sm" onClick={() => setConversionTargets([...selected])}>{t("accounts.convertToBuild")}</Button> : null}
{provider === "grok_web" ? <Button variant="secondary" size="sm" onClick={() => setWebConsoleSyncTargets([...selected])}>{t("webConsoleSync.action")}</Button> : null}
{provider === "grok_build" ? <Button variant="secondary" size="sm" onClick={() => batchBillingMutation.mutate()}>{t("accounts.refreshBilling")}</Button> : null}
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" onClick={() => setBatchDeleteOpen(true)}>{t("common.delete")}</Button>
<Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => batchUpdateMutation.mutate(true)}>{t("common.enable")}</Button>
<Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => batchUpdateMutation.mutate(false)}>{t("common.disable")}</Button>
{provider === "grok_web" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setConversionTargets([...selected])}>{t("accounts.convertToBuild")}</Button> : null}
{provider === "grok_web" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setWebConsoleSyncTargets([...selected])}>{t("webConsoleSync.action")}</Button> : null}
{provider === "grok_build" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => batchBillingMutation.mutate()}>{t("accounts.refreshBilling")}</Button> : null}
<Button variant="ghost" size="sm" className="text-destructive hover:text-destructive" disabled={bulkTaskPending} onClick={() => setBatchDeleteOpen(true)}>{t("common.delete")}</Button>
</div>
) : (
<div className="flex items-center gap-1.5">
{provider === "grok_web" && webSummary.total > 0 ? <Button variant="secondary" size="sm" onClick={() => setConversionTargets("all")}>{t("accountBulk.convertAllToBuild")}</Button> : null}
{provider === "grok_web" && webSummary.total > 0 ? <Button variant="secondary" size="sm" onClick={() => setWebConsoleSyncTargets("all")}>{t("webConsoleSync.allAction")}</Button> : null}
{hasProviderAccounts ? <Button variant="secondary" size="sm" onClick={() => setSyncAllOpen(true)}>{t("accountCredential.quotaSyncAction")}</Button> : null}
{hasProviderAccounts && provider === "grok_build" ? <Button variant="secondary" size="sm" onClick={() => setRenewAllOpen(true)}>{t("accountCredential.refreshAction")}</Button> : null}
{provider === "grok_web" && webSummary.total > 0 ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setConversionTargets("all")}>{t("accountBulk.convertAllToBuild")}</Button> : null}
{provider === "grok_web" && webSummary.total > 0 ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setWebConsoleSyncTargets("all")}>{t("webConsoleSync.allAction")}</Button> : null}
{hasProviderAccounts ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setSyncAllOpen(true)}>{t("accountCredential.quotaSyncAction")}</Button> : null}
{hasProviderAccounts && provider === "grok_build" ? <Button variant="secondary" size="sm" disabled={bulkTaskPending} onClick={() => setRenewAllOpen(true)}>{t("accountCredential.refreshAction")}</Button> : null}
<DropdownMenu>
<DropdownMenuTrigger asChild><Button size="sm">{t("accounts.connectAccount")}</Button></DropdownMenuTrigger>
<DropdownMenuContent align="end">
{provider === "grok_build" ? <DropdownMenuItem onClick={() => void startDeviceLogin()}><ExternalLink />{t("accounts.deviceLogin")}</DropdownMenuItem> : null}
{provider !== "grok_build" ? <DropdownMenuItem disabled={importMutation.isPending} onClick={() => setQuickImportOpen(true)}><ClipboardPaste />{t("accounts.quickImportSSO")}</DropdownMenuItem> : null}
<DropdownMenuItem disabled={importMutation.isPending} onClick={() => fileInputRef.current?.click()}><FileUp />{provider === "grok_build" ? t("accounts.importAuth") : provider === "grok_console" ? t("console.importFile") : t("accounts.importWebFile")}</DropdownMenuItem>
{provider !== "grok_build" ? <DropdownMenuItem disabled={bulkTaskPending} onClick={() => setQuickImportOpen(true)}><ClipboardPaste />{t("accounts.quickImportSSO")}</DropdownMenuItem> : null}
<DropdownMenuItem disabled={bulkTaskPending} onClick={() => fileInputRef.current?.click()}><FileUp />{provider === "grok_build" ? t("accounts.importAuth") : provider === "grok_console" ? t("console.importFile") : t("accounts.importWebFile")}</DropdownMenuItem>
{hasProviderAccounts && provider === "grok_build" ? (
<>
<DropdownMenuSeparator />
@@ -714,10 +693,10 @@ export function AccountsPage() {
</DataTableShell>
</div>
<AlertDialog open={syncAllOpen} onOpenChange={(open) => { if (!open) syncAbortRef.current?.abort(); setSyncAllOpen(open); }}>
<AlertDialog open={syncAllOpen} onOpenChange={(open) => { if (!open) quotaSyncAbortRef.current?.abort(); setSyncAllOpen(open); }}>
<AlertDialogContent>
<AlertDialogHeader><AlertDialogTitle>{t("accounts.syncAllTitle")}</AlertDialogTitle><AlertDialogDescription>{t(provider === "grok_web" ? "accounts.syncAllWebDescription" : provider === "grok_console" ? "console.syncAllDescription" : "accounts.syncAllDescription")}</AlertDialogDescription></AlertDialogHeader>
<AlertDialogFooter><AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel><AlertDialogAction disabled={syncAllPending} onClick={() => provider === "grok_web" ? allWebQuotaMutation.mutate() : provider === "grok_console" ? allConsoleQuotaMutation.mutate() : allBillingMutation.mutate()}>{syncAllPending ? <><Spinner />{syncProgress ? <span className="tabular-nums">{syncProgress.completed} / {syncProgress.total}</span> : t("common.loading")}</> : t("accounts.syncAll")}</AlertDialogAction></AlertDialogFooter>
<AlertDialogFooter><AlertDialogCancel>{t("common.cancel")}</AlertDialogCancel><AlertDialogAction disabled={quotaSyncMutation.isPending} onClick={() => quotaSyncMutation.mutate(provider)}>{quotaSyncMutation.isPending ? <><Spinner />{quotaSyncProgress ? <span className="tabular-nums">{quotaSyncProgress.completed} / {quotaSyncProgress.total}</span> : t("common.loading")}</> : t("accounts.syncAll")}</AlertDialogAction></AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
@@ -3,6 +3,7 @@ import { createObjectDecoder, decodeBooleanResult, hasShape, isArrayOf, isBoolea
import type { SortOrder } from "@/shared/lib/table-sort";
export type SettingsConfigDTO = {
server: { maxConcurrentRequests: number };
providerBuild: { baseURL: string; clientVersion: string; clientIdentifier: string; tokenAuth: string; tokenAuthConfigured: boolean; userAgent: string };
providerWeb: {
baseURL: string; quotaTimeout: string; chatTimeout: string; imageTimeout: string; videoTimeout: string;
@@ -45,12 +46,14 @@ export type SettingsSnapshotDTO = {
};
const settingsConfigValidator = hasShape({
server: hasShape({ maxConcurrentRequests: isNumber }),
providerBuild: hasShape({ baseURL: isString, clientVersion: isString, clientIdentifier: isString, tokenAuth: isString, tokenAuthConfigured: isBoolean, userAgent: isString }),
providerWeb: hasShape({
baseURL: isString, quotaTimeout: isString, chatTimeout: isString, imageTimeout: isString, videoTimeout: isString,
statsigMode: isOneOf("manual", "url"), statsigManualValue: isOptional(isString), statsigManualConfigured: isBoolean,
statsigSignerURL: isString, mediaConcurrency: isNumber, allowNSFW: isBoolean, recoveryBackoffBase: isString, recoveryBackoffMax: isString,
}),
providerConsole: hasShape({ baseURL: isString, userAgent: isString, chatTimeout: isString }),
batch: hasShape({ importConcurrency: isNumber, conversionConcurrency: isNumber, syncConcurrency: isNumber, refreshConcurrency: isNumber, randomDelay: isString }),
media: hasShape({ maxImageBytes: isNumber, maxTotalBytes: isNumber, cleanupThresholdPercent: isNumber, cleanupInterval: isString }),
frontend: hasShape({ publicApiBaseURL: isString }),
@@ -35,6 +35,9 @@ function validPublicAPIBaseURL(value: string): boolean {
}
export const settingsSchema = z.object({
server: z.object({
maxConcurrentRequests: positiveInteger.max(100_000),
}),
providerBuild: z.object({
baseURL: z.url(),
clientVersion: z.string().trim().min(1),
@@ -109,6 +112,7 @@ export type SettingsForm = z.infer<typeof settingsSchema>;
export function toSettingsForm(config: SettingsConfigDTO): SettingsForm {
return {
server: config.server,
providerBuild: { ...config.providerBuild, tokenAuth: "" },
providerWeb: {
...config.providerWeb,
@@ -138,6 +142,7 @@ export function toSettingsForm(config: SettingsConfigDTO): SettingsForm {
export function toSettingsDTO(config: SettingsForm): SettingsConfigDTO {
return {
server: config.server,
providerBuild: config.providerBuild,
providerWeb: {
...config.providerWeb,
@@ -164,6 +164,14 @@ export function SettingsPage() {
</SettingsPane>
<SettingsPane value="policies">
<SettingsSection title={t("settings.server.title")}>
<div className="grid gap-x-4 gap-y-5 sm:grid-cols-2">
<SettingsField controlId="server-max-concurrent-requests" label={t("settings.server.maxConcurrentRequests")} description={t("settings.server.maxConcurrentRequestsHelp")} error={form.formState.errors.server?.maxConcurrentRequests?.message}>
<Input id="server-max-concurrent-requests" type="number" min={1} max={100_000} {...form.register("server.maxConcurrentRequests", { valueAsNumber: true })} />
</SettingsField>
</div>
</SettingsSection>
<SettingsSection title={t("settings.batch.title")}>
<div className="grid gap-x-4 gap-y-5 sm:grid-cols-2">
<SettingsField controlId="batch-import-concurrency" label={t("settings.batch.importConcurrency")} error={form.formState.errors.batch?.importConcurrency?.message}><Input id="batch-import-concurrency" type="number" min={1} max={50} {...form.register("batch.importConcurrency", { valueAsNumber: true })} /></SettingsField>
+3 -2
View File
@@ -531,10 +531,11 @@ const resources = {
invalidValue: "请输入有效值",
durationUnit: "时长单位",
groups: { providers: "Provider 配置", delivery: "媒体与网络", policies: "运行策略" },
server: { title: "服务容量", maxConcurrentRequests: "API 请求并发上限", maxConcurrentRequestsHelp: "单实例同时处理的 /v1 请求数;调低不会中断进行中的请求。" },
provider: { title: "Grok Build", baseURL: "上游地址", clientVersion: "客户端版本", clientIdentifier: "客户端标识", tokenAuth: "Token Auth", userAgent: "User-Agent", recommendedVersion: "推荐 {{version}}", syncRecommendedVersion: "同步推荐版本", recommendedVersionApplied: "已是推荐版本", syncRecommendedVersionDescription: "填入后端当前已完成兼容回归的版本和 User-Agent,保存后生效。" },
web: { title: "Grok Web", baseURL: "上游地址", statsigMode: "x-statsig 获取方式", statsigManual: "手动填写", statsigURL: "URL 获取", statsigValue: "x-statsig-id", statsigConfigured: "已配置", statsigKeepConfigured: "留空保持当前配置", statsigValuePlaceholder: "粘贴 x-statsig-id", statsigSignerURL: "签名服务 URL", quotaTimeout: "额度请求超时", chatTimeout: "聊天超时", imageTimeout: "图片超时", videoTimeout: "视频超时", mediaConcurrency: "媒体任务并发", recoveryBackoffBase: "额度恢复退避", recoveryBackoffMax: "额度恢复最大退避", allowNSFW: "允许 NSFW 图片" },
batch: { title: "批量任务", importConcurrency: "导入同步并发", conversionConcurrency: "账号转换并发", syncConcurrency: "数据同步并发", refreshConcurrency: "凭据刷新并发", randomDelay: "随机延迟上限(ms)" },
media: { title: "媒体存储", maxImageSize: "单张图片上限", maxTotalSize: "媒体存储上限", cleanupThresholdPercent: "自动清理阈值", cleanupInterval: "容量检查间隔", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时使用 config.yaml 配置;仍为空则使用 http://127.0.0.1:8000。" },
media: { title: "媒体存储", maxImageSize: "单张图片上限", maxTotalSize: "媒体存储上限", cleanupThresholdPercent: "自动清理阈值", cleanupInterval: "容量检查间隔", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时回退到服务启动值,默认为 http://127.0.0.1:8000。" },
egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 与 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5、SOCKS5H,可携带用户名和密码。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败" },
routing: { title: "路由策略", stickyTTL: "会话粘性时长", cooldownBase: "基础冷却时间", cooldownMax: "最大冷却时间", capacityWait: "账号满载等待", maxAttempts: "最大尝试次数" },
audit: { title: "请求审计", bufferSize: "队列容量", batchSize: "批量写入数", flushInterval: "刷新间隔" },
@@ -884,7 +885,7 @@ const resources = {
errorFrameCount_one: "{{count}} error frame",
errorFrameCount_other: "{{count}} error frames",
},
settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies" }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use config.yaml; if that is also empty, http://127.0.0.1:8000 is used." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } },
settings: { title: "Runtime settings", description: "Manage hot-reloadable gateway runtime parameters.", saved: "Settings saved and applied", restartRequired: "Restart required", invalidValue: "Enter a valid value", durationUnit: "Duration unit", groups: { providers: "Providers", delivery: "Media & network", policies: "Runtime policies" }, server: { title: "Service capacity", maxConcurrentRequests: "API request concurrency limit", maxConcurrentRequestsHelp: "Maximum simultaneous /v1 requests per instance. Lowering the limit does not interrupt active requests." }, provider: { title: "Grok Build provider", baseURL: "Upstream URL", clientVersion: "Client version", clientIdentifier: "Client identifier", tokenAuth: "Token auth", userAgent: "User-Agent", recommendedVersion: "Recommended {{version}}", syncRecommendedVersion: "Sync recommended version", recommendedVersionApplied: "Recommended version active", syncRecommendedVersionDescription: "Fill in the backend version and User-Agent that passed compatibility regression; save to apply." }, web: { title: "Grok Web", baseURL: "Upstream URL", statsigMode: "x-statsig source", statsigManual: "Manual", statsigURL: "Fetch from URL", statsigValue: "x-statsig-id", statsigConfigured: "Configured", statsigKeepConfigured: "Leave blank to keep the current value", statsigValuePlaceholder: "Paste x-statsig-id", statsigSignerURL: "Signer URL", quotaTimeout: "Quota timeout", chatTimeout: "Chat timeout", imageTimeout: "Image timeout", videoTimeout: "Video timeout", mediaConcurrency: "Media job concurrency", recoveryBackoffBase: "Quota recovery backoff", recoveryBackoffMax: "Maximum recovery backoff", allowNSFW: "Allow NSFW images" }, batch: { title: "Batch tasks", importConcurrency: "Import sync concurrency", conversionConcurrency: "Account conversion concurrency", syncConcurrency: "Data sync concurrency", refreshConcurrency: "Credential refresh concurrency", randomDelay: "Maximum random delay (ms)" }, media: { title: "Media storage", maxImageSize: "Maximum image size", maxTotalSize: "Media storage limit", cleanupThresholdPercent: "Automatic cleanup threshold", cleanupInterval: "Capacity check interval", sizeUnit: "Storage unit", publicApiBaseURL: "Public API base URL", publicApiBaseURLHelp: "Used for public image URLs and docs examples. Leave empty to use the service startup value, which defaults to http://127.0.0.1:8000." }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, or Web assets. Build inherits the Provider User-Agent; Web and Console nodes manage their own browser User-Agent and cookies. Proxy URLs and Cloudflare cookies are write-only.", add: "Add node", saved: "Proxy node saved", deleted: "Proxy node deleted", name: "Name", scope: "Scope", proxy: "Proxy", clearance: "Clearance", health: "Health", directFallback: "Direct connection is used when no node is configured", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web (assets only)", configured: "Configured", direct: "Direct", none: "None", editTitle: "Edit proxy node", addTitle: "Add proxy node", dialogDescription: "Build nodes only configure the proxy and inherit the Provider User-Agent; Web and Console nodes use their own browser User-Agent and Cloudflare cookies.", enabled: "Enabled", proxyURL: "Proxy URL", proxyProtocols: "Supports HTTP, HTTPS, SOCKS4, SOCKS4A, SOCKS5, and SOCKS5H with optional username and password.", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "Configured; leave blank to keep unchanged", operationFailed: "Operation failed" }, routing: { title: "Routing policy", stickyTTL: "Sticky session TTL", cooldownBase: "Base cooldown", cooldownMax: "Maximum cooldown", maxAttempts: "Maximum attempts" }, audit: { title: "Request audit", bufferSize: "Queue capacity", batchSize: "Batch size", flushInterval: "Flush interval" }, clientKeys: { title: "Client key defaults", rpmLimit: "Default RPM", maxConcurrent: "Default concurrency" }, units: { seconds: "Seconds", minutes: "Minutes", hours: "Hours", days: "Days" } },
docs: {
title: "API documentation",
description: "OpenAI Responses compatibility, account routing, and conversation-state behavior for this gateway.",