fix: Enhance compatibility and error handling in response processing

This commit is contained in:
Chenyme committed 2026-07-13 19:50:19 +08:00
1 parent 2059256782
commit ec6e35141f
30 files changed
+3220 -338

No files matched your search

+17 -4
View File
@@ -76,17 +76,27 @@ Grok Build `0.2.99` 尚未原生接受 OpenAI 新版 `namespace` 与 `tool_searc
- 客户端 Tool Search 会默认写入 `parallel_tool_calls: false`;显式要求并行会返回错误,避免搜索函数与普通函数在工具定义加载完成前同时执行。
- 单独声明 `defer_loading: true` 但没有客户端 `tool_search` 时返回参数错误,避免把原本延迟的工具静默改成立即可调用。
- 服务端托管 Tool Search 需要上游在同一次推理中搜索并注入工具,当前无法等价模拟,因此缺省或 `execution: "server"` 会返回 `400 unsupported_parameter`,不会静默展开全部延迟工具。
- `additional_tools` 依赖工具在输入历史中的精确插入位置,当前同样返回明确的不支持错误,不会改写成含义不同的顶层工具。
- `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`;网关保留这些原生工具参数交由上游校验。`web_search_preview` 及其版本别名会转换为最小 `web_search` 声明;当前上游会以 `Argument not supported` 拒绝 `search_context_size` 等控制字段,因此网关在请求前明确报错,不静默删字段。`local_shell`、`apply_patch` 与 `computer_use_preview` 不在 0.2.99 枚举中,同样返回明确错误。
`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`、非空 `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`、`local_shell_call` 历史和 `mcp_tool_call_output` 会分别降级为 developer/assistant 可见文本,避免把客户端执行记录伪装成上游 hosted 调用。不透明或加密的 agent 内容、`compaction_trigger` 不会被静默丢弃,而是返回明确的不支持错误。SSE 兼容层只向下游保留标准 `response.*`、`error` 与 `[DONE]`,过滤上游私有事件,同时保留标准 comment、`id` 和 `retry` 字段。
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`、`legacy_local_shell_upgraded`、`apply_patch_emulated`、`additional_tools_position_approximated`。客户端可记录这些代码进行审计,不包含提示词、工具参数或凭据。
Chat Completions 与 Messages 都先转换为标准 Responses 输入项。Build 将其发送到原生 Responses 上游,并把 JSON/SSE 转回调用方协议;Web 再把同一规范输入转换为 app-chat 对话载荷。两种 Provider 都支持文本、URL/Base64 图片、客户端函数工具和工具结果。不支持的音频、Files API、Anthropic server tools 和 Web `/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 模型名称;Anthropic 原生 thinking signature、容器和 server tools 不会伪造。
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` 可包含文本、图片和文档,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` 会返回明确的不支持错误。
@@ -230,5 +240,8 @@ Grok Build `0.2.93` 实测使用 `GET /billing` 与 `GET /billing?format=credits
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 契约。项目通过版本锁定和协议回归降低变化风险,但不能承诺跨未知未来版本的零变更兼容。
@@ -0,0 +1,215 @@
package gateway
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"unicode"
)
// UpstreamFailure 保存可安全暴露给下游和审计的上游失败分类,不包含响应正文或凭据。
type UpstreamFailure struct {
HTTPStatus int
Code string
PublicMessage string
UpstreamCode string
AccountID uint64
AccountName string
AccountScoped bool
PermanentAccountDenial bool
QuotaExhausted bool
FreeQuotaExhausted bool
CredentialRejected bool
Fingerprint string
Cause error
}
func (e *UpstreamFailure) Error() string {
if e == nil {
return "上游请求失败"
}
if e.UpstreamCode != "" {
return fmt.Sprintf("%s: %s", e.Code, e.UpstreamCode)
}
if e.Cause != nil {
return fmt.Sprintf("%s: %v", e.Code, e.Cause)
}
return e.Code
}
func (e *UpstreamFailure) Unwrap() error {
if e == nil {
return nil
}
return e.Cause
}
func (e *UpstreamFailure) AuditCode() string {
if e == nil {
return "upstream_error"
}
if suffix := normalizeFailureCode(e.UpstreamCode); suffix != "" {
return truncateFailureCode(e.Code + "_" + suffix)
}
return truncateFailureCode(e.Code)
}
func newHTTPUpstreamFailure(status int, body []byte, accountID uint64, accountName string) *UpstreamFailure {
upstreamCode, upstreamType, upstreamMessage := extractUpstreamErrorMetadata(body)
failure := &UpstreamFailure{
HTTPStatus: status, Code: "upstream_error", PublicMessage: "上游服务返回错误",
UpstreamCode: upstreamCode, AccountID: accountID, AccountName: accountName,
}
if status < 400 || status > 599 {
failure.HTTPStatus = http.StatusBadGateway
}
metadataText := strings.ToLower(strings.Join([]string{upstreamCode, upstreamType, upstreamMessage}, " "))
switch status {
case http.StatusUnauthorized:
failure.Code = "upstream_unauthorized"
failure.PublicMessage = "上游账号认证失败"
failure.AccountScoped = true
failure.CredentialRejected = true
case http.StatusPaymentRequired:
failure.Code = "upstream_payment_required"
failure.PublicMessage = "上游账号额度不足"
failure.AccountScoped = true
failure.QuotaExhausted = true
case http.StatusForbidden:
failure.Code = "upstream_forbidden"
failure.PublicMessage = "上游拒绝了该请求"
failure.PermanentAccountDenial = isPermanentAccountDenial(metadataText)
failure.FreeQuotaExhausted = isFreeQuotaExhaustion(metadataText)
failure.QuotaExhausted = failure.FreeQuotaExhausted || isPaidQuotaExhaustion(metadataText)
failure.CredentialRejected = !failure.QuotaExhausted && containsAny(metadataText, "authentication", "unauthorized", "invalid token", "token expired")
failure.AccountScoped = failure.PermanentAccountDenial || failure.QuotaExhausted || failure.CredentialRejected || isAccountScopedForbidden(metadataText)
case http.StatusTooManyRequests:
failure.Code = "upstream_rate_limited"
failure.PublicMessage = "上游请求频率受限"
failure.AccountScoped = true
failure.FreeQuotaExhausted = isFreeQuotaExhaustion(metadataText)
failure.QuotaExhausted = failure.FreeQuotaExhausted || isPaidQuotaExhaustion(metadataText)
default:
failure.Code = "upstream_server_error"
failure.PublicMessage = "上游服务暂时异常"
}
fingerprintPart := normalizeFailureCode(firstNonEmptyFailure(upstreamCode, upstreamType, upstreamMessage))
if fingerprintPart == "" {
fingerprintPart = "unknown"
}
failure.Fingerprint = fmt.Sprintf("%d:%s", status, fingerprintPart)
return failure
}
func newTransportUpstreamFailure(err error, accountID uint64, accountName string) *UpstreamFailure {
code, message := "upstream_network_error", "连接上游服务失败"
if errors.Is(err, context.DeadlineExceeded) {
code, message = "upstream_timeout", "上游服务响应超时"
}
return &UpstreamFailure{
HTTPStatus: http.StatusBadGateway, Code: code, PublicMessage: message,
AccountID: accountID, AccountName: accountName, Fingerprint: code, Cause: err,
}
}
func newCredentialUpstreamFailure(err error, accountID uint64, accountName string) *UpstreamFailure {
return &UpstreamFailure{
HTTPStatus: http.StatusBadGateway, Code: "upstream_credential_unavailable", PublicMessage: "上游账号凭据不可用",
AccountID: accountID, AccountName: accountName, AccountScoped: true, Cause: err,
}
}
func extractUpstreamErrorMetadata(body []byte) (string, string, string) {
if len(body) == 0 {
return "", "", ""
}
var payload any
if json.Unmarshal(body, &payload) != nil {
return "", "", strings.TrimSpace(string(body))
}
root, ok := payload.(map[string]any)
if !ok {
return "", "", ""
}
if nested, ok := root["error"].(map[string]any); ok {
code := firstNonEmptyFailure(firstStringValue(nested, "code", "error_code"), firstStringValue(root, "code", "error_code"))
errorType := firstNonEmptyFailure(firstStringValue(nested, "type", "error_type"), firstStringValue(root, "type", "error_type"))
message := firstNonEmptyFailure(firstStringValue(nested, "message", "error"), firstStringValue(root, "message"))
return code, errorType, message
}
message := firstNonEmptyFailure(firstStringValue(root, "error"), firstStringValue(root, "message"))
return firstStringValue(root, "code", "error_code"), firstStringValue(root, "type", "error_type"), message
}
func isAccountScopedForbidden(text string) bool {
return containsAny(text, "quota", "billing", "subscription", "entitlement", "permission", "unauthorized", "authentication", "token", "usage-exhausted", "insufficient", "spending-limit")
}
func isPermanentAccountDenial(text string) bool {
if strings.Contains(text, "access to the chat endpoint is denied") {
return true
}
return strings.Trim(strings.TrimSpace(text), " .!\t\r\n") == "access denied"
}
func isPaidQuotaExhaustion(text string) bool {
return strings.Contains(text, "personal-team-blocked:spending-limit")
}
func isFreeQuotaExhaustion(text string) bool {
return containsAny(text, "subscription:free-usage-exhausted", "used all the included free usage for model")
}
func containsAny(text string, signals ...string) bool {
for _, signal := range signals {
if strings.Contains(text, signal) {
return true
}
}
return false
}
func firstStringValue(values map[string]any, keys ...string) string {
for _, key := range keys {
if value, ok := values[key].(string); ok {
return strings.TrimSpace(value)
}
}
return ""
}
func firstNonEmptyFailure(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}
func normalizeFailureCode(value string) string {
value = strings.ToLower(strings.TrimSpace(value))
var builder strings.Builder
for _, current := range value {
switch {
case unicode.IsLetter(current), unicode.IsDigit(current):
builder.WriteRune(current)
case current == '-', current == '_', current == '.', current == ':':
builder.WriteByte('_')
}
if builder.Len() >= 48 {
break
}
}
return strings.Trim(builder.String(), "_")
}
func truncateFailureCode(value string) string {
if len(value) <= 100 {
return value
}
return value[:100]
}
@@ -0,0 +1,42 @@
package gateway
import (
"net/http"
"testing"
)
func TestHTTPUpstreamFailureClassifiesBuildForbiddenBodies(t *testing.T) {
tests := []struct {
name string
body string
accountScoped bool
permanentAccountDenial bool
quotaExhausted bool
freeQuotaExhausted bool
upstreamCode string
}{
{
name: "top-level permanent chat denial", body: `{"status_code":403,"error":"Access to the chat endpoint is denied. Please update the permissions."}`,
accountScoped: true, permanentAccountDenial: true,
},
{
name: "spending limit", body: `{"code":"personal-team-blocked:spending-limit","error":"quota exhausted"}`,
accountScoped: true, quotaExhausted: true, upstreamCode: "personal-team-blocked:spending-limit",
},
{
name: "unknown policy rejection", body: `{"error":"upstream policy rejected request"}`,
},
{
name: "free model quota", body: `{"error":"You've used all the included free usage for model grok-build"}`,
accountScoped: true, quotaExhausted: true, freeQuotaExhausted: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
failure := newHTTPUpstreamFailure(http.StatusForbidden, []byte(test.body), 42, "build")
if failure.HTTPStatus != http.StatusForbidden || failure.Code != "upstream_forbidden" || failure.AccountScoped != test.accountScoped || failure.PermanentAccountDenial != test.permanentAccountDenial || failure.QuotaExhausted != test.quotaExhausted || failure.FreeQuotaExhausted != test.freeQuotaExhausted || failure.UpstreamCode != test.upstreamCode {
t.Fatalf("failure = %#v", failure)
}
})
}
}
@@ -315,13 +315,13 @@ func (s *Selector) MarkFreeQuotaExhausted(ctx context.Context, credential accoun
}
// MarkPaidQuotaExhausted 使用已知真实账期将付费账号移出号池,到期后才允许 Billing 探测。
func (s *Selector) MarkPaidQuotaExhausted(ctx context.Context, credential account.Credential, billing *account.Billing) {
func (s *Selector) MarkPaidQuotaExhausted(ctx context.Context, credential account.Credential, billing *account.Billing) bool {
if billing == nil || (billing.MonthlyLimit <= 0 && billing.OnDemandCap <= 0 && billing.OnDemandUsed <= 0 && billing.PrepaidBalance <= 0 && billing.CreditUsagePercent <= 0) {
return
return false
}
periodEnd, ok := billing.PeriodEnd()
if !ok {
return
return false
}
now := time.Now().UTC()
_ = s.accounts.SaveQuotaRecovery(ctx, account.QuotaRecovery{
@@ -330,6 +330,7 @@ func (s *Selector) MarkPaidQuotaExhausted(ctx context.Context, credential accoun
})
_ = s.sticky.DeleteByAccount(ctx, credential.ID)
s.invalidateCandidates(credential.Provider)
return true
}
// MarkQuotaStateChanged 在 Billing 探测改变持久化额度状态后立即失效候选快照。
+73 -11
View File
@@ -207,9 +207,11 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
}
}
excluded := make(map[uint64]bool)
failureFingerprints := make(map[string]int)
quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel)
quotaProbeAttempted := false
var lastErr error
var lastFailure *UpstreamFailure
for attempt := 0; attempt < attempts; attempt++ {
var lease *accountLease
var err error
@@ -219,7 +221,9 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
lease, err = s.selector.Acquire(ctx, route.Provider, route.UpstreamModel, quotaMode, input.PromptCacheKey, excluded, !quotaProbeAttempted)
}
if err != nil {
lastErr = err
if lastFailure == nil {
lastErr = err
}
break
}
if lease.QuotaProbe {
@@ -242,13 +246,22 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
if err != nil {
lease.Release()
lastErr = err
lastFailure = newCredentialUpstreamFailure(err, lease.Credential.ID, lease.Credential.Name)
continue
}
response, err := adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: credential, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation)})
if err != nil {
s.selector.MarkFailure(ctx, credential, 0, 0)
lease.Release()
lastErr = err
if ctx.Err() != nil || errors.Is(err, context.Canceled) {
lastFailure = &UpstreamFailure{HTTPStatus: 499, Code: "request_canceled", PublicMessage: "请求已取消", AccountID: credential.ID, AccountName: credential.Name, Cause: firstError(ctx.Err(), err)}
break
}
lastFailure = newTransportUpstreamFailure(err, credential.ID, credential.Name)
failureFingerprints[lastFailure.Fingerprint]++
if failureFingerprints[lastFailure.Fingerprint] >= 2 {
break
}
continue
}
if response.StatusCode == http.StatusUnauthorized {
@@ -258,6 +271,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
s.selector.MarkFailure(ctx, credential, http.StatusUnauthorized, 0)
lease.Release()
lastErr = fmt.Errorf("Grok Web SSO 凭据已失效")
lastFailure = newHTTPUpstreamFailure(http.StatusUnauthorized, nil, credential.ID, credential.Name)
continue
}
refreshed, refreshErr := s.accounts.EnsureCredential(ctx, credential, true)
@@ -266,16 +280,25 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
credential = refreshed
}
if refreshErr != nil || err != nil {
s.selector.MarkFailure(ctx, credential, http.StatusUnauthorized, 0)
lease.Release()
lastErr = firstError(refreshErr, err)
if refreshErr != nil {
lastFailure = newCredentialUpstreamFailure(refreshErr, credential.ID, credential.Name)
} else if ctx.Err() != nil || errors.Is(err, context.Canceled) {
lastFailure = &UpstreamFailure{HTTPStatus: 499, Code: "request_canceled", PublicMessage: "请求已取消", AccountID: credential.ID, AccountName: credential.Name, Cause: firstError(ctx.Err(), err)}
break
} else {
lastFailure = newTransportUpstreamFailure(err, credential.ID, credential.Name)
}
continue
}
if response.StatusCode == http.StatusUnauthorized {
response.Body.Close()
s.selector.MarkFailure(ctx, credential, http.StatusUnauthorized, 0)
body, _ := readRetryableBody(response.Body)
_ = s.accounts.MarkReauthRequired(ctx, credential.ID, "Grok Build OAuth credential rejected after refresh")
s.selector.MarkQuotaStateChanged(credential.Provider)
lease.Release()
lastErr = fmt.Errorf("刷新后上游仍返回 401")
lastFailure = newHTTPUpstreamFailure(http.StatusUnauthorized, body, credential.ID, credential.Name)
continue
}
}
@@ -288,26 +311,47 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
delete(excluded, credential.ID)
lease.Release()
lastErr = fmt.Errorf("Grok Web 出口会话被反机器人规则拒绝")
lastFailure = newHTTPUpstreamFailure(response.StatusCode, body, credential.ID, credential.Name)
continue
}
lastFailure = newHTTPUpstreamFailure(response.StatusCode, body, credential.ID, credential.Name)
failureHandled := false
if credential.Provider == accountdomain.ProviderWeb {
if lease.QuotaMode != "" && response.StatusCode == http.StatusTooManyRequests {
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)
}
failureHandled = reconcileErr == nil && exhausted
}
} else if used, limit, exhausted := parseFreeQuotaExhaustion(body); exhausted {
s.selector.MarkFreeQuotaExhausted(ctx, credential, used, limit)
} else {
s.selector.MarkPaidQuotaExhausted(ctx, credential, lease.Billing)
failureHandled = true
} else if lastFailure.FreeQuotaExhausted {
s.selector.MarkFreeQuotaExhausted(ctx, credential, 0, 0)
failureHandled = true
} else if lastFailure.QuotaExhausted {
failureHandled = s.selector.MarkPaidQuotaExhausted(ctx, credential, lease.Billing)
}
if credential.Provider != accountdomain.ProviderWeb || response.StatusCode != http.StatusTooManyRequests {
if credential.Provider == accountdomain.ProviderBuild && lastFailure.PermanentAccountDenial {
_ = s.accounts.MarkReauthRequired(ctx, credential.ID, "Grok Build chat endpoint access denied")
s.selector.MarkQuotaStateChanged(credential.Provider)
failureHandled = true
} else if credential.Provider == accountdomain.ProviderBuild && lastFailure.CredentialRejected {
_ = s.accounts.MarkReauthRequired(ctx, credential.ID, "Grok Build credential rejected")
s.selector.MarkQuotaStateChanged(credential.Provider)
failureHandled = true
}
if lastFailure.AccountScoped && !failureHandled {
s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter)
}
lease.Release()
lastErr = fmt.Errorf("上游返回 %d", response.StatusCode)
s.logger.Warn("upstream_request_failed", "request_id", input.RequestID, "account_id", credential.ID, "provider", credential.Provider, "status", response.StatusCode, "upstream_code", lastFailure.UpstreamCode, "account_scoped", lastFailure.AccountScoped)
if !lastFailure.AccountScoped {
failureFingerprints[lastFailure.Fingerprint]++
if failureFingerprints[lastFailure.Fingerprint] >= 2 {
break
}
}
continue
}
if response.StatusCode >= 200 && response.StatusCode < 300 {
@@ -377,6 +421,24 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
}
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
}
if lastFailure != nil {
record := auditBase
record.StatusCode = lastFailure.HTTPStatus
record.DurationMS = time.Since(startedAt).Milliseconds()
record.ErrorCode = lastFailure.AuditCode()
record.CreatedAt = time.Now().UTC()
if lastFailure.AccountID != 0 {
accountID := lastFailure.AccountID
record.AccountID = &accountID
record.AccountName = lastFailure.AccountName
}
persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout)
defer cancel()
if err := s.audits.Create(persistCtx, record); err != nil {
s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", input.RequestID, "error", err)
}
return nil, lastFailure
}
if lastErr == nil {
lastErr = ErrNoAvailableAccount
}
@@ -157,6 +157,86 @@ func TestParseFreeQuotaExhaustion(t *testing.T) {
}
}
func TestGatewayPreservesRepeatedSystemicForbiddenWithoutCoolingAccounts(t *testing.T) {
ctx := context.Background()
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "systemic-forbidden.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)
keyRepo := relational.NewClientKeyRepository(database)
credentials := make([]account.Credential, 0, 3)
for index, name := range []string{"first", "second", "third"} {
credential, _, createErr := accountRepo.UpsertByIdentity(ctx, account.Credential{
Provider: account.ProviderBuild, Name: name, SourceKey: name, EncryptedAccessToken: name,
ExpiresAt: time.Now().Add(time.Hour), Enabled: true, AuthStatus: account.AuthStatusActive,
Priority: 300 - index, MaxConcurrent: 1,
})
if createErr != nil {
t.Fatal(createErr)
}
credentials = append(credentials, credential)
}
if err := modelRepo.UpsertDiscovered(ctx, account.ProviderBuild, []string{"grok-systemic"}); err != nil {
t.Fatal(err)
}
for _, credential := range credentials {
if err := modelRepo.ReplaceAccountCapabilities(ctx, credential.ID, []string{"grok-systemic"}, time.Now().UTC()); err != nil {
t.Fatal(err)
}
}
clientKey, err := keyRepo.Create(ctx, clientkey.Key{
Name: "systemic-key", Prefix: "systemic", SecretHash: strings.Repeat("a", 64), EncryptedSecret: "encrypted",
Enabled: true, RPMLimit: 120, MaxConcurrent: 8,
})
if err != nil {
t.Fatal(err)
}
adapter := &systemicForbiddenAdapter{}
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, 3)
_, err = service.CreateResponse(ctx, Input{
RequestID: "req-systemic-403", ClientKey: clientKey, PublicModel: "grok-systemic",
Body: []byte(`{"model":"grok-systemic","input":"hello"}`),
})
var upstreamFailure *UpstreamFailure
if !errors.As(err, &upstreamFailure) || errors.Is(err, ErrNoAvailableAccount) {
t.Fatalf("error = %T %v", err, err)
}
if upstreamFailure.HTTPStatus != http.StatusForbidden || upstreamFailure.Code != "upstream_forbidden" || upstreamFailure.AccountScoped {
t.Fatalf("upstream failure = %#v", upstreamFailure)
}
attempts := adapter.Attempts()
if len(attempts) != 2 || attempts[0] != credentials[0].ID || attempts[1] != credentials[1].ID {
t.Fatalf("attempts = %#v", attempts)
}
for _, credential := range credentials {
observed, getErr := accountRepo.Get(ctx, credential.ID)
if getErr != nil {
t.Fatal(getErr)
}
if observed.FailureCount != 0 || observed.CooldownUntil != nil || observed.AuthStatus != account.AuthStatusActive {
t.Fatalf("account %d was incorrectly penalized: %#v", credential.ID, observed)
}
}
logs, total, err := auditRepo.List(ctx, 0, 10)
if err != nil || total != 1 || logs[0].StatusCode != http.StatusForbidden || logs[0].ErrorCode != "upstream_forbidden" || logs[0].AccountID == nil || *logs[0].AccountID != credentials[1].ID {
t.Fatalf("audit = %#v, total=%d, err=%v", logs, total, err)
}
}
func TestWebRateLimitExhaustsOnlyRequestedQuotaMode(t *testing.T) {
ctx := context.Background()
database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "web-rate-limit.db"))
@@ -510,6 +590,27 @@ type failoverAdapter struct {
resourceStatus int
}
type systemicForbiddenAdapter struct {
mu sync.Mutex
attempts []uint64
}
func (a *systemicForbiddenAdapter) Provider() account.Provider { return account.ProviderBuild }
func (a *systemicForbiddenAdapter) ForwardResponse(_ context.Context, request provider.ResponseResourceRequest) (*provider.Response, error) {
a.mu.Lock()
a.attempts = append(a.attempts, request.Credential.ID)
a.mu.Unlock()
return &provider.Response{
StatusCode: http.StatusForbidden, Status: "403 Forbidden", Header: make(http.Header),
Body: io.NopCloser(strings.NewReader(`{"error":"upstream policy rejected request"}`)),
}, nil
}
func (a *systemicForbiddenAdapter) Attempts() []uint64 {
a.mu.Lock()
defer a.mu.Unlock()
return append([]uint64(nil), a.attempts...)
}
type webRateLimitAdapter struct{}
type webImageStreamAdapter struct {
@@ -187,7 +187,7 @@ func TestReplaceProviderRoutesCanRenameUpstreamModels(t *testing.T) {
}
}
func TestManualModelRouteBindingsAndDeletionSuppression(t *testing.T) {
func TestManualModelRouteBindingsAndRediscovery(t *testing.T) {
ctx := context.Background()
database := openTestDatabase(t)
models := NewModelRepository(database)
@@ -231,21 +231,17 @@ func TestManualModelRouteBindingsAndDeletionSuppression(t *testing.T) {
if err := models.Delete(ctx, created.ID); err != nil {
t.Fatal(err)
}
if err := models.ReplaceAccountCapabilities(ctx, first.ID, []string{created.UpstreamModel}, time.Now().UTC()); err != nil {
t.Fatal(err)
}
if err := models.UpsertDiscovered(ctx, account.ProviderBuild, []string{created.UpstreamModel}); err != nil {
t.Fatal(err)
}
if _, err := models.GetByPublicID(ctx, created.PublicID); !errors.Is(err, repository.ErrNotFound) {
t.Fatalf("deleted route was rediscovered: %v", err)
}
recreated, err := models.Create(ctx, model.Route{
PublicID: created.PublicID, Provider: account.ProviderBuild, UpstreamModel: created.UpstreamModel,
Capability: model.CapabilityResponses, Enabled: true,
}, []uint64{second.ID})
recreated, err := models.GetByPublicID(ctx, created.UpstreamModel)
if err != nil {
t.Fatal(err)
t.Fatalf("deleted route was not rediscovered: %v", err)
}
if len(recreated.BoundAccountIDs) != 1 || recreated.BoundAccountIDs[0] != second.ID {
if recreated.ID == created.ID || recreated.PublicID != created.UpstreamModel || recreated.Origin != model.OriginDiscovered || len(recreated.BoundAccountIDs) != 0 {
t.Fatalf("recreated route = %#v", recreated)
}
}
@@ -273,7 +269,7 @@ func TestManualWebRouteSurvivesCatalogReconciliation(t *testing.T) {
}
}
func TestBatchDeleteModelRoutesSuppressesRediscovery(t *testing.T) {
func TestBatchDeleteModelRoutesAllowsRediscovery(t *testing.T) {
ctx := context.Background()
database := openTestDatabase(t)
repo := NewModelRepository(database)
@@ -300,7 +296,37 @@ func TestBatchDeleteModelRoutesSuppressesRediscovery(t *testing.T) {
}
for _, value := range []model.Route{first, second} {
if _, err := repo.Get(ctx, value.ID); !errors.Is(err, repository.ErrNotFound) {
t.Fatalf("route %d was rediscovered: %v", value.ID, err)
t.Fatalf("deleted route %d still exists: %v", value.ID, err)
}
items, total, err := repo.List(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 10, Search: value.UpstreamModel}})
if err != nil || total != 1 || len(items) != 1 || items[0].ID == value.ID || items[0].UpstreamModel != value.UpstreamModel {
t.Fatalf("rediscovered route for %s = %#v, total=%d, err=%v", value.UpstreamModel, items, total, err)
}
}
}
func TestWebRediscoveryRestoresCatalogRouteDefaults(t *testing.T) {
ctx := context.Background()
database := openTestDatabase(t)
repo := NewModelRepository(database)
value, err := repo.Create(ctx, model.Route{
PublicID: "grok-imagine-image-edit", Provider: account.ProviderWeb, UpstreamModel: "imagine-image-edit",
Capability: model.CapabilityImageEdit, Enabled: true,
}, nil)
if err != nil {
t.Fatal(err)
}
if err := repo.Delete(ctx, value.ID); err != nil {
t.Fatal(err)
}
if err := repo.UpsertDiscovered(ctx, account.ProviderWeb, []string{value.UpstreamModel}); err != nil {
t.Fatal(err)
}
items, total, err := repo.List(ctx, repository.ModelListQuery{Page: repository.PageQuery{Limit: 10, Search: value.UpstreamModel}})
if err != nil || total != 1 || len(items) != 1 {
t.Fatalf("rediscovered web route = %#v, total=%d, err=%v", items, total, err)
}
if items[0].PublicID != value.PublicID || items[0].Capability != model.CapabilityImageEdit || items[0].Origin != model.OriginDiscovered {
t.Fatalf("rediscovered web route defaults = %#v", items[0])
}
}
@@ -165,14 +165,6 @@ func (r *ModelRepository) HasSuccessfulAccountSync(ctx context.Context, accountI
func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account.Provider, upstreamModels []string) error {
return r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var suppressions []modelRouteSuppressionModel
if err := tx.Where("provider = ?", provider).Find(&suppressions).Error; err != nil {
return err
}
suppressed := make(map[string]bool, len(suppressions))
for _, value := range suppressions {
suppressed[value.UpstreamModel] = true
}
var existing []modelRouteModel
if err := tx.Where("provider = ? OR public_id IN ?", provider, upstreamModels).Find(&existing).Error; err != nil {
return err
@@ -187,18 +179,14 @@ func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account
}
rows := make([]modelRouteModel, 0, len(upstreamModels))
for _, upstreamModel := range upstreamModels {
if existingUpstream[upstreamModel] || suppressed[upstreamModel] {
if existingUpstream[upstreamModel] {
continue
}
publicID := upstreamModel
publicID, capability := discoveredRouteDefaults(provider, upstreamModel)
if publicIDs[publicID] {
publicID = fmt.Sprintf("%s/%s", provider, upstreamModel)
}
publicIDs[publicID] = true
capability := model.CapabilityResponses
if provider == account.ProviderWeb {
capability = model.CapabilityChat
}
rows = append(rows, modelRouteModel{PublicID: publicID, Provider: string(provider), UpstreamModel: upstreamModel, Capability: string(capability), Origin: string(model.OriginDiscovered), Enabled: true})
}
if len(rows) > 0 {
@@ -209,6 +197,22 @@ func (r *ModelRepository) UpsertDiscovered(ctx context.Context, provider account
})
}
func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (string, model.Capability) {
if provider != account.ProviderWeb {
return upstreamModel, model.CapabilityResponses
}
switch upstreamModel {
case "grok-imagine-image", "grok-imagine-image-quality":
return upstreamModel, model.CapabilityImage
case "imagine-image-edit":
return "grok-imagine-image-edit", model.CapabilityImageEdit
case "grok-imagine-video":
return upstreamModel, model.CapabilityVideo
default:
return upstreamModel, model.CapabilityChat
}
}
func (r *ModelRepository) UpsertRoutes(ctx context.Context, values []model.Route) error {
return r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
for _, value := range values {
@@ -243,20 +247,6 @@ func (r *ModelRepository) ReplaceProviderRoutes(ctx context.Context, provider ac
return fmt.Errorf("模型路由目录包含无效条目")
}
}
var suppressions []modelRouteSuppressionModel
if err := tx.Where("provider = ?", provider).Find(&suppressions).Error; err != nil {
return err
}
suppressed := make(map[string]bool, len(suppressions))
for _, value := range suppressions {
suppressed[value.UpstreamModel] = true
}
catalog := make([]model.Route, 0, len(values))
for _, value := range values {
if !suppressed[value.UpstreamModel] {
catalog = append(catalog, value)
}
}
var existing []modelRouteModel
if err := tx.Where("provider = ?", provider).Find(&existing).Error; err != nil {
return err
@@ -268,9 +258,9 @@ func (r *ModelRepository) ReplaceProviderRoutes(ctx context.Context, provider ac
byUpstream[row.UpstreamModel] = row
byPublicID[row.PublicID] = row
}
matched := make(map[int]modelRouteModel, len(catalog))
usedIDs := make(map[uint64]bool, len(catalog))
for index, value := range catalog {
matched := make(map[int]modelRouteModel, len(values))
usedIDs := make(map[uint64]bool, len(values))
for index, value := range values {
row, ok := byUpstream[value.UpstreamModel]
if !ok || usedIDs[row.ID] {
row, ok = byPublicID[value.PublicID]
@@ -299,7 +289,7 @@ func (r *ModelRepository) ReplaceProviderRoutes(ctx context.Context, provider ac
return mapError(err)
}
}
for index, value := range catalog {
for index, value := range values {
updates := map[string]any{
"public_id": value.PublicID,
"upstream_model": value.UpstreamModel,
@@ -352,7 +342,7 @@ func (r *ModelRepository) Create(ctx context.Context, value model.Route, account
if err := replaceModelRouteAccounts(tx, row.ID, accountIDs); err != nil {
return err
}
return tx.Where("provider = ? AND upstream_model = ?", row.Provider, row.UpstreamModel).Delete(&modelRouteSuppressionModel{}).Error
return nil
})
if err != nil {
return model.Route{}, err
@@ -390,58 +380,22 @@ func (r *ModelRepository) Update(ctx context.Context, value model.Route, account
}
func (r *ModelRepository) Delete(ctx context.Context, id uint64) error {
return r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var row modelRouteModel
if err := tx.First(&row, id).Error; err != nil {
return mapError(err)
}
suppression := modelRouteSuppressionModel{Provider: row.Provider, UpstreamModel: row.UpstreamModel, CreatedAt: time.Now().UTC()}
if err := tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "provider"}, {Name: "upstream_model"}},
DoUpdates: clause.AssignmentColumns([]string{"created_at"}),
}).Create(&suppression).Error; err != nil {
return err
}
result := tx.Delete(&modelRouteModel{}, id)
if result.Error != nil {
return mapError(result.Error)
}
if result.RowsAffected == 0 {
return repository.ErrNotFound
}
return nil
})
result := r.db.db.WithContext(ctx).Delete(&modelRouteModel{}, id)
if result.Error != nil {
return mapError(result.Error)
}
if result.RowsAffected == 0 {
return repository.ErrNotFound
}
return nil
}
func (r *ModelRepository) DeleteMany(ctx context.Context, ids []uint64) (int64, error) {
if len(ids) == 0 {
return 0, nil
}
var deleted int64
err := r.db.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
var rows []modelRouteModel
if err := tx.Where("id IN ?", ids).Find(&rows).Error; err != nil {
return err
}
if len(rows) == 0 {
return nil
}
now := time.Now().UTC()
suppressions := make([]modelRouteSuppressionModel, 0, len(rows))
for _, row := range rows {
suppressions = append(suppressions, modelRouteSuppressionModel{Provider: row.Provider, UpstreamModel: row.UpstreamModel, CreatedAt: now})
}
if err := tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "provider"}, {Name: "upstream_model"}},
DoUpdates: clause.AssignmentColumns([]string{"created_at"}),
}).CreateInBatches(suppressions, 200).Error; err != nil {
return err
}
result := tx.Where("id IN ?", ids).Delete(&modelRouteModel{})
deleted = result.RowsAffected
return mapError(result.Error)
})
return deleted, err
result := r.db.db.WithContext(ctx).Where("id IN ?", ids).Delete(&modelRouteModel{})
return result.RowsAffected, mapError(result.Error)
}
func replaceModelRouteAccounts(tx *gorm.DB, routeID uint64, accountIDs []uint64) error {
@@ -163,14 +163,6 @@ type modelRouteAccountModel struct {
func (modelRouteAccountModel) TableName() string { return "model_route_accounts" }
type modelRouteSuppressionModel struct {
Provider string `gorm:"size:32;primaryKey;check:chk_model_route_suppressions_provider,provider IN ('grok_build','grok_web')"`
UpstreamModel string `gorm:"size:255;primaryKey;check:chk_model_route_suppressions_model,length(trim(upstream_model)) BETWEEN 1 AND 255"`
CreatedAt time.Time `gorm:"not null"`
}
func (modelRouteSuppressionModel) TableName() string { return "model_route_suppressions" }
type accountModelCapabilityModel struct {
AccountID uint64 `gorm:"primaryKey"`
UpstreamModel string `gorm:"size:255;primaryKey;not null;check:chk_account_model_capabilities_model,length(trim(upstream_model)) BETWEEN 1 AND 255"`
@@ -17,7 +17,6 @@ var schemaModels = []any{
&quotaRecoveryModel{},
&modelRouteModel{},
&modelRouteAccountModel{},
&modelRouteSuppressionModel{},
&accountModelCapabilityModel{},
&accountModelSyncStateModel{},
&clientKeyModel{},
+158 -19
View File
@@ -2,7 +2,10 @@ package cli
import (
"bytes"
"compress/gzip"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -30,18 +33,25 @@ type Config struct {
// Adapter 实现 Grok Build CLI Responses、模型、Billing 与 OAuth 协议。
type Adapter struct {
cfgMu sync.RWMutex
cfg Config
http *http.Client
oauth *oauthClient
cipher *security.Cipher
base http.RoundTripper
cfgMu sync.RWMutex
cfg Config
http *http.Client
oauth *oauthClient
cipher *security.Cipher
base http.RoundTripper
identityMu sync.Mutex
identities map[uint64]clientIdentity
}
type clientIdentity struct {
agentID string
sessionID string
}
func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter {
transport := &http.Transport{Proxy: http.ProxyFromEnvironment, ForceAttemptHTTP2: true, MaxIdleConns: 256, MaxIdleConnsPerHost: 128, MaxConnsPerHost: 256, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: 30 * time.Second}
httpClient := &http.Client{Transport: transport}
return &Adapter{cfg: cfg, http: httpClient, oauth: newOAuthClient(httpClient), cipher: cipher, base: transport}
return &Adapter{cfg: cfg, http: httpClient, oauth: newOAuthClient(httpClient), cipher: cipher, base: transport, identities: make(map[uint64]clientIdentity)}
}
func (a *Adapter) SetEgress(manager *infraegress.Manager) {
@@ -71,9 +81,10 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
}
body := request.Body
var toolCompatibility *responsesToolCompatibility
var conversationOptions conversation.ResponseOptions
if request.NormalizeBody {
if request.Operation == conversation.OperationChat || request.Operation == conversation.OperationMessages {
body, err = conversation.ConvertRequest(body, request.Model, request.Operation)
body, conversationOptions, err = conversation.ConvertRequestWithOptions(body, request.Model, request.Operation)
} else {
body, toolCompatibility, err = normalizeResponsesRequest(body, request.Model)
}
@@ -92,12 +103,15 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
if err != nil {
return nil, err
}
a.applyHeaders(req, accessToken, request.Model, request.PromptCacheKey)
if err := a.applyHeaders(req, request.Credential, accessToken, request.Model, request.PromptCacheKey, true); err != nil {
return nil, err
}
if len(body) > 0 {
req.Header.Set("Content-Type", "application/json")
}
if request.Streaming {
req.Header.Set("Accept", "text/event-stream")
req.Header.Set("Accept-Encoding", "identity")
} else {
req.Header.Set("Accept", "application/json")
}
@@ -108,7 +122,15 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
if err != nil {
return nil, err
}
if err := normalizeGzipResponse(resp); err != nil {
return nil, err
}
responsesOperation := request.Operation == "" || request.Operation == conversation.OperationResponses
if responsesOperation && toolCompatibility != nil {
if warnings := toolCompatibility.warningHeader(); warnings != "" {
resp.Header.Set("X-Grok2API-Compatibility-Warnings", warnings)
}
}
if responsesOperation && toolCompatibility != nil && resp.StatusCode >= 200 && resp.StatusCode < 300 {
if request.Streaming {
resp.Body = toolCompatibility.normalizeResponseStream(resp.Body)
@@ -134,7 +156,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
}
if request.Operation == conversation.OperationChat || request.Operation == conversation.OperationMessages {
if request.Streaming && resp.StatusCode >= 200 && resp.StatusCode < 300 {
resp.Body = conversation.ConvertResponseStream(resp.Body, request.Operation)
resp.Body = conversation.ConvertResponseStreamWithOptions(resp.Body, request.Operation, conversationOptions)
resp.Header.Del("Content-Length")
resp.Header.Set("Content-Type", "text/event-stream")
} else {
@@ -146,7 +168,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
if len(data) > 64<<20 {
return nil, fmt.Errorf("上游对话响应超过 64 MiB")
}
converted, convertErr := conversation.ConvertResponseJSON(data, request.Operation)
converted, convertErr := conversation.ConvertResponseJSONWithOptions(data, request.Operation, conversationOptions)
if convertErr != nil {
return nil, convertErr
}
@@ -203,11 +225,16 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential)
if err != nil {
return nil, err
}
a.applyHeaders(req, accessToken, "", "")
if err := a.applyHeaders(req, credential, accessToken, "", "", false); err != nil {
return nil, err
}
resp, err := a.http.Do(req)
if err != nil {
return nil, err
}
if err := normalizeGzipResponse(resp); err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
@@ -238,12 +265,12 @@ func (a *Adapter) GetBilling(ctx context.Context, credential account.Credential)
if err != nil {
return account.Billing{}, err
}
monthly, err := a.getBilling(ctx, accessToken, "")
monthly, err := a.getBilling(ctx, credential, accessToken, "")
if err != nil {
return account.Billing{}, err
}
monthly.AccountID = credential.ID
if credits, creditsErr := a.getBilling(ctx, accessToken, "format=credits"); creditsErr == nil {
if credits, creditsErr := a.getBilling(ctx, credential, accessToken, "format=credits"); creditsErr == nil {
monthly = mergeBillingSnapshots(monthly, credits)
}
monthly.SyncedAt = time.Now().UTC()
@@ -313,26 +340,133 @@ func (a *Adapter) MarshalCredentials(values []provider.CredentialSeed) ([]byte,
return marshalCredentials(values)
}
func (a *Adapter) applyHeaders(req *http.Request, accessToken, model, promptCacheKey string) {
func (a *Adapter) applyHeaders(req *http.Request, credential account.Credential, accessToken, model, promptCacheKey string, trace bool) error {
cfg := a.config()
identity, err := a.clientIdentity(credential.ID)
if err != nil {
return err
}
requestID, err := randomHex(16)
if err != nil {
return err
}
conversationID := strings.TrimSpace(promptCacheKey)
if conversationID == "" {
conversationID, err = randomHex(16)
if err != nil {
return err
}
}
req.Header.Set("Authorization", "Bearer "+accessToken)
req.Header.Set("X-XAI-Token-Auth", cfg.TokenAuth)
req.Header.Set("x-grok-client-version", cfg.ClientVersion)
req.Header.Set("x-grok-client-identifier", cfg.ClientIdentifier)
req.Header.Set("x-grok-client-surface", "tui")
req.Header.Set("x-grok-client-name", cfg.ClientIdentifier)
req.Header.Set("x-grok-agent-id", identity.agentID)
req.Header.Set("x-grok-session-id", identity.sessionID)
req.Header.Set("x-grok-conv-id", conversationID)
req.Header.Set("x-grok-req-id", requestID)
req.Header.Set("x-grok-conversation-id", conversationID)
req.Header.Set("x-grok-session-id-legacy", identity.sessionID)
req.Header.Set("x-grok-request-id", requestID)
if credential.UserID != "" {
req.Header.Set("x-userid", credential.UserID)
}
if trace {
traceID, traceErr := randomHex(16)
if traceErr != nil {
return traceErr
}
spanID, spanErr := randomHex(8)
if spanErr != nil {
return spanErr
}
req.Header.Set("traceparent", "00-"+traceID+"-"+spanID+"-01")
req.Header.Set("tracestate", "")
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Encoding", "gzip")
req.Header.Set("User-Agent", cfg.UserAgent)
if model != "" {
req.Header.Set("x-grok-model-override", model)
}
if promptCacheKey != "" {
req.Header.Set("x-grok-conv-id", promptCacheKey)
return nil
}
func (a *Adapter) clientIdentity(accountID uint64) (clientIdentity, error) {
a.identityMu.Lock()
defer a.identityMu.Unlock()
if value, ok := a.identities[accountID]; ok {
return value, nil
}
agentID, err := randomHex(16)
if err != nil {
return clientIdentity{}, err
}
sessionID, err := randomUUID()
if err != nil {
return clientIdentity{}, err
}
value := clientIdentity{agentID: agentID, sessionID: sessionID}
a.identities[accountID] = value
return value, nil
}
func randomHex(bytesLength int) (string, error) {
value := make([]byte, bytesLength)
if _, err := rand.Read(value); err != nil {
return "", err
}
return hex.EncodeToString(value), nil
}
func randomUUID() (string, error) {
value := make([]byte, 16)
if _, err := rand.Read(value); err != nil {
return "", err
}
value[6] = (value[6] & 0x0f) | 0x40
value[8] = (value[8] & 0x3f) | 0x80
hexValue := hex.EncodeToString(value)
return hexValue[0:8] + "-" + hexValue[8:12] + "-" + hexValue[12:16] + "-" + hexValue[16:20] + "-" + hexValue[20:], nil
}
func normalizeGzipResponse(response *http.Response) error {
if response == nil || response.Body == nil || !strings.EqualFold(strings.TrimSpace(response.Header.Get("Content-Encoding")), "gzip") {
return nil
}
reader, err := gzip.NewReader(response.Body)
if err != nil {
_ = response.Body.Close()
return err
}
response.Body = &gzipResponseBody{Reader: reader, source: response.Body}
response.Header.Del("Content-Encoding")
response.Header.Del("Content-Length")
response.ContentLength = -1
return nil
}
type gzipResponseBody struct {
*gzip.Reader
source io.Closer
}
func (b *gzipResponseBody) Close() error {
readerErr := b.Reader.Close()
sourceErr := b.source.Close()
if readerErr != nil {
return readerErr
}
return sourceErr
}
func (a *Adapter) url(path string) string {
return strings.TrimRight(a.config().BaseURL, "/") + "/" + strings.TrimLeft(path, "/")
}
func (a *Adapter) getBilling(ctx context.Context, accessToken, query string) (account.Billing, error) {
func (a *Adapter) getBilling(ctx context.Context, credential account.Credential, accessToken, query string) (account.Billing, error) {
endpoint := a.url("/billing")
if query != "" {
endpoint += "?" + query
@@ -341,11 +475,16 @@ func (a *Adapter) getBilling(ctx context.Context, accessToken, query string) (ac
if err != nil {
return account.Billing{}, err
}
a.applyHeaders(req, accessToken, "", "")
if err := a.applyHeaders(req, credential, accessToken, "", "", false); err != nil {
return account.Billing{}, err
}
resp, err := a.http.Do(req)
if err != nil {
return account.Billing{}, err
}
if err := normalizeGzipResponse(resp); err != nil {
return account.Billing{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(io.LimitReader(resp.Body, 2<<20))
if err != nil {
@@ -1,6 +1,8 @@
package cli
import (
"bytes"
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
@@ -30,6 +32,20 @@ func TestForwardResponseMatchesGrokBuildHeadersAndPreservesReasoning(t *testing.
if r.Header.Get("Authorization") != "Bearer access-token" || r.Header.Get("x-grok-client-version") != "0.2.99" || r.Header.Get("x-grok-client-identifier") != "grok-shell" || r.Header.Get("User-Agent") != "grok-shell/0.2.99 (linux; x86_64)" || r.Header.Get("x-grok-conv-id") != "official-key" {
t.Fatalf("headers = %#v", r.Header)
}
requestID := r.Header.Get("x-grok-req-id")
sessionID := r.Header.Get("x-grok-session-id")
if r.Header.Get("x-grok-client-surface") != "tui" || r.Header.Get("x-grok-client-name") != "grok-shell" || len(r.Header.Get("x-grok-agent-id")) != 32 || len(sessionID) != 36 {
t.Fatalf("client identity headers = %#v", r.Header)
}
if r.Header.Get("x-grok-conversation-id") != "official-key" || len(requestID) != 32 || r.Header.Get("x-grok-request-id") != requestID || r.Header.Get("x-grok-session-id-legacy") != sessionID {
t.Fatalf("request identity headers = %#v", r.Header)
}
if r.Header.Get("x-userid") != "user-123" || r.Header.Get("Accept-Encoding") != "gzip" || len(r.Header.Get("traceparent")) != 55 {
t.Fatalf("protocol headers = %#v", r.Header)
}
if values, ok := r.Header["Tracestate"]; !ok || len(values) != 1 || values[0] != "" {
t.Fatalf("tracestate = %#v", values)
}
body, _ := io.ReadAll(r.Body)
if err := json.Unmarshal(body, &captured); err != nil {
t.Fatal(err)
@@ -54,7 +70,7 @@ func TestForwardResponseMatchesGrokBuildHeadersAndPreservesReasoning(t *testing.
adapter := NewAdapter(Config{BaseURL: "https://api.x.ai/v1", ClientVersion: "0.2.99", ClientIdentifier: "grok-shell", TokenAuth: "xai-grok-cli", UserAgent: "grok-shell/0.2.99 (linux; x86_64)"}, cipher)
adapter.http.Transport = transport
response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
Credential: account.Credential{EncryptedAccessToken: encrypted}, Method: http.MethodPost, Path: "/responses",
Credential: account.Credential{ID: 7, UserID: "user-123", EncryptedAccessToken: encrypted}, Method: http.MethodPost, Path: "/responses",
Model: "grok-4.5", PromptCacheKey: "official-key", NormalizeBody: true,
Body: []byte(`{"model":"public","prompt_cache_key":"official-key","input":[{"type":"reasoning","id":"rs_1","encrypted_content":"cipher"}]}`),
})
@@ -107,6 +123,50 @@ func TestForwardResponseSupportsResourceMethodsAndQuery(t *testing.T) {
}
}
func TestForwardResponseDecodesExplicitGzipResponse(t *testing.T) {
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
if err != nil {
t.Fatal(err)
}
encrypted, err := cipher.Encrypt("access-token")
if err != nil {
t.Fatal(err)
}
var compressed bytes.Buffer
writer := gzip.NewWriter(&compressed)
if _, err := writer.Write([]byte(`{"id":"resp_gzip"}`)); err != nil {
t.Fatal(err)
}
if err := writer.Close(); err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1"}, cipher)
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
if request.Header.Get("Accept-Encoding") != "gzip" {
t.Fatalf("Accept-Encoding = %q", request.Header.Get("Accept-Encoding"))
}
return &http.Response{
StatusCode: http.StatusOK, Status: "200 OK",
Header: http.Header{"Content-Encoding": []string{"gzip"}, "Content-Length": []string{"999"}},
Body: io.NopCloser(bytes.NewReader(compressed.Bytes())), Request: request,
}, nil
})
response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
Credential: account.Credential{ID: 8, EncryptedAccessToken: encrypted}, Method: http.MethodPost, Path: "/responses",
})
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
t.Fatal(err)
}
if string(body) != `{"id":"resp_gzip"}` || response.Header.Get("Content-Encoding") != "" || response.Header.Get("Content-Length") != "" {
t.Fatalf("body=%q headers=%#v", body, response.Header)
}
}
func TestForwardResponseRejectsHostedToolSearchBeforeUpstream(t *testing.T) {
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
if err != nil {
@@ -194,6 +254,9 @@ func TestForwardResponseRestoresNamespaceResponse(t *testing.T) {
t.Fatal(err)
}
defer response.Body.Close()
if response.Header.Get("X-Grok2API-Compatibility-Warnings") != "namespace_flattened" {
t.Fatalf("compatibility warnings = %q", response.Header.Get("X-Grok2API-Compatibility-Warnings"))
}
var payload map[string]any
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
t.Fatal(err)
@@ -207,3 +270,58 @@ func TestForwardResponseRestoresNamespaceResponse(t *testing.T) {
t.Fatalf("下游 tools = %#v", tools)
}
}
func TestForwardResponsePreservesClaudeCodeMessagesOptions(t *testing.T) {
cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32)))
if err != nil {
t.Fatal(err)
}
encrypted, err := cipher.Encrypt("access-token")
if err != nil {
t.Fatal(err)
}
adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1"}, cipher)
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
var payload map[string]any
if err := json.NewDecoder(request.Body).Decode(&payload); err != nil {
t.Fatal(err)
}
if payload["instructions"] != "legacy system" || payload["store"] != false || payload["reasoning"].(map[string]any)["effort"] != "high" {
t.Fatalf("upstream payload = %#v", payload)
}
return &http.Response{
StatusCode: http.StatusOK, Status: "200 OK", Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{
"id":"resp_1","model":"grok-4.5","status":"completed",
"output":[
{"type":"reasoning","summary":[{"type":"summary_text","text":"thought"}],"encrypted_content":"signature"},
{"type":"message","content":[{"type":"output_text","text":"ABCSTOPXYZ"}]}
]
}`)),
Request: request,
}, nil
})
response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{
Credential: account.Credential{EncryptedAccessToken: encrypted},
Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", NormalizeBody: true,
Operation: conversation.OperationMessages,
Body: []byte(`{
"model":"public","max_tokens":256,"stop_sequences":["STOP"],
"thinking":{"type":"enabled","budget_tokens":20000},
"messages":[{"role":"system","content":"legacy system"},{"role":"user","content":"hello"}]
}`),
})
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
var payload map[string]any
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
t.Fatal(err)
}
content := payload["content"].([]any)
if payload["stop_reason"] != "stop_sequence" || payload["stop_sequence"] != "STOP" || content[0].(map[string]any)["type"] != "thinking" || content[1].(map[string]any)["text"] != "ABC" {
t.Fatalf("messages response = %#v", payload)
}
}
@@ -146,13 +146,49 @@ func TestResponsesWebSearchAliasesAndOptions(t *testing.T) {
t.Fatalf("web search alias = %#v, choice = %#v", tool, request["tool_choice"])
}
normalized, compatibility, err = normalizeResponsesRequest([]byte(`{
"model":"public","input":"search",
"tools":[{"type":"web_search","external_web_access":true,"indexed_web_access":true,"search_content_types":["text"],"search_context_size":"low","user_location":{"type":"approximate","country":"CN"},"filters":{"allowed_domains":[]}}]
}`), "grok-4.5")
if err != nil {
t.Fatal(err)
}
if compatibility == nil {
t.Fatal("Codex web_search 控制字段未启用兼容层")
}
if err := json.Unmarshal(normalized, &request); err != nil {
t.Fatal(err)
}
tool = request["tools"].([]any)[0].(map[string]any)
if len(tool) != 1 || tool["type"] != "web_search" {
t.Fatalf("Codex web search 未降级: %#v", tool)
}
if !strings.Contains(compatibility.warningHeader(), "web_search_controls_downgraded") {
t.Fatalf("compatibility warnings = %q", compatibility.warningHeader())
}
for _, restricted := range []string{
`{"external_web_access":false}`,
`{"filters":{"allowed_domains":["example.com"]}}`,
`{"allowed_domains":["example.com"]}`,
`{"search_content_types":["image"]}`,
} {
_, _, err = normalizeResponsesRequest([]byte(`{
"model":"public","input":"search","tools":[{"type":"web_search",`+strings.TrimPrefix(strings.TrimSuffix(restricted, "}"), "{")+`}]
}`), "grok-4.5")
requestErr, ok := err.(*responsesRequestError)
if !ok || requestErr.Code != "unsupported_parameter" {
t.Fatalf("restricted web search error = %#v", err)
}
}
_, _, err = normalizeResponsesRequest([]byte(`{
"model":"public","input":"search",
"tools":[{"type":"web_search","search_context_size":"low"}]
"tools":[{"type":"web_search","unknown_control":true}]
}`), "grok-4.5")
requestErr, ok := err.(*responsesRequestError)
if !ok || requestErr.Code != "unsupported_parameter" || requestErr.Param != "tools[0].search_context_size" {
t.Fatalf("web search option error = %#v", err)
if !ok || requestErr.Code != "unsupported_parameter" || requestErr.Param != "tools[0].unknown_control" {
t.Fatalf("unknown web search option error = %#v", err)
}
}
@@ -176,7 +212,17 @@ func TestResponsesBuild0299NativeAndUnsupportedToolMatrix(t *testing.T) {
})
}
unsupported := []string{"local_shell", "apply_patch", "computer_use_preview", "unknown_tool"}
compatible := []string{"local_shell", "apply_patch"}
for _, kind := range compatible {
t.Run("compatible_"+kind, func(t *testing.T) {
body := []byte(`{"model":"public","input":"hello","tools":[{"type":"` + kind + `"}]}`)
if _, compatibility, err := normalizeResponsesRequest(body, "grok-4.5"); err != nil || compatibility == nil {
t.Fatalf("compatibility=%#v error=%v", compatibility, err)
}
})
}
unsupported := []string{"computer_use_preview", "unknown_tool"}
for _, kind := range unsupported {
t.Run("unsupported_"+kind, func(t *testing.T) {
body := []byte(`{"model":"public","input":"hello","tools":[{"type":"` + kind + `"}]}`)
@@ -241,11 +287,12 @@ func TestResponsesMCPDeferLoadingUsesClientToolSearch(t *testing.T) {
}
}
func TestResponsesCodexHistoryItemsAreVisibleOrRejected(t *testing.T) {
func TestResponsesCodexHistoryItemsAreStructuredOrVisible(t *testing.T) {
normalized, _, err := normalizeResponsesRequest([]byte(`{
"model":"public","input":[
{"type":"agent_message","author":"worker","recipient":"root","content":[{"type":"input_text","text":"analysis result"}]},
{"type":"local_shell_call","status":"completed","action":{"type":"exec","command":"pwd"}},
{"type":"local_shell_call","call_id":"shell_1","status":"completed","action":{"type":"exec","command":"pwd"}},
{"type":"local_shell_call_output","call_id":"shell_1","status":"completed","output":"/workspace\n"},
{"type":"mcp_tool_call_output","call_id":"mcp_1","output":{"content":"done"}}
]
}`), "grok-4.5")
@@ -257,22 +304,28 @@ func TestResponsesCodexHistoryItemsAreVisibleOrRejected(t *testing.T) {
t.Fatal(err)
}
items := request["input"].([]any)
if items[0].(map[string]any)["role"] != "developer" || items[1].(map[string]any)["role"] != "assistant" || items[2].(map[string]any)["role"] != "developer" {
if items[0].(map[string]any)["role"] != "developer" || items[1].(map[string]any)["type"] != "shell_call" || items[2].(map[string]any)["type"] != "shell_call_output" || items[3].(map[string]any)["role"] != "developer" {
t.Fatalf("Codex 历史转换 = %#v", items)
}
for index, expected := range []string{"Agent message", "Local shell call", "MCP tool output"} {
for index, expected := range map[int]string{0: "Agent message", 3: "MCP tool output"} {
content := items[index].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
if !strings.Contains(content, expected) {
t.Fatalf("input[%d] = %q", index, content)
}
}
_, _, err = normalizeResponsesRequest([]byte(`{
normalized, _, err = normalizeResponsesRequest([]byte(`{
"model":"public","input":[{"type":"agent_message","content":[{"type":"encrypted_text","encrypted_content":"opaque"}]}]
}`), "grok-4.5")
requestErr, ok := err.(*responsesRequestError)
if !ok || requestErr.Code != "unsupported_parameter" || requestErr.Param != "input[0].content" {
t.Fatalf("opaque agent error = %#v", err)
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(normalized, &request); err != nil {
t.Fatal(err)
}
marker := request["input"].([]any)[0].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
if !strings.Contains(marker, "encrypted inter-agent message") {
t.Fatalf("opaque agent marker = %q", marker)
}
}
@@ -0,0 +1,432 @@
package cli
import (
"encoding/json"
"fmt"
"sort"
"strings"
)
// normalizeShellTool 保留 OpenAI 新版 shell;同一请求不能同时声明新旧两套本地 shell。
func (c *responsesToolCompatibility) normalizeShellTool(tool map[string]any, param string) ([]any, error) {
if c.legacyLocalShell {
return nil, &responsesRequestError{
Message: "同一请求不能同时声明 shell 和 local_shell",
Param: param + ".type", Code: "invalid_parameter",
}
}
c.nativeShell = true
return c.normalizeNativeTool(tool, param)
}
// normalizeLegacyLocalShellTool 将旧 Codex local_shell 升级为 0.2.99 原生 local shell 环境。
func (c *responsesToolCompatibility) normalizeLegacyLocalShellTool(tool map[string]any, param string) ([]any, error) {
if c.nativeShell || c.legacyLocalShell {
return nil, &responsesRequestError{
Message: "单次请求只能声明一个 shell/local_shell 工具",
Param: param + ".type", Code: "invalid_parameter",
}
}
for key := range tool {
if key != "type" {
return nil, &responsesRequestError{
Message: "旧版 local_shell 不支持额外配置字段",
Param: param + "." + key, Code: "unsupported_parameter",
}
}
}
c.legacyLocalShell = true
c.changed = true
c.addWarning("legacy_local_shell_upgraded")
return []any{map[string]any{
"type": "shell",
"environment": map[string]any{"type": "local"},
}}, nil
}
// normalizeApplyPatchTool 将客户端执行的 apply_patch 包装为严格 function。
func (c *responsesToolCompatibility) normalizeApplyPatchTool(tool map[string]any, namespace, param string) ([]any, error) {
if namespace != "" {
return nil, &responsesRequestError{
Message: "namespace 内暂不支持 apply_patch",
Param: param + ".type", Code: "unsupported_parameter",
}
}
for key := range tool {
if key != "type" {
return nil, &responsesRequestError{
Message: "apply_patch 不接受自定义字段",
Param: param + "." + key, Code: "unsupported_parameter",
}
}
}
identity := responsesToolIdentity{Kind: responsesApplyPatchTool, Name: "apply_patch"}
c.changed = true
c.addWarning("apply_patch_emulated")
return []any{map[string]any{
"type": "function",
"name": c.alias(identity),
"description": "Create, update, or delete one file using a structured V4A patch operation. " +
"create_file and update_file require path and diff; delete_file requires path.",
"parameters": map[string]any{
"type": "object",
"properties": map[string]any{
"operation": map[string]any{
"type": "object",
"properties": map[string]any{
"type": map[string]any{"type": "string", "enum": []any{"create_file", "update_file", "delete_file"}},
"path": map[string]any{"type": "string", "minLength": 1},
"diff": map[string]any{"type": "string"},
},
"required": []any{"type", "path"}, "additionalProperties": false,
},
},
"required": []any{"operation"}, "additionalProperties": false,
},
"strict": true,
}}, nil
}
func (c *responsesToolCompatibility) normalizeApplyPatchCallInput(item map[string]any, param string) (map[string]any, error) {
callID := strings.TrimSpace(stringField(item, "call_id"))
if callID == "" {
return nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"}
}
operation, err := validateApplyPatchOperation(item["operation"], param+".operation")
if err != nil {
return nil, err
}
arguments, err := json.Marshal(map[string]any{"operation": operation})
if err != nil {
return nil, err
}
converted := map[string]any{
"type": "function_call", "call_id": callID,
"name": c.alias(responsesToolIdentity{Kind: responsesApplyPatchTool, Name: "apply_patch"}),
"arguments": string(arguments),
}
for _, key := range []string{"id", "status"} {
if value, exists := item[key]; exists {
converted[key] = cloneJSONValue(value)
}
}
return converted, nil
}
func normalizeApplyPatchOutputInput(item map[string]any, param string) (map[string]any, error) {
callID := strings.TrimSpace(stringField(item, "call_id"))
if callID == "" {
return nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"}
}
status := strings.TrimSpace(stringField(item, "status"))
if status == "" {
status = "completed"
}
if status != "completed" && status != "failed" {
return nil, &responsesRequestError{Message: "apply_patch_call_output.status 只支持 completed 或 failed", Param: param + ".status", Code: "invalid_parameter"}
}
output := ""
if value, exists := item["output"]; exists && value != nil {
if text, ok := value.(string); ok {
output = text
} else {
encoded, err := json.Marshal(value)
if err != nil {
return nil, &responsesRequestError{Message: "apply_patch_call_output.output 无法编码", Param: param + ".output", Code: "invalid_parameter"}
}
output = string(encoded)
}
}
message := "Apply patch status: " + status
if output != "" {
message += "\n" + output
}
return map[string]any{"type": "function_call_output", "call_id": callID, "output": message}, nil
}
func validateApplyPatchOperation(value any, param string) (map[string]any, error) {
operation, ok := value.(map[string]any)
if !ok {
return nil, &responsesRequestError{Message: "apply_patch operation 必须是对象", Param: param, Code: "invalid_parameter"}
}
kind := strings.TrimSpace(stringField(operation, "type"))
path := strings.TrimSpace(stringField(operation, "path"))
if path == "" {
return nil, &responsesRequestError{Message: "apply_patch operation.path 不能为空", Param: param + ".path", Code: "invalid_parameter"}
}
switch kind {
case "create_file", "update_file":
if _, ok := operation["diff"].(string); !ok {
return nil, &responsesRequestError{Message: kind + " 必须提供 diff 字符串", Param: param + ".diff", Code: "invalid_parameter"}
}
case "delete_file":
default:
return nil, &responsesRequestError{Message: "apply_patch operation.type 无效", Param: param + ".type", Code: "invalid_parameter"}
}
return cloneJSONObject(operation), nil
}
func decodeApplyPatchArguments(value any, param string) (map[string]any, error) {
text, ok := value.(string)
if !ok {
return nil, &responsesRequestError{Message: "apply_patch function arguments 必须是字符串", Param: param, Code: "invalid_parameter"}
}
var wrapper map[string]any
if err := json.Unmarshal([]byte(text), &wrapper); err != nil {
return nil, &responsesRequestError{Message: "apply_patch function arguments 不是有效 JSON", Param: param, Code: "invalid_parameter"}
}
return validateApplyPatchOperation(wrapper["operation"], param+".operation")
}
func normalizeLegacyLocalShellCallInput(item map[string]any, param string) (map[string]any, error) {
callID := strings.TrimSpace(stringField(item, "call_id"))
if callID == "" {
return nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"}
}
action, err := legacyShellAction(item["action"], param+".action")
if err != nil {
return nil, err
}
converted := map[string]any{"type": "shell_call", "call_id": callID, "action": action}
for _, key := range []string{"id", "status", "timeout_ms", "max_output_length"} {
if value, exists := item[key]; exists {
converted[key] = cloneJSONValue(value)
}
}
return converted, nil
}
func legacyShellAction(value any, param string) (map[string]any, error) {
action, ok := value.(map[string]any)
if !ok {
return nil, &responsesRequestError{Message: "local_shell_call.action 必须是对象", Param: param, Code: "invalid_parameter"}
}
if kind := strings.TrimSpace(stringField(action, "type")); kind != "" && kind != "exec" {
return nil, &responsesRequestError{Message: "local_shell_call.action.type 只支持 exec", Param: param + ".type", Code: "unsupported_parameter"}
}
command, err := legacyShellCommand(action, param)
if err != nil {
return nil, err
}
return map[string]any{"type": "exec", "commands": []any{command}}, nil
}
func legacyShellCommand(action map[string]any, param string) (string, error) {
command := ""
switch value := action["command"].(type) {
case string:
command = strings.TrimSpace(value)
case []any:
parts := make([]string, 0, len(value))
for index, raw := range value {
part, ok := raw.(string)
if !ok {
return "", &responsesRequestError{Message: "local_shell command 参数必须是字符串", Param: fmt.Sprintf("%s.command[%d]", param, index), Code: "invalid_parameter"}
}
parts = append(parts, quoteShellArgument(part))
}
command = strings.Join(parts, " ")
default:
if commands, ok := action["commands"].([]any); ok {
parts := make([]string, 0, len(commands))
for index, raw := range commands {
part, ok := raw.(string)
if !ok {
return "", &responsesRequestError{Message: "shell commands 必须是字符串", Param: fmt.Sprintf("%s.commands[%d]", param, index), Code: "invalid_parameter"}
}
parts = append(parts, part)
}
command = strings.Join(parts, "\n")
}
}
if command == "" {
return "", &responsesRequestError{Message: "local_shell_call.action.command 不能为空", Param: param + ".command", Code: "invalid_parameter"}
}
if environment, ok := action["env"].(map[string]any); ok && len(environment) > 0 {
keys := make([]string, 0, len(environment))
for key := range environment {
if !validEnvironmentName(key) {
return "", &responsesRequestError{Message: "local_shell env 名称无效", Param: param + ".env." + key, Code: "invalid_parameter"}
}
keys = append(keys, key)
}
sort.Strings(keys)
assignments := make([]string, 0, len(keys))
for _, key := range keys {
value, ok := environment[key].(string)
if !ok {
return "", &responsesRequestError{Message: "local_shell env 值必须是字符串", Param: param + ".env." + key, Code: "invalid_parameter"}
}
assignments = append(assignments, key+"="+quoteShellArgument(value))
}
command = "env " + strings.Join(assignments, " ") + " " + command
}
if directory := strings.TrimSpace(stringField(action, "working_directory")); directory != "" {
command = "cd " + quoteShellArgument(directory) + " && " + command
}
return command, nil
}
func normalizeLegacyLocalShellOutputInput(item map[string]any, param string) (map[string]any, error) {
callID := strings.TrimSpace(stringField(item, "call_id"))
if callID == "" {
return nil, &responsesRequestError{Message: param + ".call_id 不能为空", Param: param + ".call_id", Code: "invalid_parameter"}
}
var output []any
switch value := item["output"].(type) {
case []any:
output = cloneJSONArray(value)
case string:
exitCode := 0
if strings.EqualFold(stringField(item, "status"), "failed") {
exitCode = 1
}
if number, ok := item["exit_code"].(float64); ok {
exitCode = int(number)
}
output = []any{map[string]any{
"stdout": value, "stderr": "",
"outcome": map[string]any{"type": "exit", "exit_code": exitCode},
}}
default:
return nil, &responsesRequestError{Message: "local_shell_call_output.output 必须是字符串或数组", Param: param + ".output", Code: "invalid_parameter"}
}
converted := map[string]any{"type": "shell_call_output", "call_id": callID, "output": output}
if value, exists := item["max_output_length"]; exists {
converted["max_output_length"] = cloneJSONValue(value)
}
return converted, nil
}
func rewriteLegacyShellAction(value any) map[string]any {
action, _ := value.(map[string]any)
commands, _ := action["commands"].([]any)
parts := make([]string, 0, len(commands))
for _, raw := range commands {
if command, ok := raw.(string); ok {
parts = append(parts, command)
}
}
legacy := map[string]any{"type": "exec", "command": strings.Join(parts, "\n")}
return legacy
}
func quoteShellArgument(value string) string {
if value == "" {
return "''"
}
safe := true
for _, character := range value {
if !((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') ||
(character >= '0' && character <= '9') || strings.ContainsRune("_@%+=:,./-", character)) {
safe = false
break
}
}
if safe {
return value
}
return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'"
}
func validEnvironmentName(value string) bool {
if value == "" {
return false
}
for index, character := range value {
if !((character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') || character == '_' || (index > 0 && character >= '0' && character <= '9')) {
return false
}
}
return true
}
func (c *responsesToolCompatibility) normalizeAdditionalToolsInput(item map[string]any, param string) (map[string]any, []any, []any, error) {
if role := strings.TrimSpace(stringField(item, "role")); role != "" && role != "developer" {
return nil, nil, nil, &responsesRequestError{Message: "additional_tools.role 只支持 developer", Param: param + ".role", Code: "unsupported_parameter"}
}
tools, ok := item["tools"].([]any)
if !ok {
return nil, nil, nil, &responsesRequestError{Message: param + ".tools 必须是数组", Param: param + ".tools", Code: "invalid_parameter"}
}
c.addWarning("additional_tools_position_approximated")
normalized := make([]any, 0, len(tools))
names := make([]string, 0, len(tools))
for index, rawTool := range tools {
converted, err := c.normalizeTool(rawTool, "", false, true, fmt.Sprintf("%s.tools[%d]", param, index))
if err != nil {
return nil, nil, nil, err
}
normalized = append(normalized, converted...)
if tool, ok := rawTool.(map[string]any); ok {
name := strings.TrimSpace(stringField(tool, "name"))
if name == "" {
name = strings.TrimSpace(stringField(tool, "server_label"))
}
if name == "" {
name = strings.TrimSpace(stringField(tool, "type"))
}
if name != "" {
names = append(names, name)
}
}
}
message := "Additional tools become available at this point in the conversation."
if len(names) > 0 {
message += "\nTools: " + strings.Join(names, ", ")
}
return compatibilityBoundaryMessage(message), normalized, cloneJSONArray(tools), nil
}
func compatibilityBoundaryMessage(text string) map[string]any {
return map[string]any{
"type": "message", "role": "developer",
"content": []any{map[string]any{"type": "input_text", "text": text}},
}
}
func dedupeNormalizedTools(tools []any) []any {
result := make([]any, 0, len(tools))
positions := make(map[string]int)
for _, raw := range tools {
tool, ok := raw.(map[string]any)
if !ok {
result = append(result, raw)
continue
}
kind := stringField(tool, "type")
name := stringField(tool, "name")
if name == "" {
name = stringField(tool, "server_label")
}
key := kind + "\x00" + name
if name == "" {
key = kind
}
if index, exists := positions[key]; exists {
result[index] = raw
continue
}
positions[key] = len(result)
result = append(result, raw)
}
return result
}
func (c *responsesToolCompatibility) addWarning(code string) {
if c == nil || code == "" {
return
}
if _, exists := c.warningSet[code]; exists {
return
}
c.warningSet[code] = struct{}{}
c.warnings = append(c.warnings, code)
}
func (c *responsesToolCompatibility) warningHeader() string {
if c == nil {
return ""
}
return strings.Join(c.warnings, ",")
}
@@ -0,0 +1,225 @@
package cli
import (
"encoding/json"
"io"
"strings"
"testing"
)
func TestLegacyLocalShellUsesNativeLocalShellAndRestoresJSON(t *testing.T) {
normalized, compatibility, err := normalizeResponsesRequest([]byte(`{
"model":"public","input":"show cwd",
"tools":[{"type":"local_shell"}],
"tool_choice":{"type":"local_shell"}
}`), "grok-4.5")
if err != nil {
t.Fatal(err)
}
if compatibility == nil || !compatibility.legacyLocalShell {
t.Fatal("legacy local_shell 未启用兼容层")
}
var request map[string]any
if err := json.Unmarshal(normalized, &request); err != nil {
t.Fatal(err)
}
tool := request["tools"].([]any)[0].(map[string]any)
environment := tool["environment"].(map[string]any)
if tool["type"] != "shell" || environment["type"] != "local" || request["tool_choice"] != "required" {
t.Fatalf("upstream shell = %#v, choice = %#v", tool, request["tool_choice"])
}
restored, err := compatibility.normalizeResponseJSON([]byte(`{
"id":"resp_1","object":"response",
"tools":[{"type":"shell","environment":{"type":"local"}}],
"output":[{"id":"sh_1","type":"shell_call","call_id":"call_1","status":"completed","action":{"type":"exec","commands":["pwd"]}}]
}`))
if err != nil {
t.Fatal(err)
}
var response map[string]any
if err := json.Unmarshal(restored, &response); err != nil {
t.Fatal(err)
}
call := response["output"].([]any)[0].(map[string]any)
action := call["action"].(map[string]any)
if call["type"] != "local_shell_call" || action["type"] != "exec" || action["command"] != "pwd" {
t.Fatalf("legacy local_shell_call = %#v", call)
}
if response["tools"].([]any)[0].(map[string]any)["type"] != "local_shell" {
t.Fatalf("visible tools = %#v", response["tools"])
}
}
func TestLegacyLocalShellHistoryBecomesStructuredShellHistory(t *testing.T) {
normalized, _, err := normalizeResponsesRequest([]byte(`{
"model":"public","tools":[{"type":"local_shell"}],"input":[
{"type":"local_shell_call","id":"sh_1","call_id":"call_1","status":"completed","action":{"type":"exec","command":["printf","a b"],"working_directory":"/workspace","env":{"MODE":"test"}}},
{"type":"local_shell_call_output","call_id":"call_1","status":"failed","exit_code":7,"output":"failure"}
]
}`), "grok-4.5")
if err != nil {
t.Fatal(err)
}
var request map[string]any
if err := json.Unmarshal(normalized, &request); err != nil {
t.Fatal(err)
}
items := request["input"].([]any)
call := items[0].(map[string]any)
commands := call["action"].(map[string]any)["commands"].([]any)
if call["type"] != "shell_call" || len(commands) != 1 || commands[0] != `cd /workspace && env MODE=test printf 'a b'` {
t.Fatalf("shell call history = %#v", call)
}
output := items[1].(map[string]any)
outcome := output["output"].([]any)[0].(map[string]any)["outcome"].(map[string]any)
if output["type"] != "shell_call_output" || outcome["exit_code"] != float64(7) {
t.Fatalf("shell output history = %#v", output)
}
}
func TestRequestRejectsAmbiguousShellDeclarations(t *testing.T) {
_, _, err := normalizeResponsesRequest([]byte(`{
"model":"public","input":"hello",
"tools":[{"type":"shell","environment":{"type":"local"}},{"type":"local_shell"}]
}`), "grok-4.5")
requestErr, ok := err.(*responsesRequestError)
if !ok || requestErr.Code != "invalid_parameter" || requestErr.Param != "tools[1].type" {
t.Fatalf("error = %#v", err)
}
}
func TestApplyPatchToolRequestHistoryAndJSONResponse(t *testing.T) {
normalized, compatibility, err := normalizeResponsesRequest([]byte(`{
"model":"public","input":"edit file",
"tools":[{"type":"apply_patch"}],
"tool_choice":{"type":"apply_patch"}
}`), "grok-4.5")
if err != nil {
t.Fatal(err)
}
if compatibility == nil {
t.Fatal("apply_patch 未启用兼容层")
}
var request map[string]any
if err := json.Unmarshal(normalized, &request); err != nil {
t.Fatal(err)
}
tool := request["tools"].([]any)[0].(map[string]any)
choice := request["tool_choice"].(map[string]any)
if tool["type"] != "function" || tool["name"] != "grok2api_apply_patch" || choice["type"] != "function" || choice["name"] != "grok2api_apply_patch" {
t.Fatalf("apply patch wrapper = %#v, choice = %#v", tool, choice)
}
restored, err := compatibility.normalizeResponseJSON([]byte(`{
"id":"resp_1","object":"response",
"tools":[{"type":"function","name":"grok2api_apply_patch"}],
"output":[{"id":"fc_1","type":"function_call","call_id":"call_1","status":"completed","name":"grok2api_apply_patch","arguments":"{\"operation\":{\"type\":\"update_file\",\"path\":\"main.go\",\"diff\":\"@@\\n-old\\n+new\"}}"}]
}`))
if err != nil {
t.Fatal(err)
}
var response map[string]any
if err := json.Unmarshal(restored, &response); err != nil {
t.Fatal(err)
}
call := response["output"].([]any)[0].(map[string]any)
operation := call["operation"].(map[string]any)
if call["type"] != "apply_patch_call" || call["name"] != nil || call["arguments"] != nil || operation["type"] != "update_file" || operation["path"] != "main.go" {
t.Fatalf("apply_patch_call = %#v", call)
}
if response["tools"].([]any)[0].(map[string]any)["type"] != "apply_patch" {
t.Fatalf("visible tools = %#v", response["tools"])
}
history, _, err := normalizeResponsesRequest([]byte(`{
"model":"public","tools":[{"type":"apply_patch"}],"input":[
{"type":"apply_patch_call","id":"apc_1","call_id":"call_1","status":"completed","operation":{"type":"delete_file","path":"old.txt"}},
{"type":"apply_patch_call_output","call_id":"call_1","status":"failed","output":"permission denied"}
]
}`), "grok-4.5")
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(history, &request); err != nil {
t.Fatal(err)
}
items := request["input"].([]any)
if items[0].(map[string]any)["type"] != "function_call" || !strings.Contains(items[0].(map[string]any)["arguments"].(string), `"delete_file"`) {
t.Fatalf("apply patch call history = %#v", items[0])
}
if items[1].(map[string]any)["type"] != "function_call_output" || !strings.Contains(items[1].(map[string]any)["output"].(string), "failed") {
t.Fatalf("apply patch output history = %#v", items[1])
}
}
func TestApplyPatchStreamBuffersFunctionProtocolAndRestoresItems(t *testing.T) {
_, compatibility, err := normalizeResponsesRequest([]byte(`{
"model":"public","input":"edit","stream":true,"tools":[{"type":"apply_patch"}]
}`), "grok-4.5")
if err != nil {
t.Fatal(err)
}
source := strings.Join([]string{
`event: response.output_item.added`,
`data: {"type":"response.output_item.added","output_index":0,"sequence_number":1,"item":{"id":"fc_1","type":"function_call","call_id":"call_1","status":"in_progress","name":"grok2api_apply_patch","arguments":""}}`,
``,
`event: response.function_call_arguments.delta`,
`data: {"type":"response.function_call_arguments.delta","item_id":"fc_1","output_index":0,"sequence_number":2,"delta":"{\"operation\":{\"type\":\"delete_file\","}`,
``,
`event: response.function_call_arguments.done`,
`data: {"type":"response.function_call_arguments.done","item_id":"fc_1","output_index":0,"sequence_number":3,"arguments":"{\"operation\":{\"type\":\"delete_file\",\"path\":\"old.txt\"}}"}`,
``,
`event: response.output_item.done`,
`data: {"type":"response.output_item.done","output_index":0,"sequence_number":4,"item":{"id":"fc_1","type":"function_call","call_id":"call_1","status":"completed","name":"grok2api_apply_patch","arguments":"{\"operation\":{\"type\":\"delete_file\",\"path\":\"old.txt\"}}"}}`,
``,
}, "\n")
stream := compatibility.normalizeResponseStream(io.NopCloser(strings.NewReader(source)))
converted, err := io.ReadAll(stream)
if err != nil {
t.Fatal(err)
}
text := string(converted)
if strings.Contains(text, "function_call_arguments") || strings.Contains(text, "grok2api_apply_patch") || strings.Contains(text, `"arguments"`) {
t.Fatalf("内部 function 协议泄露:\n%s", text)
}
for _, expected := range []string{
`event: response.output_item.added`, `event: response.output_item.done`,
`"type":"apply_patch_call"`, `"type":"delete_file"`, `"path":"old.txt"`,
} {
if !strings.Contains(text, expected) {
t.Fatalf("apply patch SSE 缺少 %s:\n%s", expected, text)
}
}
}
func TestAdditionalToolsAndCompactionBoundaryRemainVisible(t *testing.T) {
normalized, _, err := normalizeResponsesRequest([]byte(`{
"model":"public","tools":[{"type":"function","name":"lookup","description":"old","parameters":{"type":"object"}}],
"input":[
{"type":"compaction_trigger"},
{"type":"additional_tools","role":"developer","tools":[{"type":"function","name":"lookup","description":"new","parameters":{"type":"object"}},{"type":"apply_patch"}]},
{"type":"message","role":"user","content":[{"type":"input_text","text":"continue"}]}
]
}`), "grok-4.5")
if err != nil {
t.Fatal(err)
}
var request map[string]any
if err := json.Unmarshal(normalized, &request); err != nil {
t.Fatal(err)
}
tools := request["tools"].([]any)
if len(tools) != 2 || tools[0].(map[string]any)["description"] != "new" || tools[1].(map[string]any)["name"] != "grok2api_apply_patch" {
t.Fatalf("normalized tools = %#v", tools)
}
items := request["input"].([]any)
if len(items) != 3 || items[0].(map[string]any)["role"] != "developer" || items[1].(map[string]any)["role"] != "developer" {
t.Fatalf("boundary items = %#v", items)
}
first := items[0].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
second := items[1].(map[string]any)["content"].([]any)[0].(map[string]any)["text"].(string)
if !strings.Contains(first, "compaction boundary") || !strings.Contains(second, "lookup, apply_patch") {
t.Fatalf("boundary text = %q / %q", first, second)
}
}
@@ -27,6 +27,7 @@ func (c *responsesToolCompatibility) normalizeCustomTool(tool map[string]any, na
}
description += "Provide the custom tool input in the input string field."
c.changed = true
c.addWarning("custom_tool_emulated")
return []any{map[string]any{
"type": "function", "name": c.alias(identity), "description": description,
"parameters": map[string]any{
@@ -5,14 +5,11 @@ import (
"strings"
)
// normalizeAgentMessageInput 将可见的 inter-agent 文本保留为 developer 消息;不透明内容不会静默丢弃。
func normalizeAgentMessageInput(item map[string]any, param string) (map[string]any, error) {
// normalizeAgentMessageInput 将 inter-agent 历史保留为 developer 消息;不透明内容保留边界标记而不泄露密文。
func normalizeAgentMessageInput(item map[string]any, _ string) (map[string]any, error) {
content, ok := textInputContent(item["content"])
if !ok {
return nil, &responsesRequestError{
Message: "agent_message 只支持可见文本内容",
Param: param + ".content", Code: "unsupported_parameter",
}
return compatibilityBoundaryMessage("An encrypted inter-agent message occurred here but is not portable to the Grok Build account."), nil
}
author := strings.TrimSpace(stringField(item, "author"))
if author == "" {
@@ -23,7 +23,9 @@ func (c *responsesToolCompatibility) normalizeResponseJSON(body []byte) ([]byte,
if err := json.Unmarshal(body, &response); err != nil {
return nil, fmt.Errorf("解析 Grok Build Responses 响应: %w", err)
}
c.rewriteResponseValue(response)
if err := c.rewriteResponseValue(response); err != nil {
return nil, err
}
c.restoreVisibleTools(response)
converted, err := json.Marshal(response)
if err != nil {
@@ -77,9 +79,10 @@ type responsesStreamOutput struct {
}
type responsesStreamCall struct {
identity responsesToolIdentity
arguments strings.Builder
lastDelta map[string]any
identity responsesToolIdentity
arguments strings.Builder
lastDelta map[string]any
addedPayload map[string]any
}
func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte) ([]responsesStreamOutput, error) {
@@ -105,12 +108,16 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte
}
if kind == "response.output_item.added" {
if item, ok := payload["item"].(map[string]any); ok {
c.rememberStreamCall(item)
state := c.rememberStreamCall(item)
if state != nil && state.identity.Kind == responsesApplyPatchTool {
state.addedPayload = cloneJSONObject(payload)
return nil, nil
}
}
}
if kind == "response.function_call_arguments.delta" {
identity, state, found := c.streamIdentity(payload)
if found && (identity.Kind == responsesToolSearch || identity.Kind == responsesCustomTool) {
if found && (identity.Kind == responsesToolSearch || identity.Kind == responsesCustomTool || identity.Kind == responsesApplyPatchTool) {
state.arguments.WriteString(stringField(payload, "delta"))
if identity.Kind == responsesCustomTool {
state.lastDelta = cloneJSONObject(payload)
@@ -120,7 +127,7 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte
}
if kind == "response.function_call_arguments.done" {
identity, state, found := c.streamIdentity(payload)
if found && identity.Kind == responsesToolSearch {
if found && (identity.Kind == responsesToolSearch || identity.Kind == responsesApplyPatchTool) {
// Tool Search 的 arguments 是结构化对象;等 output_item.done 带齐参数后再对下游可见。
return nil, nil
}
@@ -148,7 +155,17 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte
return outputs, nil
}
}
c.rewriteResponseValue(payload)
if kind == "response.output_item.done" {
if item, ok := payload["item"].(map[string]any); ok {
identity, exists := c.aliases[stringField(item, "name")]
if exists && identity.Kind == responsesApplyPatchTool {
return c.rewriteApplyPatchDoneEvent(payload, item)
}
}
}
if err := c.rewriteResponseValue(payload); err != nil {
return nil, err
}
if response, ok := payload["response"].(map[string]any); ok {
c.restoreVisibleTools(response)
}
@@ -159,13 +176,13 @@ func (c *responsesToolCompatibility) rewriteStreamData(event string, data []byte
return []responsesStreamOutput{{Data: converted}}, nil
}
func (c *responsesToolCompatibility) rememberStreamCall(item map[string]any) {
func (c *responsesToolCompatibility) rememberStreamCall(item map[string]any) *responsesStreamCall {
if stringField(item, "type") != "function_call" {
return
return nil
}
identity, exists := c.aliases[stringField(item, "name")]
if !exists {
return
return nil
}
state := &responsesStreamCall{identity: identity}
for _, key := range []string{stringField(item, "id"), stringField(item, "call_id")} {
@@ -173,6 +190,7 @@ func (c *responsesToolCompatibility) rememberStreamCall(item map[string]any) {
c.streamCalls[key] = state
}
}
return state
}
func (c *responsesToolCompatibility) streamIdentity(payload map[string]any) (responsesToolIdentity, *responsesStreamCall, bool) {
@@ -194,26 +212,38 @@ func (c *responsesToolCompatibility) streamIdentity(payload map[string]any) (res
return identity, state, true
}
func (c *responsesToolCompatibility) rewriteResponseValue(value any) {
func (c *responsesToolCompatibility) rewriteResponseValue(value any) error {
switch typed := value.(type) {
case []any:
for _, item := range typed {
c.rewriteResponseValue(item)
if err := c.rewriteResponseValue(item); err != nil {
return err
}
}
case map[string]any:
for _, item := range typed {
c.rewriteResponseValue(item)
if err := c.rewriteResponseValue(item); err != nil {
return err
}
}
if stringField(typed, "type") == "function_call" {
c.rewriteFunctionCall(typed)
switch stringField(typed, "type") {
case "function_call":
if err := c.rewriteFunctionCall(typed); err != nil {
return err
}
case "shell_call":
if c.legacyLocalShell {
rewriteLegacyLocalShellCall(typed)
}
}
}
return nil
}
func (c *responsesToolCompatibility) rewriteFunctionCall(call map[string]any) {
func (c *responsesToolCompatibility) rewriteFunctionCall(call map[string]any) error {
identity, exists := c.aliases[stringField(call, "name")]
if !exists {
return
return nil
}
switch identity.Kind {
case responsesFunctionTool:
@@ -239,7 +269,64 @@ func (c *responsesToolCompatibility) rewriteFunctionCall(call map[string]any) {
call["arguments"] = decodeToolSearchArguments(call["arguments"])
delete(call, "name")
delete(call, "namespace")
case responsesApplyPatchTool:
operation, err := decodeApplyPatchArguments(call["arguments"], "response.output[].arguments")
if err != nil {
return fmt.Errorf("恢复 apply_patch_call: %w", err)
}
call["type"] = "apply_patch_call"
call["operation"] = operation
delete(call, "name")
delete(call, "namespace")
delete(call, "arguments")
}
return nil
}
func rewriteLegacyLocalShellCall(call map[string]any) {
call["type"] = "local_shell_call"
call["action"] = rewriteLegacyShellAction(call["action"])
delete(call, "max_output_length")
}
func (c *responsesToolCompatibility) rewriteApplyPatchDoneEvent(payload, item map[string]any) ([]responsesStreamOutput, error) {
done := cloneJSONObject(payload)
if err := c.rewriteResponseValue(done); err != nil {
return nil, err
}
doneItem, _ := done["item"].(map[string]any)
var state *responsesStreamCall
for _, key := range []string{stringField(item, "id"), stringField(item, "call_id")} {
if candidate, exists := c.streamCalls[key]; exists {
state = candidate
break
}
}
added := map[string]any{"type": "response.output_item.added"}
if state != nil && state.addedPayload != nil {
added = cloneJSONObject(state.addedPayload)
added["type"] = "response.output_item.added"
}
for _, key := range []string{"output_index", "sequence_number"} {
if value, exists := done[key]; exists && added[key] == nil {
added[key] = cloneJSONValue(value)
}
}
addedItem := cloneJSONObject(doneItem)
addedItem["status"] = "in_progress"
added["item"] = addedItem
addedData, err := json.Marshal(added)
if err != nil {
return nil, fmt.Errorf("编码 apply_patch added event: %w", err)
}
doneData, err := json.Marshal(done)
if err != nil {
return nil, fmt.Errorf("编码 apply_patch done event: %w", err)
}
return []responsesStreamOutput{
{Event: "response.output_item.added", Data: addedData},
{Event: "response.output_item.done", Data: doneData},
}, nil
}
func customToolStreamPayload(source map[string]any, kind, valueKey, value string) map[string]any {
@@ -18,6 +18,21 @@ var nativeHostedToolChoiceTypes = map[string]string{
"code_interpreter": "code_interpreter",
"mcp": "mcp",
"shell": "shell",
"local_shell": "shell",
}
// webSearchCompatibilityFields 是 Codex/OpenAI 新版声明中已知、但 0.2.99 上游会以
// "Argument not supported" 拒绝的控制字段。Build 只能降级为其原生最小搜索工具。
var webSearchCompatibilityFields = map[string]struct{}{
"external_web_access": {},
"indexed_web_access": {},
"search_content_types": {},
"search_context_size": {},
"user_location": {},
"filters": {},
"allowed_domains": {},
"max_search_results": {},
"safe_search": {},
}
// normalizeNativeTool 保留 0.2.99 已确认支持的工具,并拒绝只属于 Tool Search 的延迟字段。
@@ -31,24 +46,89 @@ func (c *responsesToolCompatibility) normalizeNativeTool(tool map[string]any, pa
return []any{cloneJSONValue(tool)}, nil
}
// normalizeWebSearchTool 将旧 discriminator 映射为 web_search;0.2.99 未确认的控制字段不会被静默删除。
// normalizeWebSearchTool 将 Codex/OpenAI 新版搜索声明降级为 0.2.99 支持的最小 web_search。
func (c *responsesToolCompatibility) normalizeWebSearchTool(tool map[string]any, kind, param string) ([]any, error) {
if external, exists := tool["external_web_access"]; exists {
enabled, ok := external.(bool)
if !ok {
return nil, &responsesRequestError{Message: "external_web_access 必须是布尔值", Param: param + ".external_web_access", Code: "invalid_parameter"}
}
if !enabled {
return nil, &responsesRequestError{
Message: "Grok Build 0.2.99 无法保证禁用外部网络搜索",
Param: param + ".external_web_access", Code: "unsupported_parameter",
}
}
}
if filters, exists := tool["filters"]; exists && hasNonEmptyWebSearchConstraint(filters) {
return nil, &responsesRequestError{
Message: "Grok Build 0.2.99 无法保证 web_search filters 约束",
Param: param + ".filters", Code: "unsupported_parameter",
}
}
if domains, exists := tool["allowed_domains"]; exists && hasNonEmptyWebSearchConstraint(domains) {
return nil, &responsesRequestError{
Message: "Grok Build 0.2.99 无法保证 allowed_domains 约束",
Param: param + ".allowed_domains", Code: "unsupported_parameter",
}
}
if contentTypes, exists := tool["search_content_types"]; exists {
values, ok := contentTypes.([]any)
if !ok {
return nil, &responsesRequestError{Message: "search_content_types 必须是数组", Param: param + ".search_content_types", Code: "invalid_parameter"}
}
for _, value := range values {
if value != "text" {
return nil, &responsesRequestError{
Message: "Grok Build 0.2.99 只能兼容文本 Web Search",
Param: param + ".search_content_types", Code: "unsupported_parameter",
}
}
}
}
for key := range tool {
if key == "type" {
continue
}
return nil, &responsesRequestError{
Message: "Grok Build 0.2.99 的 web_search 尚未确认支持可选控制字段",
Param: param + "." + key, Code: "unsupported_parameter",
if _, compatible := webSearchCompatibilityFields[key]; !compatible {
return nil, &responsesRequestError{
Message: "Grok Build 0.2.99 不支持该 web_search 字段",
Param: param + "." + key, Code: "unsupported_parameter",
}
}
c.changed = true
c.addWarning("web_search_controls_downgraded")
}
if kind == "web_search" {
if kind == "web_search" && len(tool) == 1 {
return []any{cloneJSONValue(tool)}, nil
}
c.changed = true
return []any{map[string]any{"type": "web_search"}}, nil
}
func hasNonEmptyWebSearchConstraint(value any) bool {
if value == nil {
return false
}
switch typed := value.(type) {
case []any:
return len(typed) > 0
case map[string]any:
for _, item := range typed {
if hasNonEmptyWebSearchConstraint(item) {
return true
}
}
return false
case string:
return strings.TrimSpace(typed) != ""
case bool:
return typed
default:
return true
}
}
// normalizeMCPTool 支持客户端 Tool Search 延迟加载整个 MCP server 定义。
func (c *responsesToolCompatibility) normalizeMCPTool(tool map[string]any, clientSearch, force bool, param string) ([]any, error) {
deferred, _ := tool["defer_loading"].(bool)
@@ -19,6 +19,7 @@ const (
responsesFunctionTool responsesToolKind = iota
responsesCustomTool
responsesToolSearch
responsesApplyPatchTool
)
type responsesToolIdentity struct {
@@ -40,6 +41,10 @@ type responsesToolCompatibility struct {
clientSearchTool map[string]any
clientSearchParam string
streamCalls map[string]*responsesStreamCall
legacyLocalShell bool
nativeShell bool
warnings []string
warningSet map[string]struct{}
changed bool
}
@@ -57,6 +62,7 @@ func newResponsesToolCompatibility() *responsesToolCompatibility {
aliases: make(map[string]responsesToolIdentity),
identityAliases: make(map[string]string),
streamCalls: make(map[string]*responsesStreamCall),
warningSet: make(map[string]struct{}),
}
}
@@ -110,6 +116,7 @@ func normalizeResponsesTools(payload map[string]json.RawMessage) (*responsesTool
}
normalizedTools = append(normalizedTools, searchTool)
}
normalizedTools = dedupeNormalizedTools(normalizedTools)
if hasTools || len(normalizedTools) > 0 {
payload["tools"] = mustJSON(normalizedTools)
}
@@ -237,6 +244,7 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl
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")))
}
@@ -262,6 +270,7 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl
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
@@ -271,9 +280,15 @@ func (c *responsesToolCompatibility) normalizeTool(raw any, namespace string, cl
return c.normalizeWebSearchTool(tool, kind, param)
case "mcp":
return c.normalizeMCPTool(tool, clientSearch, force, param)
case "x_search", "image_generation", "collections_search", "file_search", "code_execution", "code_interpreter", "shell":
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 "local_shell", "apply_patch", "computer_use_preview":
case "computer_use_preview":
return nil, unsupportedBuildToolError(kind, param)
default:
if kind == "" {
@@ -428,7 +443,24 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, []
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
@@ -436,7 +468,14 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, []
c.changed = true
rewritten = append(rewritten, converted)
case "local_shell_call":
converted, err := normalizeLocalShellInput(item, param)
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
}
@@ -450,15 +489,18 @@ func (c *responsesToolCompatibility) normalizeInputItems(items []any) ([]any, []
c.changed = true
rewritten = append(rewritten, converted)
case "compaction_trigger":
return nil, nil, nil, &responsesRequestError{
Message: "Grok Build 不支持 compaction_trigger input item",
Param: param, Code: "unsupported_parameter",
}
c.changed = true
c.addWarning("compaction_boundary_preserved")
rewritten = append(rewritten, compatibilityBoundaryMessage("Codex context compaction boundary reached."))
case "additional_tools":
return nil, nil, nil, &responsesRequestError{
Message: "Grok Build 当前不支持 additional_tools 的位置语义",
Param: param, Code: "unsupported_parameter",
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))
}
@@ -524,6 +566,16 @@ func (c *responsesToolCompatibility) normalizeToolChoice(payload map[string]json
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{
@@ -579,6 +631,8 @@ func (c *responsesToolCompatibility) alias(identity responsesToolIdentity) strin
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) {
@@ -74,8 +74,6 @@ func TestConvertAnthropicMessagesRequestToResponses(t *testing.T) {
}
func TestConvertAnthropicMessagesInlineSystemRole(t *testing.T) {
// Claude Code 会在 messages 中注入 role="system"(mid-conversation system)。
// 该 system 消息应被提取并合并到顶层 instructions,而不是报 400。
body := []byte(`{
"model":"public-chat","max_tokens":1024,
"system":"Top-level rules.",
@@ -118,7 +116,9 @@ func TestConvertAnthropicMessagesInlineSystemOnly(t *testing.T) {
t.Fatalf("inline-only system should not fail: %v", err)
}
var payload map[string]any
_ = json.Unmarshal(converted, &payload)
if err := json.Unmarshal(converted, &payload); err != nil {
t.Fatal(err)
}
if payload["instructions"] != "Only inline." {
t.Fatalf("instructions = %#v", payload["instructions"])
}
@@ -134,6 +134,119 @@ func TestConvertAnthropicMessagesRejectsUnknownRole(t *testing.T) {
}
}
func TestConvertAnthropicClaudeCodeRequestToResponses(t *testing.T) {
body := []byte(`{
"model":"public-chat","max_tokens":4096,"stream":true,
"system":[{"type":"text","text":"top-level system","cache_control":{"type":"ephemeral"}}],
"messages":[
{"role":"system","content":"legacy system"},
{"role":"developer","content":[{"type":"text","text":"developer context","cache_control":{"type":"ephemeral"}}]},
{"role":"assistant","content":[
{"type":"thinking","thinking":"prior thought","signature":"encrypted-reasoning"},
{"type":"tool_use","id":"toolu_1","name":"Read","input":{"path":"README.md"}}
]},
{"role":"user","content":[
{"type":"tool_result","tool_use_id":"toolu_1","is_error":true,"content":[
{"type":"text","text":"failed"},
{"type":"image","source":{"type":"base64","media_type":"image/png","data":"AAAA"}}
]},
{"type":"document","title":"notes.txt","source":{"type":"text","data":"document text"}},
{"type":"text","text":"continue"}
]}
],
"metadata":{"user_id":"cc-user"},
"thinking":{"type":"enabled","budget_tokens":12000},
"tools":[{"name":"Read","description":"Read file","input_schema":{"type":"object"},"strict":true,"cache_control":{"type":"ephemeral"}}],
"mcp_servers":[{"name":"github","url":"https://example.com/mcp","authorization_token":"token"}]
}`)
converted, options, err := ConvertRequestWithOptions(body, "grok-4.5", OperationMessages)
if err != nil {
t.Fatal(err)
}
if !options.AnthropicThinking {
t.Fatal("thinking option 未保留")
}
var payload map[string]any
if err := json.Unmarshal(converted, &payload); err != nil {
t.Fatal(err)
}
if payload["instructions"] != "top-level system\n\nlegacy system\n\ndeveloper context" || payload["safety_identifier"] != "cc-user" || payload["store"] != false {
t.Fatalf("request metadata = %#v", payload)
}
reasoning := payload["reasoning"].(map[string]any)
if reasoning["effort"] != "high" || payload["include"].([]any)[0] != "reasoning.encrypted_content" {
t.Fatalf("reasoning = %#v, include = %#v", reasoning, payload["include"])
}
input := payload["input"].([]any)
if len(input) != 4 || input[0].(map[string]any)["type"] != "reasoning" || input[1].(map[string]any)["type"] != "function_call" || input[2].(map[string]any)["type"] != "function_call_output" {
t.Fatalf("input = %#v", input)
}
output := input[2].(map[string]any)["output"].([]any)
if len(output) != 3 || !strings.Contains(output[0].(map[string]any)["text"].(string), "failed") || output[2].(map[string]any)["type"] != "input_image" {
t.Fatalf("tool result = %#v", output)
}
tools := payload["tools"].([]any)
if len(tools) != 2 || tools[0].(map[string]any)["type"] != "function" || tools[0].(map[string]any)["strict"] != true || tools[1].(map[string]any)["type"] != "mcp" {
t.Fatalf("tools = %#v", tools)
}
}
func TestConvertAnthropicMessagesValidatesToolRelationships(t *testing.T) {
tests := []struct {
name string
messages string
want string
}{
{name: "orphan result", messages: `[{"role":"user","content":[{"type":"tool_result","tool_use_id":"missing","content":"x"}]}]`, want: "未匹配"},
{name: "missing result", messages: `[{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{}}]}]`, want: "提供 tool_result"},
{name: "result after text", messages: `[{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{}}]},{"role":"user","content":[{"type":"text","text":"late"},{"type":"tool_result","tool_use_id":"toolu_1","content":"x"}]}]`, want: "必须位于"},
{name: "user tool use", messages: `[{"role":"user","content":[{"type":"tool_use","id":"toolu_1","name":"Read","input":{}}]}]`, want: "只允许"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
body := []byte(`{"model":"public","max_tokens":64,"messages":` + test.messages + `}`)
_, _, err := ConvertRequestWithOptions(body, "grok-4.5", OperationMessages)
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("error = %v", err)
}
})
}
}
func TestConvertAnthropicMessagesRejectsUnrepresentableTopK(t *testing.T) {
_, _, err := ConvertRequestWithOptions([]byte(`{
"model":"public","max_tokens":64,"top_k":10,
"messages":[{"role":"user","content":"hello"}]
}`), "grok-4.5", OperationMessages)
if err == nil || !strings.Contains(err.Error(), "top_k") {
t.Fatalf("error = %v", err)
}
}
func TestConvertAnthropicWebSearchControls(t *testing.T) {
converted, _, err := ConvertRequestWithOptions([]byte(`{
"model":"public","max_tokens":64,"messages":[{"role":"user","content":"search"}],
"tools":[{"type":"web_search_20250305","name":"web_search","max_uses":3,"allowed_domains":["example.com"],"user_location":{"type":"approximate","country":"US"}}]
}`), "grok-4.5", OperationMessages)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
_ = json.Unmarshal(converted, &payload)
tool := payload["tools"].([]any)[0].(map[string]any)
if tool["type"] != "web_search" || tool["max_uses"] != float64(3) || len(tool["allowed_domains"].([]any)) != 1 || tool["user_location"].(map[string]any)["country"] != "US" {
t.Fatalf("tool = %#v", tool)
}
_, _, err = ConvertRequestWithOptions([]byte(`{
"model":"public","max_tokens":64,"messages":[{"role":"user","content":"search"}],
"tools":[{"type":"web_search_20250305","name":"web_search","search_context_size":"high"}]
}`), "grok-4.5", OperationMessages)
if err == nil || !strings.Contains(err.Error(), "search_context_size") {
t.Fatalf("error = %v", err)
}
}
func TestConvertResponsesJSONToChatAndMessages(t *testing.T) {
body := []byte(`{
"id":"resp_1","object":"response","created_at":123,"model":"grok-4.5","status":"completed",
@@ -168,6 +281,77 @@ func TestConvertResponsesJSONToChatAndMessages(t *testing.T) {
}
}
func TestConvertResponsesJSONToMessagesThinkingAndStop(t *testing.T) {
body := []byte(`{
"id":"response-1","model":"grok-4.5","status":"completed",
"output":[
{"type":"reasoning","summary":[{"type":"summary_text","text":"thought"}],"encrypted_content":"signature"},
{"type":"message","content":[{"type":"output_text","text":"ABCSTOPXYZ"}]},
{"type":"function_call","call_id":"call_1","name":"Read","arguments":"{}"}
],
"usage":{"input_tokens":10,"output_tokens":5}
}`)
data, err := ConvertResponseJSONWithOptions(body, OperationMessages, ResponseOptions{AnthropicThinking: true, StopSequences: []string{"STOP"}})
if err != nil {
t.Fatal(err)
}
var response map[string]any
if err := json.Unmarshal(data, &response); err != nil {
t.Fatal(err)
}
content := response["content"].([]any)
if response["id"] != "msg_response-1" || response["stop_reason"] != "tool_use" || len(content) != 3 {
t.Fatalf("response = %#v", response)
}
thinking := content[0].(map[string]any)
tool := content[2].(map[string]any)
if thinking["type"] != "thinking" || thinking["signature"] != "signature" || content[1].(map[string]any)["text"] != "ABC" || tool["id"] != "toolu_call_1" {
t.Fatalf("content = %#v", content)
}
}
func TestConvertResponsesJSONToMessagesStopSequence(t *testing.T) {
body := []byte(`{"id":"resp_1","status":"completed","output":[{"type":"message","content":[{"type":"output_text","text":"ABCSTOPXYZ"}]}]}`)
data, err := ConvertResponseJSONWithOptions(body, OperationMessages, ResponseOptions{StopSequences: []string{"STOP"}})
if err != nil {
t.Fatal(err)
}
var response map[string]any
_ = json.Unmarshal(data, &response)
if response["stop_reason"] != "stop_sequence" || response["stop_sequence"] != "STOP" || response["content"].([]any)[0].(map[string]any)["text"] != "ABC" {
t.Fatalf("response = %#v", response)
}
}
func TestConvertResponsesJSONToMessagesNormalizesErrorType(t *testing.T) {
tests := []struct {
name string
body string
want string
}{
{name: "preserve anthropic type", body: `{"error":{"message":"auth","type":"authentication_error"}}`, want: "authentication_error"},
{name: "map openai type", body: `{"error":{"message":"invalid","type":"unsupported_parameter"}}`, want: "invalid_request_error"},
{name: "map upstream code", body: `{"error":{"message":"limited","code":"rate_limit_exceeded"}}`, want: "rate_limit_error"},
{name: "hide private type", body: `{"error":{"message":"failed","type":"private_internal"}}`, want: "api_error"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
data, err := ConvertResponseJSON([]byte(test.body), OperationMessages)
if err != nil {
t.Fatal(err)
}
var response map[string]any
if err := json.Unmarshal(data, &response); err != nil {
t.Fatal(err)
}
errorObject := response["error"].(map[string]any)
if errorObject["type"] != test.want {
t.Fatalf("error = %#v", response)
}
})
}
}
func TestConvertResponsesStream(t *testing.T) {
stream := strings.Join([]string{
`event: response.created`,
@@ -191,3 +375,61 @@ func TestConvertResponsesStream(t *testing.T) {
}
}
}
func TestConvertResponsesStreamToMessagesThinkingToolsAndStop(t *testing.T) {
stream := strings.Join([]string{
`event: response.created`,
`data: {"type":"response.created","response":{"id":"response-1","model":"grok-4.5","usage":{"input_tokens":3}}}`, "",
`event: response.output_item.added`,
`data: {"type":"response.output_item.added","item":{"id":"reasoning-1","type":"reasoning"}}`, "",
`event: response.reasoning_summary_text.delta`,
`data: {"type":"response.reasoning_summary_text.delta","item_id":"reasoning-1","delta":"thought"}`, "",
`event: response.output_item.done`,
`data: {"type":"response.output_item.done","item":{"id":"reasoning-1","type":"reasoning","encrypted_content":"signature"}}`, "",
`event: response.output_text.delta`,
`data: {"type":"response.output_text.delta","delta":"ABCST"}`, "",
`event: response.output_text.delta`,
`data: {"type":"response.output_text.delta","delta":"OPXYZ"}`, "",
`event: response.completed`,
`data: {"type":"response.completed","response":{"status":"completed","usage":{"input_tokens":3,"output_tokens":2}}}`, "", "",
}, "\n")
converted, err := io.ReadAll(ConvertResponseStreamWithOptions(io.NopCloser(strings.NewReader(stream)), OperationMessages, ResponseOptions{AnthropicThinking: true, StopSequences: []string{"STOP"}}))
if err != nil {
t.Fatal(err)
}
text := string(converted)
ordered := []string{"message_start", "thinking_delta", "signature_delta", "text_delta", "message_delta", "message_stop"}
position := 0
for _, expected := range ordered {
index := strings.Index(text[position:], expected)
if index < 0 {
t.Fatalf("%q 缺失或乱序:\n%s", expected, text)
}
position += index + len(expected)
}
if strings.Contains(text, "XYZ") || !strings.Contains(text, `"text":"ABC"`) || !strings.Contains(text, `"stop_reason":"stop_sequence"`) || !strings.Contains(text, `"stop_sequence":"STOP"`) {
t.Fatalf("stream = %s", text)
}
}
func TestConvertResponsesStreamEmitsDoneOnlyToolArguments(t *testing.T) {
stream := strings.Join([]string{
`event: response.output_item.added`,
`data: {"type":"response.output_item.added","item":{"id":"item_1","type":"function_call","call_id":"call_1","name":"Read","arguments":""}}`, "",
`event: response.function_call_arguments.done`,
`data: {"type":"response.function_call_arguments.done","item_id":"item_1","arguments":"{\"path\":\"README.md\"}"}`, "",
`event: response.completed`,
`data: {"type":"response.completed","response":{"status":"completed"}}`, "", "",
}, "\n")
converted, err := io.ReadAll(ConvertResponseStreamWithOptions(io.NopCloser(strings.NewReader(stream)), OperationMessages, ResponseOptions{}))
if err != nil {
t.Fatal(err)
}
text := string(converted)
if !strings.Contains(text, `"id":"toolu_call_1"`) || !strings.Contains(text, `"partial_json":"{\"path\":\"README.md\"}"`) || !strings.Contains(text, `"stop_reason":"tool_use"`) {
t.Fatalf("stream = %s", text)
}
if strings.Count(text, `"type":"content_block_stop"`) != 1 {
t.Fatalf("tool block closed multiple times: %s", text)
}
}
@@ -16,13 +16,21 @@ const (
// ConvertRequest 将下游对话协议转换为 Responses 请求,作为 Provider 的统一上游协议。
func ConvertRequest(body []byte, model, operation string) ([]byte, error) {
converted, _, err := ConvertRequestWithOptions(body, model, operation)
return converted, err
}
// ConvertRequestWithOptions 同时返回下游协议特有的响应语义,供 JSON/SSE 转换阶段使用。
func ConvertRequestWithOptions(body []byte, model, operation string) ([]byte, ResponseOptions, error) {
switch operation {
case OperationChat:
return convertChatRequest(body, model)
converted, err := convertChatRequest(body, model)
return converted, ResponseOptions{}, err
case OperationMessages:
return convertMessagesRequest(body, model)
default:
return replaceModel(body, model)
converted, err := replaceModel(body, model)
return converted, ResponseOptions{}, err
}
}
@@ -241,71 +249,119 @@ func convertChatToolChoice(raw json.RawMessage) (json.RawMessage, error) {
return mustJSON(map[string]any{"type": "function", "name": function.Name}), nil
}
func convertMessagesRequest(body []byte, model string) ([]byte, error) {
func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, error) {
var request anthropicRequest
if err := json.Unmarshal(body, &request); err != nil {
return nil, fmt.Errorf("解析 Messages 请求: %w", err)
return nil, ResponseOptions{}, fmt.Errorf("解析 Messages 请求: %w", err)
}
if len(request.Messages) == 0 {
return nil, errors.New("messages 必须是非空数组")
return nil, ResponseOptions{}, errors.New("messages 必须是非空数组")
}
input, inlineSystem, err := convertAnthropicMessages(request.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)
if err != nil {
return nil, err
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,
"max_output_tokens": request.MaxTokens, "store": false,
}
system, err := anthropicSystemText(request.System)
if err != nil {
return nil, err
instructions := make([]string, 0, len(inlineInstructions)+1)
if system, err := anthropicSystemText(request.System); err != nil {
return nil, ResponseOptions{}, err
} else if system != "" {
instructions = append(instructions, system)
}
// 合并顶层 system 与 messages 中内联的 system(Claude Code 会注入后者)。
if inlineSystem != "" {
if system != "" {
system = system + "\n\n" + inlineSystem
} else {
system = inlineSystem
}
}
if system != "" {
target["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 len(request.StopSequences) > 0 {
target["stop"] = request.StopSequences
}
if request.Metadata != nil {
target["metadata"] = request.Metadata
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 request.Thinking != nil && request.Thinking.Type != "disabled" {
effort := "high"
if thinkingEnabled {
effort := anthropicThinkingEffort(request.Thinking.BudgetTokens)
if request.OutputConfig != nil && request.OutputConfig.Effort != "" {
effort = request.OutputConfig.Effort
}
target["reasoning"] = map[string]any{"effort": effort, "summary": "auto"}
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, err
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, err
return nil, ResponseOptions{}, err
}
target["tool_choice"] = choice
target["parallel_tool_calls"] = parallel
}
return json.Marshal(target)
converted, err := json.Marshal(target)
return converted, ResponseOptions{
AnthropicThinking: thinkingEnabled,
StopSequences: append([]string(nil), request.StopSequences...),
}, err
}
type anthropicRequest struct {
@@ -319,8 +375,11 @@ type anthropicRequest struct {
StopSequences []string `json:"stop_sequences"`
Metadata map[string]any `json:"metadata"`
Thinking *struct {
Type string `json:"type"`
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 {
@@ -343,36 +402,43 @@ type anthropicToolChoice struct {
DisableParallelToolUse bool `json:"disable_parallel_tool_use"`
}
func convertAnthropicMessages(messages []anthropicMessage) ([]any, string, error) {
func convertAnthropicMessages(messages []anthropicMessage) ([]any, []string, error) {
input := make([]any, 0, len(messages))
systemTexts := make([]string, 0)
for _, message := range 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 != "user" && role != "assistant" {
// Claude Code 等客户端会在 messages 中注入 role="system"
// (mid-conversation system)。抽取其文本,合并到顶层 instructions,
// 而不是直接拒绝。
if role == "system" {
text, err := anthropicSystemText(message.Content)
if err != nil {
return nil, "", err
}
if text != "" {
systemTexts = append(systemTexts, text)
}
continue
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)
}
return nil, "", fmt.Errorf("Messages API 不支持 role=%q", message.Role)
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, "", errors.New("Messages content 必须是字符串或内容块数组")
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 {
@@ -380,53 +446,116 @@ func convertAnthropicMessages(messages []anthropicMessage) ([]any, string, error
messageParts = nil
}
}
for _, block := range blocks {
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, "", errors.New("text block 无效")
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, "", err
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 || value.ID == "" || value.Name == "" {
return nil, "", errors.New("tool_use block 无效")
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 toolUseID == "" {
return nil, "", errors.New("tool_result 缺少 tool_use_id")
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"])
if err != nil {
return nil, "", err
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, "", fmt.Errorf("当前不支持 Anthropic content.type=%q", typeName)
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)
}
}
return input, strings.Join(systemTexts, "\n\n"), nil
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) {
@@ -480,7 +609,51 @@ func anthropicImageURL(raw json.RawMessage) (string, error) {
}
}
func anthropicToolResult(raw json.RawMessage) (string, error) {
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) (any, error) {
if isEmptyJSON(raw) {
return "", nil
}
var text string
if json.Unmarshal(raw, &text) == nil {
return text, nil
@@ -489,25 +662,58 @@ func anthropicToolResult(raw json.RawMessage) (string, error) {
if json.Unmarshal(raw, &blocks) != nil {
return "", errors.New("tool_result.content 无效")
}
parts := make([]string, 0, len(blocks))
parts := make([]any, 0, len(blocks))
for _, block := range blocks {
var typeName string
_ = json.Unmarshal(block["type"], &typeName)
if typeName != "text" {
return "", fmt.Errorf("tool_result 暂不支持 type=%q", 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)
default:
return nil, fmt.Errorf("tool_result 暂不支持 type=%q", typeName)
}
var value string
_ = json.Unmarshal(block["text"], &value)
parts = append(parts, value)
}
return strings.Join(parts, "\n"), nil
return parts, nil
}
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 _, tool := range 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)
}
@@ -523,11 +729,86 @@ func convertAnthropicTools(tools []map[string]json.RawMessage) ([]any, error) {
return nil, fmt.Errorf("tool %q 的 input_schema 无效", name)
}
}
result = append(result, map[string]any{"type": "function", "name": name, "description": description, "parameters": schema})
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 {
@@ -7,6 +7,12 @@ import (
"time"
)
// ResponseOptions 保留无法直接交给 Responses 上游执行的下游协议语义。
type ResponseOptions struct {
AnthropicThinking bool
StopSequences []string
}
type responseEnvelope struct {
ID string `json:"id"`
Model string `json:"model"`
@@ -27,6 +33,7 @@ type responseItem struct {
CallID string `json:"call_id"`
Name string `json:"name"`
Arguments string `json:"arguments"`
Encrypted string `json:"encrypted_content"`
}
type responseContent struct {
@@ -48,19 +55,26 @@ type responseUsage struct {
}
type parsedResponse struct {
ID string
Model string
CreatedAt int64
Text string
Reasoning string
Refusal string
Calls []responseItem
Usage responseUsage
Status string
ID string
Model string
CreatedAt int64
Text string
Reasoning string
Signature string
Refusal string
Calls []responseItem
Usage responseUsage
Status string
StopSequence string
}
// ConvertResponseJSON 将 Responses 非流式结果转换为 Chat Completions 或 Anthropic Messages。
func ConvertResponseJSON(body []byte, operation string) ([]byte, error) {
return ConvertResponseJSONWithOptions(body, operation, ResponseOptions{})
}
// ConvertResponseJSONWithOptions 按原始 Messages 请求选项恢复 thinking 与 stop sequence。
func ConvertResponseJSONWithOptions(body []byte, operation string, options ResponseOptions) ([]byte, error) {
if operation == OperationResponses {
return body, nil
}
@@ -75,9 +89,12 @@ func ConvertResponseJSON(body []byte, operation string) ([]byte, error) {
return body, nil
}
parsed := parseResponse(envelope)
if operation == OperationMessages {
parsed.Text, parsed.StopSequence = applyAnthropicStopSequences(parsed.Text, options.StopSequences)
}
var result any
if operation == OperationMessages {
result = messagesResponse(parsed)
result = messagesResponse(parsed, options)
} else {
result = chatResponse(parsed)
}
@@ -104,6 +121,9 @@ func parseResponse(value responseEnvelope) parsedResponse {
for _, summary := range item.Summary {
parsed.Reasoning += summary.Text
}
if item.Encrypted != "" {
parsed.Signature = item.Encrypted
}
case "function_call":
parsed.Calls = append(parsed.Calls, item)
}
@@ -144,8 +164,19 @@ func chatResponse(value parsedResponse) map[string]any {
}
}
func messagesResponse(value parsedResponse) map[string]any {
content := make([]any, 0, len(value.Calls)+1)
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})
}
@@ -154,23 +185,73 @@ func messagesResponse(value parsedResponse) 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": call.CallID, "name": call.Name, "input": input})
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": strings.Replace(value.ID, "resp_", "msg_", 1), "type": "message", "role": "assistant",
"model": value.Model, "content": content, "stop_reason": stopReason, "stop_sequence": nil,
"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,
@@ -194,13 +275,36 @@ func anthropicErrorJSON(value any) []byte {
if text, ok := object["message"].(string); ok && text != "" {
message = text
}
// 透传上游错误类型/代码,便于定位(限流、鉴权、转换失败等)。
if text, ok := object["type"].(string); ok && text != "" {
errorType = text
} else if text, ok := object["code"].(string); ok && text != "" {
errorType = text
}
errorType = normalizeAnthropicErrorType(object)
}
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,19 +6,25 @@ import (
"encoding/json"
"fmt"
"io"
"sort"
"strings"
"time"
)
// ConvertResponseStream 将 Responses SSE 转换为 Chat Completions 或 Anthropic Messages SSE。
func ConvertResponseStream(source io.ReadCloser, operation string) io.ReadCloser {
return ConvertResponseStreamWithOptions(source, operation, ResponseOptions{})
}
// ConvertResponseStreamWithOptions 按原始 Messages 请求选项生成有序 Anthropic SSE。
func ConvertResponseStreamWithOptions(source io.ReadCloser, operation string, options ResponseOptions) io.ReadCloser {
if operation == OperationResponses {
return source
}
reader, writer := io.Pipe()
go func() {
defer source.Close()
converter := newStreamConverter(writer, operation)
converter := newStreamConverter(writer, operation, options)
err := consumeSSE(source, converter.handle)
if err == nil {
err = converter.finish()
@@ -29,27 +35,41 @@ func ConvertResponseStream(source io.ReadCloser, operation string) io.ReadCloser
}
type streamConverter struct {
writer io.Writer
operation string
id string
model string
created int64
started bool
textStarted bool
textIndex int
nextIndex int
tools map[string]streamTool
usage responseUsage
writer io.Writer
operation string
id string
model string
created int64
started bool
finished bool
textStarted bool
textIndex int
thinkingStarted bool
thinkingClosed bool
thinkingIndex int
thinkingItemID string
nextIndex int
tools map[string]streamTool
usage responseUsage
options ResponseOptions
stopFilter *anthropicStreamStopFilter
stopSequence string
}
type streamTool struct {
Index int
ID string
Name string
Index int
ID string
Name string
Arguments string
SentArgs bool
Closed bool
}
func newStreamConverter(writer io.Writer, operation string) *streamConverter {
return &streamConverter{writer: writer, operation: operation, created: time.Now().Unix(), tools: make(map[string]streamTool)}
func newStreamConverter(writer io.Writer, operation string, options ResponseOptions) *streamConverter {
return &streamConverter{
writer: writer, operation: operation, created: time.Now().Unix(), tools: make(map[string]streamTool),
options: options, stopFilter: newAnthropicStreamStopFilter(options.StopSequences),
}
}
func (c *streamConverter) handle(event string, data []byte) error {
@@ -64,6 +84,9 @@ func (c *streamConverter) handle(event string, data []byte) error {
if raw := root["type"]; typeName == "" {
_ = json.Unmarshal(raw, &typeName)
}
if c.stopSequence != "" && typeName != "response.completed" && typeName != "response.incomplete" && typeName != "response.failed" && typeName != "error" {
return nil
}
switch typeName {
case "response.created", "response.in_progress":
var response responseEnvelope
@@ -78,15 +101,25 @@ func (c *streamConverter) handle(event string, data []byte) error {
}
return c.textDelta(delta)
case "response.reasoning_summary_text.delta":
if c.operation != OperationChat {
return nil
}
var delta string
_ = json.Unmarshal(root["delta"], &delta)
return c.chatDelta(map[string]any{"reasoning_content": delta})
if c.operation == OperationChat {
return c.chatDelta(map[string]any{"reasoning_content": delta})
}
return c.thinkingDelta(delta)
case "response.reasoning_text.delta":
var delta string
_ = json.Unmarshal(root["delta"], &delta)
if c.operation == OperationMessages {
return c.thinkingDelta(delta)
}
return nil
case "response.output_item.added":
var item responseItem
_ = json.Unmarshal(root["item"], &item)
if item.Type == "reasoning" && c.operation == OperationMessages && c.options.AnthropicThinking {
return c.thinkingStart(item.ID)
}
if item.Type != "function_call" {
return nil
}
@@ -98,17 +131,29 @@ func (c *streamConverter) handle(event string, data []byte) error {
_ = json.Unmarshal(root["item_id"], &itemID)
_ = json.Unmarshal(root["delta"], &delta)
return c.toolDelta(itemID, delta)
case "response.function_call_arguments.done":
var itemID, arguments string
_ = json.Unmarshal(root["item_id"], &itemID)
_ = json.Unmarshal(root["arguments"], &arguments)
return c.toolArgumentsDone(itemID, arguments)
case "response.output_item.done":
var item responseItem
_ = json.Unmarshal(root["item"], &item)
if item.Type == "function_call" {
return c.toolDone(item.ID)
return c.toolArgumentsDone(item.ID, item.Arguments)
}
if item.Type == "reasoning" {
return c.thinkingDone(item)
}
case "response.completed", "response.incomplete":
var response responseEnvelope
_ = json.Unmarshal(root["response"], &response)
c.setResponse(response)
return c.done(response.Status)
status := response.Status
if status == "" && typeName == "response.incomplete" {
status = "incomplete"
}
return c.done(status)
case "error", "response.failed":
return c.streamError(data)
}
@@ -147,7 +192,7 @@ func (c *streamConverter) start() error {
}
return c.writeEvent("message_start", map[string]any{
"type": "message_start", "message": map[string]any{
"id": strings.Replace(c.id, "resp_", "msg_", 1), "type": "message", "role": "assistant",
"id": anthropicMessageID(c.id), "type": "message", "role": "assistant",
"model": c.model, "content": []any{}, "stop_reason": nil, "stop_sequence": nil,
"usage": anthropicUsage(c.usage),
},
@@ -166,7 +211,60 @@ func (c *streamConverter) textDelta(delta string) error {
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}})
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 {
@@ -183,9 +281,10 @@ 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}
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++
}
c.tools[item.ID] = tool
@@ -205,6 +304,8 @@ func (c *streamConverter) toolDelta(itemID, delta string) error {
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}}}})
}
@@ -214,15 +315,42 @@ func (c *streamConverter) toolDelta(itemID, delta string) error {
})
}
func (c *streamConverter) toolDone(itemID string) error {
func (c *streamConverter) toolArgumentsDone(itemID, arguments string) error {
tool, ok := c.tools[itemID]
if !ok || c.operation != OperationMessages {
if !ok || tool.Closed {
return nil
}
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})
}
func (c *streamConverter) done(status string) error {
if c.finished {
return nil
}
if err := c.start(); err != nil {
return err
}
@@ -239,31 +367,78 @@ func (c *streamConverter) done(status string) error {
}); err != nil {
return err
}
c.finished = true
_, err := io.WriteString(c.writer, "data: [DONE]\n\n")
return err
}
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": nil},
"type": "message_delta", "delta": map[string]any{"stop_reason": stopReason, "stop_sequence": nullableAnthropicString(c.stopSequence)},
"usage": map[string]any{"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}})
}
func (c *streamConverter) streamError(data []byte) error {
if c.operation == OperationMessages {
c.finished = true
return c.writeEvent("error", map[string]any{"type": "error", "error": map[string]any{"type": "api_error", "message": string(data)}})
}
if err := c.writeData(json.RawMessage(data)); err != nil {
@@ -273,7 +448,12 @@ func (c *streamConverter) streamError(data []byte) error {
return err
}
func (c *streamConverter) finish() error { return nil }
func (c *streamConverter) finish() error {
if c.finished {
return nil
}
return c.done("")
}
func (c *streamConverter) writeData(value any) error {
data, err := json.Marshal(value)
@@ -293,6 +473,69 @@ 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
+350 -21
View File
@@ -103,12 +103,14 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
if request.Method != http.MethodPost {
return jsonProviderResponse(http.StatusMethodNotAllowed, map[string]any{"error": map[string]any{"message": "method not allowed"}}), nil
}
var conversationOptions conversation.ResponseOptions
if request.Operation == conversation.OperationMessages {
converted, err := conversation.ConvertRequest(request.Body, request.Model, request.Operation)
converted, options, err := conversation.ConvertRequestWithOptions(request.Body, request.Model, request.Operation)
if err != nil {
return jsonProviderResponse(http.StatusBadRequest, map[string]any{"type": "error", "error": map[string]any{"type": "invalid_request_error", "message": err.Error()}}), nil
}
request.Body = converted
conversationOptions = options
}
var input openAIRequest
@@ -173,7 +175,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
if streaming {
prepared, preflightErr := preflightUpstream(upstream.Body)
if preflightErr == nil {
body := a.streamOpenAIResponse(ctx, prepared, lease, request.Credential, responseID, input.Model, request.Operation, normalized.Prompt, previous, tools, parallelTools)
body := a.streamOpenAIResponse(ctx, prepared, lease, request.Credential, responseID, input.Model, request.Operation, normalized.Prompt, previous, tools, parallelTools, conversationOptions)
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: streamHeaders(), Body: body}, nil
}
if errors.Is(preflightErr, errWebAntiBot) && attempt == 0 && a.invalidateSignedStatsig(http.MethodPost, statsigTarget) {
@@ -216,7 +218,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
if err := a.archiveChatImages(ctx, request.Credential, &parsed); err != nil {
return nil, err
}
payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false)
payload := buildOpenAIResult(request.Operation, responseID, input.Model, parsed, false, conversationOptions)
data, err := json.Marshal(payload)
if err != nil {
return nil, err
@@ -349,7 +351,7 @@ func (a *Adapter) handleResponseResource(ctx context.Context, request provider.R
return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: jsonHeaders(), Body: io.NopCloser(strings.NewReader(state.ResponseJSON))}, nil
}
func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser, lease *infraegress.Lease, credential account.Credential, responseID, model, operation, prompt string, previous *inferencedomain.WebResponseState, tools toolConfiguration, parallelTools bool) io.ReadCloser {
func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser, lease *infraegress.Lease, credential account.Credential, responseID, model, operation, prompt string, previous *inferencedomain.WebResponseState, tools toolConfiguration, parallelTools bool, options conversation.ResponseOptions) io.ReadCloser {
reader, writer := io.Pipe()
go func() {
defer source.Close()
@@ -367,7 +369,10 @@ func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser
if len(tools.Functions) > 0 && tools.Choice != "none" {
sieve = newToolStreamSieve(tools.available)
}
writeStreamStart(writer, operation, responseID, model, parsed.InputTokens)
messagesStream := newWebMessagesStream(writer, responseID, model, parsed.InputTokens, options)
if operation != conversation.OperationMessages {
writeStreamStart(writer, operation, responseID, model, parsed.InputTokens)
}
err := consumeUpstreamInto(source, parsed, func(kind, delta string) error {
if len(parsed.ToolCalls) > 0 && kind != "reasoning" {
return nil
@@ -390,24 +395,24 @@ func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser
result := sieve.Feed(delta)
if result.SafeText != "" {
clientText.WriteString(result.SafeText)
if err := writeStreamDelta(writer, operation, responseID, model, kind, result.SafeText); err != nil {
if err := writeWebStreamDelta(writer, messagesStream, operation, responseID, model, kind, result.SafeText); err != nil {
return err
}
}
if result.Complete {
if len(result.Calls) == 0 {
clientText.WriteString(result.Raw)
return writeStreamDelta(writer, operation, responseID, model, kind, result.Raw)
return writeWebStreamDelta(writer, messagesStream, operation, responseID, model, kind, result.Raw)
}
parsed.ToolCalls = result.Calls
return writeStreamToolCalls(writer, operation, responseID, model, result.Calls)
return writeWebStreamToolCalls(writer, messagesStream, operation, responseID, model, result.Calls)
}
return nil
}
if kind == "text" {
clientText.WriteString(delta)
}
return writeStreamDelta(writer, operation, responseID, model, kind, delta)
return writeWebStreamDelta(writer, messagesStream, operation, responseID, model, kind, delta)
})
if err != nil {
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err)
@@ -418,14 +423,14 @@ func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser
result := sieve.Flush()
if result.SafeText != "" {
clientText.WriteString(result.SafeText)
if err := writeStreamDelta(writer, operation, responseID, model, "text", result.SafeText); err != nil {
if err := writeWebStreamDelta(writer, messagesStream, operation, responseID, model, "text", result.SafeText); err != nil {
_ = writer.CloseWithError(err)
return
}
}
if len(result.Calls) > 0 {
parsed.ToolCalls = result.Calls
if err := writeStreamToolCalls(writer, operation, responseID, model, result.Calls); err != nil {
if err := writeWebStreamToolCalls(writer, messagesStream, operation, responseID, model, result.Calls); err != nil {
_ = writer.CloseWithError(err)
return
}
@@ -446,7 +451,7 @@ func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser
delta = "\n\n" + delta
}
clientText.WriteString(delta)
if err := writeStreamDelta(writer, operation, responseID, model, "text", delta); err != nil {
if err := writeWebStreamDelta(writer, messagesStream, operation, responseID, model, "text", delta); err != nil {
_ = writer.CloseWithError(err)
return
}
@@ -455,12 +460,19 @@ func (a *Adapter) streamOpenAIResponse(ctx context.Context, source io.ReadCloser
parsed.Text.Reset()
parsed.Text.WriteString(clientText.String())
a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, http.StatusOK, nil)
payload := buildOpenAIResult(operation, responseID, model, *parsed, false)
payload := buildOpenAIResult(operation, responseID, model, *parsed, false, options)
data, _ := json.Marshal(payload)
if operation == conversation.OperationResponses {
a.saveResponseState(context.WithoutCancel(ctx), credential.ID, responseID, *parsed, data)
}
writeStreamDone(writer, operation, responseID, model, *parsed, payload)
if operation == conversation.OperationMessages {
if finishErr := messagesStream.Finish(*parsed, payload); finishErr != nil {
_ = writer.CloseWithError(finishErr)
return
}
} else {
writeStreamDone(writer, operation, responseID, model, *parsed, payload)
}
_ = writer.Close()
}()
return reader
@@ -619,8 +631,10 @@ func contentTextAndImages(raw json.RawMessage) (string, []string, error) {
} else {
return "", nil, errors.New("图片内容缺少 image_url")
}
case "input_audio", "file":
case "input_audio", "file", "input_file":
return "", nil, fmt.Errorf("Grok Web 对话暂不支持 %s 内容", typeName)
default:
return "", nil, fmt.Errorf("Grok Web 对话暂不支持 content.type=%q", typeName)
}
}
return strings.Join(values, "\n"), images, nil
@@ -1123,8 +1137,12 @@ func searchSourceTitle(sources []map[string]any, rawURL string) string {
return rawURL
}
func buildOpenAIResult(operation, responseID, model string, parsed parsedChat, streaming bool) map[string]any {
func buildOpenAIResult(operation, responseID, model string, parsed parsedChat, streaming bool, responseOptions ...conversation.ResponseOptions) map[string]any {
created := time.Now().Unix()
options := conversation.ResponseOptions{}
if len(responseOptions) > 0 {
options = responseOptions[0]
}
inputTokens := parsed.InputTokens
outputTokens := estimateTokens(parsed.Text.String()) + estimateTokens(parsed.Reasoning.String()) + estimateToolCallTokens(parsed.ToolCalls)
if operation == "chat" {
@@ -1151,24 +1169,30 @@ func buildOpenAIResult(operation, responseID, model string, parsed parsedChat, s
return value
}
if operation == conversation.OperationMessages {
content := make([]any, 0, len(parsed.ToolCalls)+1)
if parsed.Text.Len() > 0 || len(parsed.ToolCalls) == 0 {
content = append(content, map[string]any{"type": "text", "text": parsed.Text.String()})
visibleText, stopSequence := applyWebStopSequences(parsed.Text.String(), options.StopSequences)
content := make([]any, 0, len(parsed.ToolCalls)+2)
if options.AnthropicThinking && parsed.Reasoning.Len() > 0 {
content = append(content, map[string]any{"type": "thinking", "thinking": parsed.Reasoning.String()})
}
if visibleText != "" || len(parsed.ToolCalls) == 0 {
content = append(content, map[string]any{"type": "text", "text": visibleText})
}
for _, call := range parsed.ToolCalls {
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": call.ID, "name": call.Name, "input": input})
content = append(content, map[string]any{"type": "tool_use", "id": webAnthropicToolID(call.ID), "name": call.Name, "input": input})
}
stopReason := "end_turn"
if len(parsed.ToolCalls) > 0 {
stopReason = "tool_use"
} else if stopSequence != "" {
stopReason = "stop_sequence"
}
return map[string]any{
"id": strings.Replace(responseID, "resp_", "msg_", 1), "type": "message", "role": "assistant", "model": model,
"content": content, "stop_reason": stopReason, "stop_sequence": nil,
"content": content, "stop_reason": stopReason, "stop_sequence": nullableWebString(stopSequence),
"usage": map[string]any{"input_tokens": inputTokens, "output_tokens": outputTokens, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0},
}
}
@@ -1213,6 +1237,38 @@ func buildOpenAIResult(operation, responseID, model string, parsed parsedChat, s
}
}
func applyWebStopSequences(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 nullableWebString(value string) any {
if value == "" {
return nil
}
return value
}
func webAnthropicToolID(value string) string {
if strings.HasPrefix(value, "toolu_") {
return value
}
return "toolu_" + value
}
func chatToolCalls(calls []parsedToolCall) []any {
values := make([]any, 0, len(calls))
for _, call := range calls {
@@ -1246,6 +1302,279 @@ func estimateToolCallTokens(calls []parsedToolCall) int64 {
return total
}
type webMessagesStream struct {
writer io.Writer
responseID string
model string
inputTokens int64
options conversation.ResponseOptions
started bool
thinkingStarted bool
thinkingClosed bool
thinkingIndex int
textStarted bool
textClosed bool
textIndex int
nextIndex int
hasTools bool
stopSequence string
stopFilter *webStopFilter
}
func newWebMessagesStream(writer io.Writer, responseID, model string, inputTokens int64, options conversation.ResponseOptions) *webMessagesStream {
return &webMessagesStream{
writer: writer, responseID: responseID, model: model, inputTokens: inputTokens,
options: options, stopFilter: newWebStopFilter(options.StopSequences),
}
}
func (s *webMessagesStream) Start() error {
if s.started {
return nil
}
s.started = true
return writeSSE(s.writer, "message_start", map[string]any{
"type": "message_start", "message": map[string]any{
"id": strings.Replace(s.responseID, "resp_", "msg_", 1), "type": "message", "role": "assistant", "model": s.model,
"content": []any{}, "stop_reason": nil, "stop_sequence": nil,
"usage": map[string]any{"input_tokens": s.inputTokens, "output_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0},
},
})
}
func (s *webMessagesStream) Delta(kind, delta string) error {
if err := s.Start(); err != nil {
return err
}
if s.stopSequence != "" {
return nil
}
if kind == "reasoning" {
if !s.options.AnthropicThinking {
return nil
}
if !s.thinkingStarted {
s.thinkingStarted = true
s.thinkingIndex = s.nextIndex
s.nextIndex++
if err := writeSSE(s.writer, "content_block_start", map[string]any{
"type": "content_block_start", "index": s.thinkingIndex,
"content_block": map[string]any{"type": "thinking", "thinking": ""},
}); err != nil {
return err
}
}
return writeSSE(s.writer, "content_block_delta", map[string]any{
"type": "content_block_delta", "index": s.thinkingIndex,
"delta": map[string]any{"type": "thinking_delta", "thinking": delta},
})
}
if kind != "text" {
return nil
}
if err := s.startText(); err != nil {
return err
}
emit, matched := s.stopFilter.Push(delta)
if matched != "" {
s.stopSequence = matched
}
if emit == "" {
return nil
}
return s.writeTextDelta(emit)
}
func (s *webMessagesStream) startText() error {
if s.textStarted && !s.textClosed {
return nil
}
if err := s.closeThinking(); err != nil {
return err
}
s.textStarted = true
s.textClosed = false
s.textIndex = s.nextIndex
s.nextIndex++
return writeSSE(s.writer, "content_block_start", map[string]any{
"type": "content_block_start", "index": s.textIndex,
"content_block": map[string]any{"type": "text", "text": ""},
})
}
func (s *webMessagesStream) writeTextDelta(delta string) error {
if delta == "" {
return nil
}
return writeSSE(s.writer, "content_block_delta", map[string]any{
"type": "content_block_delta", "index": s.textIndex,
"delta": map[string]any{"type": "text_delta", "text": delta},
})
}
func (s *webMessagesStream) Tools(calls []parsedToolCall) error {
if err := s.Start(); err != nil {
return err
}
if err := s.closeThinking(); err != nil {
return err
}
if err := s.closeText(); err != nil {
return err
}
for _, call := range calls {
index := s.nextIndex
s.nextIndex++
id := webAnthropicToolID(call.ID)
if err := writeSSE(s.writer, "content_block_start", map[string]any{
"type": "content_block_start", "index": index,
"content_block": map[string]any{"type": "tool_use", "id": id, "name": call.Name, "input": map[string]any{}},
}); err != nil {
return err
}
if err := writeSSE(s.writer, "content_block_delta", map[string]any{
"type": "content_block_delta", "index": index,
"delta": map[string]any{"type": "input_json_delta", "partial_json": call.Arguments},
}); err != nil {
return err
}
if err := writeSSE(s.writer, "content_block_stop", map[string]any{"type": "content_block_stop", "index": index}); err != nil {
return err
}
s.hasTools = true
}
return nil
}
func (s *webMessagesStream) Finish(parsed parsedChat, payload map[string]any) error {
if err := s.Start(); err != nil {
return err
}
if s.stopSequence == "" {
if pending := s.stopFilter.Flush(); pending != "" {
if err := s.startText(); err != nil {
return err
}
if err := s.writeTextDelta(pending); err != nil {
return err
}
}
}
if err := s.closeThinking(); err != nil {
return err
}
if err := s.closeText(); err != nil {
return err
}
stopReason := "end_turn"
if s.hasTools || len(parsed.ToolCalls) > 0 {
stopReason = "tool_use"
} else if s.stopSequence != "" {
stopReason = "stop_sequence"
}
usage, _ := payload["usage"].(map[string]any)
if err := writeSSE(s.writer, "message_delta", map[string]any{
"type": "message_delta", "delta": map[string]any{"stop_reason": stopReason, "stop_sequence": nullableWebString(s.stopSequence)},
"usage": map[string]any{"output_tokens": usage["output_tokens"]},
}); err != nil {
return err
}
return writeSSE(s.writer, "message_stop", map[string]any{"type": "message_stop"})
}
func (s *webMessagesStream) closeThinking() error {
if !s.thinkingStarted || s.thinkingClosed {
return nil
}
s.thinkingClosed = true
return writeSSE(s.writer, "content_block_stop", map[string]any{"type": "content_block_stop", "index": s.thinkingIndex})
}
func (s *webMessagesStream) closeText() error {
if !s.textStarted || s.textClosed {
return nil
}
s.textClosed = true
return writeSSE(s.writer, "content_block_stop", map[string]any{"type": "content_block_stop", "index": s.textIndex})
}
func writeWebStreamDelta(writer io.Writer, stream *webMessagesStream, operation, responseID, model, kind, delta string) error {
if operation == conversation.OperationMessages {
return stream.Delta(kind, delta)
}
return writeStreamDelta(writer, operation, responseID, model, kind, delta)
}
func writeWebStreamToolCalls(writer io.Writer, stream *webMessagesStream, operation, responseID, model string, calls []parsedToolCall) error {
if operation == conversation.OperationMessages {
return stream.Tools(calls)
}
return writeStreamToolCalls(writer, operation, responseID, model, calls)
}
type webStopFilter struct {
sequences []string
pending string
matched string
}
func newWebStopFilter(sequences []string) *webStopFilter {
filtered := make([]string, 0, len(sequences))
for _, sequence := range sequences {
if sequence != "" {
filtered = append(filtered, sequence)
}
}
return &webStopFilter{sequences: filtered}
}
func (f *webStopFilter) 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 *webStopFilter) Flush() string {
if f == nil || f.matched != "" {
return ""
}
value := f.pending
f.pending = ""
return value
}
func writeStreamStart(writer io.Writer, operation, responseID, model string, inputTokens int64) {
if operation == "chat" {
chunk := map[string]any{"id": strings.Replace(responseID, "resp_", "chatcmpl_", 1), "object": "chat.completion.chunk", "created": time.Now().Unix(), "model": model, "choices": []any{map[string]any{"index": 0, "delta": map[string]any{"role": "assistant"}, "finish_reason": nil}}}
@@ -123,6 +123,18 @@ func TestNormalizeResponsesInputImage(t *testing.T) {
}
}
func TestNormalizeResponsesInputFileFailsExplicitly(t *testing.T) {
input, _ := json.Marshal([]any{map[string]any{
"type": "message", "role": "user", "content": []any{
map[string]any{"type": "input_file", "file_url": "https://example.com/a.pdf"},
},
}})
_, err := normalizeOpenAIInput(openAIRequest{Input: input}, "responses")
if err == nil || !strings.Contains(err.Error(), "input_file") {
t.Fatalf("error = %v", err)
}
}
func TestParseChatImageDataURIValidatesContent(t *testing.T) {
value := "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII="
image, err := parseChatImageDataURI(value, 1<<20)
@@ -1,9 +1,12 @@
package web
import (
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
)
func TestParseToolConfigurationSupportsChatAndResponsesSchemas(t *testing.T) {
@@ -86,6 +89,45 @@ func TestParseToolCallsBuildsStandardResults(t *testing.T) {
}
}
func TestBuildMessagesResultPreservesThinkingAndStopSequence(t *testing.T) {
parsed := parsedChat{}
parsed.Reasoning.WriteString("thought")
parsed.Text.WriteString("ABCSTOPXYZ")
result := buildOpenAIResult("messages", "resp_test", "grok-chat-fast", parsed, false, conversation.ResponseOptions{
AnthropicThinking: true, StopSequences: []string{"STOP"},
})
content := result["content"].([]any)
if result["stop_reason"] != "stop_sequence" || result["stop_sequence"] != "STOP" || len(content) != 2 {
t.Fatalf("result = %#v", result)
}
if content[0].(map[string]any)["type"] != "thinking" || content[1].(map[string]any)["text"] != "ABC" {
t.Fatalf("content = %#v", content)
}
}
func TestWebMessagesStreamPreservesThinkingAndSplitStopSequence(t *testing.T) {
var output bytes.Buffer
stream := newWebMessagesStream(&output, "resp_test", "grok-chat-fast", 3, conversation.ResponseOptions{
AnthropicThinking: true, StopSequences: []string{"STOP"},
})
for _, delta := range []struct{ kind, value string }{
{kind: "reasoning", value: "thought"},
{kind: "text", value: "ABCST"},
{kind: "text", value: "OPXYZ"},
} {
if err := stream.Delta(delta.kind, delta.value); err != nil {
t.Fatal(err)
}
}
if err := stream.Finish(parsedChat{}, map[string]any{"usage": map[string]any{"output_tokens": int64(2)}}); err != nil {
t.Fatal(err)
}
text := output.String()
if strings.Contains(text, "XYZ") || !strings.Contains(text, `"thinking":"thought"`) || !strings.Contains(text, `"text":"ABC"`) || !strings.Contains(text, `"stop_reason":"stop_sequence"`) {
t.Fatalf("stream = %s", text)
}
}
func TestToolStreamSieveHandlesSplitXML(t *testing.T) {
sieve := newToolStreamSieve(map[string]struct{}{"lookup": {}})
first := sieve.Feed("before <tool_ca")
@@ -1001,6 +1001,7 @@ func writeOpenAIError(c *gin.Context, status int, code, message string) {
func writeGatewayError(c *gin.Context, err error) {
status, code := http.StatusBadGateway, "upstream_unavailable"
message := "上游服务暂不可用"
var upstreamFailure *gateway.UpstreamFailure
switch {
case errors.Is(err, clientkeyapp.ErrBillingLimit):
status, code = http.StatusTooManyRequests, "billing_limit_exceeded"
@@ -1011,6 +1012,8 @@ func writeGatewayError(c *gin.Context, err error) {
case errors.Is(err, gateway.ErrResponseNotFound):
status, code = http.StatusNotFound, "response_not_found"
message = "Response 不存在或已过期"
case errors.As(err, &upstreamFailure):
status, code, message = upstreamFailure.HTTPStatus, upstreamFailure.Code, upstreamFailure.PublicMessage
case errors.Is(err, gateway.ErrResponseAccountUnavailable), errors.Is(err, gateway.ErrNoAvailableAccount):
status, code = http.StatusServiceUnavailable, "upstream_unavailable"
message = "当前没有可用的上游账号"
@@ -1021,6 +1024,7 @@ func writeGatewayError(c *gin.Context, err error) {
func writeGatewayAnthropicError(c *gin.Context, err error) {
status, errorType := http.StatusBadGateway, "api_error"
message := "上游服务暂不可用"
var upstreamFailure *gateway.UpstreamFailure
switch {
case errors.Is(err, clientkeyapp.ErrBillingLimit):
status, errorType = http.StatusTooManyRequests, "rate_limit_error"
@@ -1028,6 +1032,11 @@ func writeGatewayAnthropicError(c *gin.Context, err error) {
case errors.Is(err, gateway.ErrModelNotFound):
status, errorType = http.StatusNotFound, "not_found_error"
message = "模型不存在"
case errors.As(err, &upstreamFailure):
status, message = upstreamFailure.HTTPStatus, upstreamFailure.PublicMessage
if status == http.StatusTooManyRequests {
errorType = "rate_limit_error"
}
case errors.Is(err, gateway.ErrResponseAccountUnavailable), errors.Is(err, gateway.ErrNoAvailableAccount):
status, errorType = http.StatusServiceUnavailable, "overloaded_error"
message = "当前没有可用的上游账号"
@@ -10,6 +10,7 @@ import (
"testing"
"time"
"github.com/chenyme/grok2api/backend/internal/application/gateway"
mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media"
"github.com/gin-gonic/gin"
)
@@ -102,6 +103,34 @@ func TestGatewayErrorDoesNotExposeInternalDetails(t *testing.T) {
}
}
func TestGatewayErrorPreservesSanitizedUpstreamClassification(t *testing.T) {
gin.SetMode(gin.TestMode)
openAIRouter := gin.New()
openAIRouter.GET("/", func(c *gin.Context) {
writeGatewayError(c, &gateway.UpstreamFailure{
HTTPStatus: http.StatusForbidden, Code: "upstream_forbidden", PublicMessage: "上游拒绝了该请求",
Cause: errors.New("secret upstream response"),
})
})
openAIRecorder := httptest.NewRecorder()
openAIRouter.ServeHTTP(openAIRecorder, httptest.NewRequest(http.MethodGet, "/", nil))
if openAIRecorder.Code != http.StatusForbidden || !strings.Contains(openAIRecorder.Body.String(), `"code":"upstream_forbidden"`) || strings.Contains(openAIRecorder.Body.String(), "secret") {
t.Fatalf("OpenAI status=%d body=%s", openAIRecorder.Code, openAIRecorder.Body.String())
}
anthropicRouter := gin.New()
anthropicRouter.GET("/", func(c *gin.Context) {
writeGatewayAnthropicError(c, &gateway.UpstreamFailure{
HTTPStatus: http.StatusTooManyRequests, Code: "upstream_rate_limited", PublicMessage: "上游请求频率受限",
})
})
anthropicRecorder := httptest.NewRecorder()
anthropicRouter.ServeHTTP(anthropicRecorder, httptest.NewRequest(http.MethodGet, "/", nil))
if anthropicRecorder.Code != http.StatusTooManyRequests || !strings.Contains(anthropicRecorder.Body.String(), `"type":"rate_limit_error"`) {
t.Fatalf("Anthropic status=%d body=%s", anthropicRecorder.Code, anthropicRecorder.Body.String())
}
}
func TestMessagesEndpointUsesAnthropicContract(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
+3 -3
View File
@@ -298,9 +298,9 @@ const resources = {
selectAccountRequired: "至少选择一个账号",
noBindableAccounts: "当前来源没有可绑定账号",
deleteTitle: "删除模型路由?",
deleteDescription: "将删除 {{name}} 及其密钥权限关联;后续模型同步不会自动重新创建。",
deleteDescription: "将删除 {{name}} 及其密钥权限关联;如果上游账号仍支持该模型,后续同步会重新创建。",
batchDeleteTitle: "删除所选 {{count}} 个模型路由?",
batchDeleteDescription: "将同时删除所选路由及其密钥权限关联;后续模型同步不会自动重新创建。",
batchDeleteDescription: "将同时删除所选路由及其密钥权限关联;上游账号仍支持的模型会在后续同步时重新创建。",
synced: "已同步 {{count}} 个模型",
created: "模型路由已创建",
updated: "模型路由已更新",
@@ -644,7 +644,7 @@ const resources = {
shell: { appearance: "Appearance", dark: "Dark", light: "Light", system: "System", language: "Language", navigation: "Navigation", openNavigation: "Open navigation" },
dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", resourcesTitle: "Resource status", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 models", model: "Model", share: "Call share", noTopModels: "No model calls in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" },
accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "The selected {{count}} accounts will use SSO to complete Device OAuth automatically. Linked accounts are skipped and conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens directly. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export all accounts", exported: "Account credentials exported", exportTitle: "Export all account credentials?", exportDescription: "The exported JSON contains OAuth credentials that can access the upstream service. Store it only in a trusted location and never upload, share, or commit it to version control.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", totalAccounts: "Total accounts", providerAccountBreakdown: "Grok Build {{build}} · Grok Web {{web}}", availableAccounts: "Routable accounts", providerAvailableBreakdown: "Build available {{build}} · Web available {{web}}", recoveringAccounts: "Waiting for recovery", recoveryBreakdown: "Cooling {{cooldown}} · Reset {{reset}} · Probing {{probing}}", attentionAccounts: "Needs attention", issueBreakdown: "Disabled {{disabled}} · Authorization expired {{reauth}}", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitLine truncated
models: { title: "Model routes", description: "Map public model IDs to Grok Build and Grok Web upstream models.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a custom Grok Build upstream model and configure its public ID and routable accounts. Grok Web continues to use the built-in catalog.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "When enabled, only selected accounts are routed and treated as manually confirmed to support the model. Otherwise model sync decides automatically.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. Future model syncs will not recreate it automatically.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Future model syncs will not recreate them automatically.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" },
models: { title: "Model routes", description: "Map public model IDs to Grok Build and Grok Web upstream models.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a custom Grok Build upstream model and configure its public ID and routable accounts. Grok Web continues to use the built-in catalog.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "When enabled, only selected accounts are routed and treated as manually confirmed to support the model. Otherwise model sync decides automatically.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" },
keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", allModels: "All models", modelSearch: "Search models. Leave blank to allow all models.", selectedModels: "{{count}} models selected", neverExpires: "Never expires", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely. It is hidden by default in the list and can be copied again later.", secretLabel: "Complete key", copySecret: "Copy complete key", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" },
audits: { title: "Request audits", description: "Stores routing, status, latency, and usage details only. Request and response bodies are never saved.", search: "Search request ID or model", request: "Request ID", route: "Route", status: "Status", mode: "Mode", tokens: "Details", billing: "Billing", duration: "Duration", createdAt: "Time", stream: "Streaming", nonStream: "Non-streaming", cursorPage: "Page {{page}}", key: "Key", keyFilterPlaceholder: "Enter key name or ID", model: "Model", account: "Account", accountFilterPlaceholder: "Enter account name or ID", owningAccount: "Account", owningKey: "Client key", routeDetails: "View routing details", statusSuccess: "Success", statusClientError: "Client error", statusServerError: "Server error", usageSummary: "Usage summary", totalRequests: "Total requests", requestBreakdown: "{{success}} succeeded · {{failed}} failed", totalTokens: "Total tokens", tokenEfficiency: "Cache hit rate {{cacheRate}}%", tokenBreakdown: "Input {{input}} · Output {{output}} · Cached {{cached}} · Reasoning {{reasoning}}", successRate: "Success rate", averageDuration: "Average duration {{duration}}", estimatedCost: "Estimated cost", pricingCoverage: "{{priced}} priced · {{unpriced}} unpriced", pricingDescription: "Calculated using the latest official xAI model prices. Models without a listed price are excluded.", total: "Total", input: "Input", output: "Output", mediaInput: "Media Input", imageCount: "{{count}} images", secondsCount: "{{count}} sec", cached: "Cached", reasoning: "Reasoning", costUsd: "Cost ${{value}}", sources: "Sources {{count}}", serverTools: "Server tools called {{count}} times" },
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" }, egress: { title: "Egress proxies", description: "Nodes manage proxy and health independently for Grok Build, Grok Web, or Web assets. Build inherits the Provider User-Agent; Web 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 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" } },