mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
fix(grok): normalize delegated message input for Responses
This commit is contained in:
1 parent
d851a38477
commit
522f1fb999
6 files changed
+144
-9
No files matched your search
@@ -584,7 +584,7 @@ func buildChatMessagesFromItems(messages []ChatMessage, rawItems []json.RawMessa
|
||||
// input_text 是信封(消息类型、任务名、发送者),正文放在 encrypted_content 片段里
|
||||
// (自定义 provider 下为明文)。chat 上游没有对应条目,按原顺序拼成一条 user 消息,
|
||||
// 否则子智能体收不到任务却仍返回 200。
|
||||
text := agentMessageText(item["content"])
|
||||
text := AgentMessageText(item["content"])
|
||||
if text == "" {
|
||||
pendingReasoning = ""
|
||||
continue
|
||||
@@ -653,8 +653,9 @@ func buildChatMessagesFromItems(messages []ChatMessage, rawItems []json.RawMessa
|
||||
return messages, mediaByCallID, nil
|
||||
}
|
||||
|
||||
// agentMessageText 按原顺序拼接 agent_message 里 input_text 与 encrypted_content 片段的文本。
|
||||
func agentMessageText(raw json.RawMessage) string {
|
||||
// AgentMessageText concatenates agent_message text and plaintext encrypted_content
|
||||
// parts in their original order without attempting to decrypt their contents.
|
||||
func AgentMessageText(raw json.RawMessage) string {
|
||||
raw = bytesTrimSpace(raw)
|
||||
if len(raw) == 0 || string(raw) == "null" {
|
||||
return ""
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/apicompat"
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/tidwall/sjson"
|
||||
)
|
||||
@@ -69,6 +70,18 @@ func sanitizeGrokResponsesModelInput(body []byte) ([]byte, error) {
|
||||
pendingOutputImages = pendingOutputImages[:0]
|
||||
|
||||
switch itemType {
|
||||
case "agent_message":
|
||||
content, err := json.Marshal(item["content"])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serialize Grok agent message content: %w", err)
|
||||
}
|
||||
text := apicompat.AgentMessageText(content)
|
||||
if text == "" {
|
||||
continue
|
||||
}
|
||||
role = "user"
|
||||
item = map[string]any{"type": "message", "role": role, "content": text}
|
||||
itemType = "message"
|
||||
case "text", "input_text", "output_text":
|
||||
text := strings.TrimSpace(grokStringValue(item["text"]))
|
||||
if text == "" {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"testing"
|
||||
@@ -9,6 +10,61 @@ import (
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func TestSanitizeGrokResponsesModelInputAgentMessage(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
content string
|
||||
text string
|
||||
}{
|
||||
{"text only", `[{"type":"input_text","text":"What is 19 plus 23?"}]`, "What is 19 plus 23?"},
|
||||
{"envelope and plaintext payload", `[{"type":"input_text","text":"Message Type: NEW_TASK\nPayload:\n"},{"type":"encrypted_content","encrypted_content":"Review the code"},{"type":"text","text":"\nthen report"},{"type":"encrypted_content","encrypted_content":" back. "}]`, "Message Type: NEW_TASK\nPayload:\nReview the code\nthen report back. "},
|
||||
{"string content", `" task\n"`, " task\n"},
|
||||
{"opaque content is not decrypted", `[{"type":"encrypted_content","encrypted_content":"gAAAAABopaque=="}]`, "gAAAAABopaque=="},
|
||||
{"empty content", `[]`, ""},
|
||||
{"null content", `null`, ""},
|
||||
{"unsupported content", `[{"type":"input_image","image_url":"https://example.com/image.png"},{"type":"output_text","text":"ignored"}]`, ""},
|
||||
{"malformed content", `{"text":"ignored"}`, ""},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
body := []byte(`{"input":[{"type":"agent_message","id":"amsg_1","author":"/root","recipient":"/root/child","role":"assistant","content":` + tt.content + `}]}`)
|
||||
patched, err := sanitizeGrokResponsesModelInput(body)
|
||||
require.NoError(t, err)
|
||||
if tt.text == "" {
|
||||
require.Empty(t, gjson.GetBytes(patched, "input").Array())
|
||||
return
|
||||
}
|
||||
expected, err := json.Marshal([]map[string]any{{"type": "message", "role": "user", "content": tt.text}})
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, string(expected), gjson.GetBytes(patched, "input").Raw)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeGrokResponsesModelInputAgentMessageMixedHistory(t *testing.T) {
|
||||
body := []byte(`{"input":[
|
||||
{"type":"message","role":"user","content":"start"},
|
||||
{"type":"agent_message","author":"/root","recipient":"/root/child","content":[{"type":"input_text","text":"Payload:\n"},{"type":"encrypted_content","encrypted_content":"task"}]},
|
||||
{"type":"message","role":"assistant","content":"working"},
|
||||
{"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"call_1","output":"found"},
|
||||
{"type":"agent_message","content":[]},
|
||||
{"type":"agent_message","author":"/root/child","recipient":"/root","content":[{"type":"input_text","text":"result"}]},
|
||||
{"type":"message","role":"user","content":"continue"}
|
||||
]}`)
|
||||
patched, err := sanitizeGrokResponsesModelInput(body)
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, `[
|
||||
{"type":"message","role":"user","content":"start"},
|
||||
{"type":"message","role":"user","content":"Payload:\ntask"},
|
||||
{"type":"message","role":"assistant","content":"working"},
|
||||
{"type":"function_call","call_id":"call_1","name":"lookup","arguments":"{}"},
|
||||
{"type":"function_call_output","call_id":"call_1","output":"found"},
|
||||
{"type":"message","role":"user","content":"result"},
|
||||
{"type":"message","role":"user","content":"continue"}
|
||||
]`, gjson.GetBytes(patched, "input").Raw)
|
||||
}
|
||||
|
||||
func TestSanitizeGrokResponsesModelInputNormalizesReplayHistory(t *testing.T) {
|
||||
body := []byte(`{
|
||||
"input":[
|
||||
|
||||
@@ -2041,6 +2041,71 @@ func TestForwardGrokResponsesStreamingDefaultsEmptyModelTo45AndSnapshots(t *test
|
||||
require.NotNil(t, repo.updates[52][grokQuotaSnapshotExtraKey])
|
||||
}
|
||||
|
||||
func TestForwardGrokResponsesAgentMessage(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
for _, stream := range []bool{false, true} {
|
||||
for _, payload := range []struct {
|
||||
name string
|
||||
content string
|
||||
text string
|
||||
}{
|
||||
{"text", `[{"type":"input_text","text":"What is 19 plus 23?"}]`, "What is 19 plus 23?"},
|
||||
{"plaintext payload", `[{"type":"input_text","text":"Payload:\n"},{"type":"encrypted_content","encrypted_content":"What is 19 plus 23?"}]`, "Payload:\nWhat is 19 plus 23?"},
|
||||
} {
|
||||
t.Run(fmt.Sprintf("stream=%t/%s", stream, payload.name), func(t *testing.T) {
|
||||
body := []byte(fmt.Sprintf(`{"model":"grok-4.7","stream":%t,"input":[
|
||||
{"type":"message","role":"user","content":"history"},
|
||||
{"type":"agent_message","id":"amsg_repro","author":"/root","recipient":"/root/child","content":%s},
|
||||
{"type":"message","role":"assistant","content":"ready"}
|
||||
]}`, stream, payload.content))
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(body))
|
||||
account := &Account{
|
||||
ID: 53, Platform: PlatformGrok, Type: AccountTypeAPIKey,
|
||||
Credentials: map[string]any{"api_key": "xai-test-key", "base_url": "https://api.x.ai/v1"},
|
||||
}
|
||||
response := `{"id":"resp_agent","object":"response","model":"grok-4.7","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"42"}]}],"usage":{"input_tokens":5,"output_tokens":1}}`
|
||||
upstreamBody := response
|
||||
contentType := "application/json"
|
||||
if stream {
|
||||
contentType = "text/event-stream"
|
||||
upstreamBody = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"42\"}\n\ndata: {\"type\":\"response.completed\",\"response\":" + response + "}\n\n"
|
||||
}
|
||||
upstream := &httpUpstreamRecorder{resp: &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{contentType}},
|
||||
Body: io.NopCloser(strings.NewReader(upstreamBody)),
|
||||
}}
|
||||
svc := &OpenAIGatewayService{httpUpstream: upstream}
|
||||
result, err := svc.forwardGrokResponses(context.Background(), c, account, body, "grok-4.7", stream, time.Now())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "https://api.x.ai/v1/responses", upstream.lastReq.URL.String())
|
||||
require.Equal(t, stream, gjson.GetBytes(upstream.lastBody, "stream").Bool())
|
||||
expected, err := json.Marshal([]map[string]any{
|
||||
{"type": "message", "role": "user", "content": "history"},
|
||||
{"type": "message", "role": "user", "content": payload.text},
|
||||
{"type": "message", "role": "assistant", "content": "ready"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, string(expected), gjson.GetBytes(upstream.lastBody, "input").Raw)
|
||||
require.Equal(t, stream, result.Stream)
|
||||
require.Equal(t, "resp_agent", result.ResponseID)
|
||||
require.Equal(t, 5, result.Usage.InputTokens)
|
||||
require.Equal(t, 1, result.Usage.OutputTokens)
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
require.Contains(t, recorder.Header().Get("Content-Type"), contentType)
|
||||
if stream {
|
||||
require.Contains(t, recorder.Body.String(), `"delta":"42"`)
|
||||
require.Contains(t, recorder.Body.String(), `"type":"response.completed"`)
|
||||
} else {
|
||||
require.Equal(t, "42", gjson.GetBytes(recorder.Body.Bytes(), "output.0.content.0.text").String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardGrokResponsesAPIKeyUsesXAIResponses(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
"postcss@<8.5.18": ">=8.5.18",
|
||||
"dompurify@<3.4.17": ">=3.4.17",
|
||||
"source-map-js@<1.2.2": ">=1.2.2",
|
||||
"follow-redirects@<1.16.1": ">=1.16.1",
|
||||
"follow-redirects@<1.16.2": ">=1.16.2",
|
||||
"decode-uri-component@<0.5.1": ">=0.5.1"
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+5
-5
@@ -10,7 +10,7 @@ overrides:
|
||||
postcss@<8.5.18: '>=8.5.18'
|
||||
dompurify@<3.4.17: '>=3.4.17'
|
||||
source-map-js@<1.2.2: '>=1.2.2'
|
||||
follow-redirects@<1.16.1: '>=1.16.1'
|
||||
follow-redirects@<1.16.2: '>=1.16.2'
|
||||
decode-uri-component@<0.5.1: '>=0.5.1'
|
||||
|
||||
importers:
|
||||
@@ -2566,8 +2566,8 @@ packages:
|
||||
flatted@3.3.3:
|
||||
resolution: {integrity: sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==}
|
||||
|
||||
follow-redirects@1.16.1:
|
||||
resolution: {integrity: sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==}
|
||||
follow-redirects@1.16.2:
|
||||
resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
|
||||
engines: {node: '>=4.0'}
|
||||
peerDependencies:
|
||||
debug: '*'
|
||||
@@ -6563,7 +6563,7 @@ snapshots:
|
||||
|
||||
axios@1.20.0:
|
||||
dependencies:
|
||||
follow-redirects: 1.16.1
|
||||
follow-redirects: 1.16.2
|
||||
form-data: 4.0.6
|
||||
https-proxy-agent: 5.0.1
|
||||
proxy-from-env: 2.1.0
|
||||
@@ -7305,7 +7305,7 @@ snapshots:
|
||||
|
||||
flatted@3.3.3: {}
|
||||
|
||||
follow-redirects@1.16.1: {}
|
||||
follow-redirects@1.16.2: {}
|
||||
|
||||
for-in@1.0.2: {}
|
||||
|
||||
|
||||
Reference in new issue
Block a user