diff --git a/backend/internal/pkg/apicompat/responses_server_side_search.go b/backend/internal/pkg/apicompat/responses_server_side_search.go new file mode 100644 index 0000000000..b8dfe01066 --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_server_side_search.go @@ -0,0 +1,24 @@ +package apicompat + +import "strings" + +// IsServerSideSearchCall reports whether a Responses output item is a search +// that the xAI server runs itself, so the client has nothing to execute. +// +// xAI documents the Responses API form of X Search as a custom_tool_call whose +// call_id starts with xs_, and attachment search as one whose call_id starts +// with as_; both are "handled by the xAI server" +// (https://docs.x.ai/developers/tools/tool-usage-details, "Using Responses API" +// table; https://docs.x.ai/developers/tools/x-search, "How X Search Works"). +// A custom_tool_call without these prefixes is a client tool call. +// +// This is the only place the prefix rule lives. Converters that turn +// custom_tool_call items into client tool calls skip items for which it +// returns true when the caller says the upstream is xAI, and Grok search +// counting includes them. +func IsServerSideSearchCall(itemType, callID string) bool { + if itemType != "custom_tool_call" { + return false + } + return strings.HasPrefix(callID, "xs_") || strings.HasPrefix(callID, "as_") +} diff --git a/backend/internal/pkg/apicompat/responses_server_side_search_calls_test.go b/backend/internal/pkg/apicompat/responses_server_side_search_calls_test.go new file mode 100644 index 0000000000..cb2f9b3d75 --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_server_side_search_calls_test.go @@ -0,0 +1,189 @@ +package apicompat + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// serverSideSearchStream is the event sequence of one custom_tool_call item +// followed by a text answer, in the shape xAI documents for X Search. +func serverSideSearchStream(callID, name string) []*ResponsesStreamEvent { + item := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_1", CallID: callID, Name: name, Input: `{"query":"q"}`, Status: "completed"} + added := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_1", CallID: callID, Name: name} + message := ResponsesOutput{Type: "message", ID: "msg_1", Role: "assistant", Content: []ResponsesContentPart{{Type: "output_text", Text: "found it"}}} + return []*ResponsesStreamEvent{ + {Type: "response.created", Response: &ResponsesResponse{ID: "resp_1"}}, + {Type: "response.output_item.added", OutputIndex: 0, Item: &added}, + {Type: "response.custom_tool_call_input.delta", OutputIndex: 0, ItemID: "ctc_1", Delta: `{"query":"q"}`}, + {Type: "response.custom_tool_call_input.done", OutputIndex: 0, ItemID: "ctc_1", Input: `{"query":"q"}`}, + {Type: "response.output_item.done", OutputIndex: 0, Item: &item}, + {Type: "response.output_text.delta", OutputIndex: 1, Delta: "found it"}, + {Type: "response.output_item.done", OutputIndex: 1, Item: &message}, + {Type: "response.completed", Response: &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{item, message}}}, + } +} + +func anthropicEventsOf(events []*ResponsesStreamEvent, xai bool) []AnthropicStreamEvent { + state := NewResponsesEventToAnthropicState() + state.XAIServerSideSearch = xai + var out []AnthropicStreamEvent + for _, event := range events { + out = append(out, ResponsesEventToAnthropicEvents(event, state)...) + } + return out +} + +func chatChunksOf(events []*ResponsesStreamEvent, xai bool) []ChatCompletionsChunk { + state := NewResponsesEventToChatState() + state.XAIServerSideSearch = xai + var out []ChatCompletionsChunk + for _, event := range events { + out = append(out, ResponsesEventToChatChunks(event, state)...) + } + return out +} + +func anthropicToolUseStarts(events []AnthropicStreamEvent) int { + count := 0 + for _, event := range events { + if event.Type == "content_block_start" && event.ContentBlock != nil && event.ContentBlock.Type == "tool_use" { + count++ + } + } + return count +} + +func anthropicStopReason(events []AnthropicStreamEvent) string { + for _, event := range events { + if event.Type == "message_delta" && event.Delta != nil { + return event.Delta.StopReason + } + } + return "" +} + +func chatToolCallChunks(chunks []ChatCompletionsChunk) int { + count := 0 + for _, chunk := range chunks { + for _, choice := range chunk.Choices { + count += len(choice.Delta.ToolCalls) + } + } + return count +} + +func chatFinishReason(chunks []ChatCompletionsChunk) string { + for _, chunk := range chunks { + for _, choice := range chunk.Choices { + if choice.FinishReason != nil { + return *choice.FinishReason + } + } + } + return "" +} + +func TestResponsesEventToAnthropicEvents_ServerSideSearchIsNotToolUse(t *testing.T) { + for _, tt := range []struct { + name, callID, toolName string + xai bool + wantToolUse int + wantStop string + }{ + {"x search", "xs_123", "x_keyword_search", true, 0, "end_turn"}, + {"attachment search", "as_456", "attachment_search", true, 0, "end_turn"}, + {"client custom tool", "call_9", "exec", true, 1, "tool_use"}, + {"x search call id on a non-xAI upstream", "xs_123", "x_keyword_search", false, 1, "tool_use"}, + {"attachment search call id on a non-xAI upstream", "as_456", "attachment_search", false, 1, "tool_use"}, + } { + t.Run(tt.name, func(t *testing.T) { + events := anthropicEventsOf(serverSideSearchStream(tt.callID, tt.toolName), tt.xai) + require.Equal(t, tt.wantToolUse, anthropicToolUseStarts(events)) + require.Equal(t, tt.wantStop, anthropicStopReason(events)) + }) + } +} + +func TestResponsesEventToAnthropicEvents_ServerSideSearchKeepsClientToolCall(t *testing.T) { + stream := serverSideSearchStream("xs_123", "x_keyword_search") + client := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_2", CallID: "call_9", Name: "exec", Input: "dir"} + clientAdded := ResponsesOutput{Type: "custom_tool_call", ID: "ctc_2", CallID: "call_9", Name: "exec"} + mixed := append([]*ResponsesStreamEvent{}, stream[:len(stream)-1]...) + mixed = append(mixed, + &ResponsesStreamEvent{Type: "response.output_item.added", OutputIndex: 2, Item: &clientAdded}, + &ResponsesStreamEvent{Type: "response.custom_tool_call_input.delta", OutputIndex: 2, ItemID: "ctc_2", Delta: "dir"}, + &ResponsesStreamEvent{Type: "response.output_item.done", OutputIndex: 2, Item: &client}, + &ResponsesStreamEvent{Type: "response.completed", Response: &ResponsesResponse{ID: "resp_1", Status: "completed"}}, + ) + + events := anthropicEventsOf(mixed, true) + require.Equal(t, 1, anthropicToolUseStarts(events)) + require.Equal(t, "tool_use", anthropicStopReason(events)) +} + +func TestResponsesEventToChatChunks_ServerSideSearchIsNotToolCall(t *testing.T) { + for _, tt := range []struct { + name, callID, toolName string + xai bool + wantToolCalls int + wantFinish string + }{ + {"x search", "xs_123", "x_keyword_search", true, 0, "stop"}, + {"attachment search", "as_456", "attachment_search", true, 0, "stop"}, + {"client custom tool", "call_9", "exec", true, 2, "tool_calls"}, + {"x search call id on a non-xAI upstream", "xs_123", "x_keyword_search", false, 2, "tool_calls"}, + {"attachment search call id on a non-xAI upstream", "as_456", "attachment_search", false, 2, "tool_calls"}, + } { + t.Run(tt.name, func(t *testing.T) { + chunks := chatChunksOf(serverSideSearchStream(tt.callID, tt.toolName), tt.xai) + // A client call is announced once and then carries its input delta. + require.Equal(t, tt.wantToolCalls, chatToolCallChunks(chunks)) + require.Equal(t, tt.wantFinish, chatFinishReason(chunks)) + }) + } +} + +func TestBufferedResponseAccumulator_ServerSideSearchIsNotRebuiltAsFunctionCall(t *testing.T) { + rebuild := func(callID, name string, xai bool) []ResponsesOutput { + acc := NewBufferedResponseAccumulator() + acc.XAIServerSideSearch = xai + for _, event := range serverSideSearchStream(callID, name) { + if event.Type == "response.completed" { + continue + } + acc.ProcessEvent(event) + } + resp := &ResponsesResponse{ID: "resp_1", Status: "completed"} + acc.SupplementResponseOutput(resp) + return resp.Output + } + + client := rebuild("call_9", "exec", true) + require.Equal(t, "function_call", client[len(client)-1].Type) + require.Equal(t, "call_9", client[len(client)-1].CallID) + + for _, callID := range []string{"xs_123", "as_456"} { + notXAI := rebuild(callID, "x_keyword_search", false) + require.Equal(t, "function_call", notXAI[len(notXAI)-1].Type, "without the xAI switch the item is rebuilt as before") + + output := rebuild(callID, "x_keyword_search", true) + for _, item := range output { + require.NotEqual(t, "function_call", item.Type, "a server-side search is not a client function call") + } + last := output[len(output)-1] + require.Equal(t, "custom_tool_call", last.Type) + require.Equal(t, callID, last.CallID) + require.Equal(t, `{"query":"q"}`, last.Input) + + resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: output} + message := ResponsesToAnthropic(resp, "m") + require.Equal(t, "end_turn", *message.StopReason) + for _, block := range message.Content { + require.NotEqual(t, "tool_use", block.Type) + } + chat := ResponsesToChatCompletions(resp, "m") + require.Empty(t, chat.Choices[0].Message.ToolCalls) + require.Equal(t, "stop", chat.Choices[0].FinishReason) + } +} diff --git a/backend/internal/pkg/apicompat/responses_server_side_search_test.go b/backend/internal/pkg/apicompat/responses_server_side_search_test.go new file mode 100644 index 0000000000..58ba793b46 --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_server_side_search_test.go @@ -0,0 +1,30 @@ +package apicompat + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +func TestIsServerSideSearchCall(t *testing.T) { + tests := []struct { + name string + itemType string + callID string + want bool + }{ + {"x search", "custom_tool_call", "xs_123", true}, + {"attachment search", "custom_tool_call", "as_456", true}, + {"padded call id is not a prefix match", "custom_tool_call", " xs_123", false}, + {"client custom tool", "custom_tool_call", "call_9", false}, + {"prefix is not a substring", "custom_tool_call", "call_xs_9", false}, + {"no call id", "custom_tool_call", "", false}, + {"function call keeps its client meaning", "function_call", "xs_123", false}, + {"other server-side item types are separate items", "x_search_call", "xs_123", false}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + require.Equal(t, tt.want, IsServerSideSearchCall(tt.itemType, tt.callID)) + }) + } +} diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 5eab6d9489..1d5654b7c4 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -190,6 +190,11 @@ type ResponsesEventToAnthropicState struct { PendingThinkingSignature string HasToolCall bool + // XAIServerSideSearch is set by callers whose upstream is xAI. A + // custom_tool_call that IsServerSideSearchCall then never becomes a tool_use + // block, because xAI runs it itself. + XAIServerSideSearch bool + // OutputIndexToBlockIdx maps Responses output_index → Anthropic content block index. OutputIndexToBlockIdx map[int]int @@ -349,6 +354,9 @@ func resToAnthHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesE // function_call 与 custom_tool_call(custom/freeform 工具,如新版 apply_patch) // 同样映射为 Anthropic 的 tool_use 块。 case "function_call", "custom_tool_call": + if state.XAIServerSideSearch && IsServerSideSearchCall(evt.Item.Type, evt.Item.CallID) { + return nil + } var events []AnthropicStreamEvent events = append(events, closeCurrentBlock(state)...) diff --git a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go index e1a7b88c77..ebbf9367b4 100644 --- a/backend/internal/pkg/apicompat/responses_to_chatcompletions.go +++ b/backend/internal/pkg/apicompat/responses_to_chatcompletions.go @@ -131,6 +131,11 @@ type ResponsesEventToChatState struct { argumentBuffers map[int]*strings.Builder IncludeUsage bool Usage *ChatUsage + + // XAIServerSideSearch is set by callers whose upstream is xAI. A + // custom_tool_call that IsServerSideSearchCall then never becomes a tool + // call, because xAI runs it itself. + XAIServerSideSearch bool } // NewResponsesEventToChatState returns an initialised stream state. @@ -266,6 +271,9 @@ func resToChatHandleOutputItemAdded(evt *ResponsesStreamEvent, state *ResponsesE if evt.Item == nil || (evt.Item.Type != "function_call" && evt.Item.Type != "custom_tool_call") { return nil } + if state.XAIServerSideSearch && IsServerSideSearchCall(evt.Item.Type, evt.Item.CallID) { + return nil + } state.SawToolCall = true idx := state.NextToolCallIndex @@ -505,6 +513,9 @@ type bufferedFuncCall struct { EncryptedFunctionArgs json.RawMessage EncryptedContent string Args strings.Builder + // ServerSideSearch marks a custom_tool_call the xAI server ran itself; it + // is rebuilt as that item, never as a client function_call. + ServerSideSearch bool } // BufferedResponseAccumulator collects content from Responses SSE delta events @@ -516,6 +527,11 @@ type BufferedResponseAccumulator struct { reasoning strings.Builder funcCalls []bufferedFuncCall outputIndexToFuncIdx map[int]int + + // XAIServerSideSearch is set by callers whose upstream is xAI. A + // custom_tool_call that IsServerSideSearchCall is then rebuilt as that item + // instead of as a client function_call. + XAIServerSideSearch bool } // NewBufferedResponseAccumulator returns an initialised accumulator. @@ -549,6 +565,7 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent) Namespace: event.Item.Namespace, EncryptedFunctionArgs: event.Item.EncryptedFunctionArgs, EncryptedContent: event.Item.EncryptedContent, + ServerSideSearch: a.XAIServerSideSearch && IsServerSideSearchCall(event.Item.Type, event.Item.CallID), }) } case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": @@ -612,6 +629,15 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput { } for i := range a.funcCalls { + if a.funcCalls[i].ServerSideSearch { + out = append(out, ResponsesOutput{ + Type: "custom_tool_call", + CallID: a.funcCalls[i].CallID, + Name: a.funcCalls[i].Name, + Input: a.funcCalls[i].Args.String(), + }) + continue + } out = append(out, ResponsesOutput{ Type: "function_call", CallID: a.funcCalls[i].CallID, diff --git a/backend/internal/service/grok_search_count.go b/backend/internal/service/grok_search_count.go index c89ce93f04..2b8136b62f 100644 --- a/backend/internal/service/grok_search_count.go +++ b/backend/internal/service/grok_search_count.go @@ -4,13 +4,15 @@ import ( "strconv" "strings" + "github.com/Wei-Shaw/sub2api/internal/pkg/apicompat" "github.com/tidwall/gjson" ) // countGrokNativeSearchCallsFromJSONBytes counts completed native search tool // calls in a Responses-style JSON body (output array or nested response.output). // Counts: web_search_call, x_search_call, tool_search_call, and function_call -// named tool_search / web_search / x_search. +// named tool_search / web_search / x_search, and custom_tool_call items the xAI +// server runs itself (apicompat.IsServerSideSearchCall: call_id xs_ / as_). func countGrokNativeSearchCallsFromJSONBytes(body []byte) int { if len(body) == 0 || !gjson.ValidBytes(body) { return 0 @@ -225,6 +227,9 @@ func isGrokNativeSearchOutputItem(item gjson.Result) bool { case "web_search_call", "x_search_call", "tool_search_call": return true case "function_call", "custom_tool_call": + if apicompat.IsServerSideSearchCall(itemType, item.Get("call_id").String()) { + return true + } name := strings.ToLower(strings.TrimSpace(item.Get("name").String())) return name == "web_search" || name == "x_search" || name == "tool_search" default: diff --git a/backend/internal/service/grok_search_count_test.go b/backend/internal/service/grok_search_count_test.go index 8bb0a2c79e..67b435ae00 100644 --- a/backend/internal/service/grok_search_count_test.go +++ b/backend/internal/service/grok_search_count_test.go @@ -19,6 +19,25 @@ func TestCountGrokNativeSearchCallsFromJSONBytes(t *testing.T) { require.Equal(t, 3, countGrokNativeSearchCallsFromJSONBytes(body)) } +// xAI runs X Search (call_id xs_) and attachment search (as_) on its own server and reports +// them as custom_tool_call items. A custom tool the client declared keeps its call_ id. +func TestCountGrokNativeSearchCalls_ServerSideSearchCustomToolCall(t *testing.T) { + t.Parallel() + xSearch := `{"type":"custom_tool_call","id":"ctc_1","call_id":"xs_1","name":"x_keyword_search","input":"{}"}` + attachment := `{"type":"custom_tool_call","id":"ctc_2","call_id":"as_1","name":"attachment_search","input":"{}"}` + client := `{"type":"custom_tool_call","id":"ctc_3","call_id":"call_1","name":"exec","input":"dir"}` + + require.Equal(t, 2, countGrokNativeSearchCallsFromJSONBytes([]byte(`{"output":[`+xSearch+`,`+attachment+`,`+client+`]}`))) + require.Equal(t, 0, countGrokNativeSearchCallsFromJSONBytes([]byte(`{"output":[`+client+`]}`))) + + sse := stringsJoin( + `data: {"type":"response.output_item.done","item":`+xSearch+`}`, + `data: {"type":"response.output_item.done","item":`+client+`}`, + `data: {"type":"response.completed","response":{"output":[`+xSearch+`,`+client+`]}}`, + ) + require.Equal(t, 1, countGrokNativeSearchCallsFromSSEBody(sse), "item.done and the terminal output list the same call once") +} + func TestCountGrokNativeSearchCallsFromJSONBytes_PrefersNestedResponse(t *testing.T) { t.Parallel() body := []byte(`{"output":[{"type":"web_search_call","id":"duplicate"}],"response":{"output":[{"type":"web_search_call","id":"duplicate"},{"type":"x_search_call","id":"xs1"}]}}`) diff --git a/backend/internal/service/openai_gateway_chat_completions.go b/backend/internal/service/openai_gateway_chat_completions.go index befaa75d7b..482060ec8e 100644 --- a/backend/internal/service/openai_gateway_chat_completions.go +++ b/backend/internal/service/openai_gateway_chat_completions.go @@ -839,6 +839,7 @@ func (s *OpenAIGatewayService) handleChatStreamingResponse( state := apicompat.NewResponsesEventToChatState() state.Model = originalModel + state.XAIServerSideSearch = account != nil && account.IsGrok() // 网关作为计费链路的一环,不能把下游 usage 输出绑定到客户端是否显式请求。 // raw Chat Completions 直转路径已经强制透出 usage,这里保持同样行为,避免级联代理计费为 0。 state.IncludeUsage = true diff --git a/backend/internal/service/openai_gateway_grok_server_side_search_test.go b/backend/internal/service/openai_gateway_grok_server_side_search_test.go new file mode 100644 index 0000000000..258bec4dcc --- /dev/null +++ b/backend/internal/service/openai_gateway_grok_server_side_search_test.go @@ -0,0 +1,201 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" + "github.com/tidwall/sjson" +) + +// X Search runs on the xAI server and arrives as a custom_tool_call whose call_id +// starts with xs_ (attachment search: as_). The item shape follows the CustomToolCall +// schema in https://api.x.ai/api-docs/openapi.json. +const ( + grokXSearchItemJSON = `{"type":"custom_tool_call","id":"ctc_1","call_id":"xs_123","name":"x_keyword_search","input":"{\"query\":\"q\"}","status":"completed"}` + grokASearchItemJSON = `{"type":"custom_tool_call","id":"ctc_2","call_id":"as_456","name":"attachment_search","input":"{\"query\":\"q\"}","status":"completed"}` + grokClientToolJSON = `{"type":"custom_tool_call","id":"ctc_3","call_id":"call_9","name":"exec","input":"{\"cmd\":\"dir\"}","status":"completed"}` + grokMessageItemJSON = `{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"found it"}]}` +) + +func grokSSEFrame(eventType, payload string) string { + if payload == "" { + return fmt.Sprintf("data: {\"type\":%q}\n\n", eventType) + } + return fmt.Sprintf("data: {\"type\":%q,%s}\n\n", eventType, payload) +} + +// grokCustomToolCallStream streams the given custom_tool_call items in order and then a text +// answer. terminalOutput is the output array of the terminal event. +func grokCustomToolCallStream(items []string, terminalOutput string) string { + var sb strings.Builder + sb.WriteString(grokSSEFrame("response.created", `"response":{"id":"resp_1","model":"grok-4.7"}`)) + for index, item := range items { + callID := gjson.Get(item, "call_id").String() + name := gjson.Get(item, "name").String() + input := gjson.Get(item, "input").String() + sb.WriteString(grokSSEFrame("response.output_item.added", fmt.Sprintf(`"output_index":%d,"item":{"type":"custom_tool_call","id":"ctc_%d","call_id":%q,"name":%q,"input":""}`, index, index, callID, name))) + sb.WriteString(grokSSEFrame("response.custom_tool_call_input.delta", fmt.Sprintf(`"output_index":%d,"item_id":"ctc_%d","delta":%q`, index, index, input))) + sb.WriteString(grokSSEFrame("response.custom_tool_call_input.done", fmt.Sprintf(`"output_index":%d,"item_id":"ctc_%d","input":%q`, index, index, input))) + sb.WriteString(grokSSEFrame("response.output_item.done", fmt.Sprintf(`"output_index":%d,"item":%s`, index, item))) + } + textIndex := len(items) + sb.WriteString(grokSSEFrame("response.output_text.delta", fmt.Sprintf(`"output_index":%d,"delta":"found it"`, textIndex))) + sb.WriteString(grokSSEFrame("response.output_item.done", fmt.Sprintf(`"output_index":%d,"item":%s`, textIndex, grokMessageItemJSON))) + sb.WriteString(grokSSEFrame("response.completed", `"response":{"id":"resp_1","status":"completed","output":`+terminalOutput+`,"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}`)) + return sb.String() +} + +type grokSearchForwardOutcome struct { + body string + searchCount int +} + +func forwardGrokCustomToolCallStream(t *testing.T, path string, streaming bool, account *Account, sse string) grokSearchForwardOutcome { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + model := "grok-4.7" + if !account.IsGrok() { + model = "gpt-5.5" + } + body := []byte(fmt.Sprintf(`{"model":%q,"stream":%t,"messages":[{"role":"user","content":"hi"}]}`, model, streaming)) + if path == "/v1/messages" { + body, _ = sjson.SetBytes(body, "max_tokens", 32) + } + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Set("api_key", &APIKey{ID: 88000}) + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sse)), + }} + var svc *OpenAIGatewayService + if account.IsGrok() { + svc = grokAuditOAuthService(upstream, account) + } else { + svc = &OpenAIGatewayService{httpUpstream: upstream, cfg: rawChatCompletionsTestConfig()} + } + var result *OpenAIForwardResult + var err error + if path == "/v1/chat/completions" { + result, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + result, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + return grokSearchForwardOutcome{body: rec.Body.String(), searchCount: result.SearchCount} +} + +func TestGrokServerSideSearchCustomToolCallIsNotAClientToolCall(t *testing.T) { + // A Grok API-key account sends /v1/chat/completions to xAI as Chat Completions, not + // through Responses, so only /v1/messages applies to it. + accounts := map[string]*Account{ + "oauth": healthyGrokOAuthGatewayTestAccount(4242, "access-token"), + "apikey": grokAuditAPIKeyAccount(4243), + } + terminals := map[string]string{ + "empty terminal": `[]`, + "terminal with the items": `[` + grokXSearchItemJSON + `,` + grokMessageItemJSON + `]`, + } + for accountName, account := range accounts { + for terminalName, terminalOutput := range terminals { + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + if path == "/v1/chat/completions" && account.Type == AccountTypeAPIKey { + continue + } + for _, streaming := range []bool{false, true} { + t.Run(fmt.Sprintf("%s %s %s stream=%v", accountName, terminalName, path, streaming), func(t *testing.T) { + sse := grokCustomToolCallStream([]string{grokXSearchItemJSON}, terminalOutput) + got := forwardGrokCustomToolCallStream(t, path, streaming, account, sse) + + require.Equal(t, 1, got.searchCount) + require.NotContains(t, got.body, "tool_use", got.body) + require.NotContains(t, got.body, "tool_calls", got.body) + require.NotContains(t, got.body, "x_keyword_search", got.body) + require.Contains(t, got.body, "found it", got.body) + if path == "/v1/messages" { + require.Contains(t, got.body, `"stop_reason":"end_turn"`, got.body) + } else { + require.Contains(t, got.body, `"finish_reason":"stop"`, got.body) + } + }) + } + } + } + } +} + +func TestGrokServerSideSearchCountsEveryPrefixAndKeepsClientTools(t *testing.T) { + account := healthyGrokOAuthGatewayTestAccount(4242, "access-token") + items := []string{grokXSearchItemJSON, grokASearchItemJSON, grokClientToolJSON} + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + for _, streaming := range []bool{false, true} { + t.Run(fmt.Sprintf("%s stream=%v", path, streaming), func(t *testing.T) { + got := forwardGrokCustomToolCallStream(t, path, streaming, account, grokCustomToolCallStream(items, `[]`)) + + require.Equal(t, 2, got.searchCount, "xs_ and as_ are searches, call_ is not") + require.NotContains(t, got.body, "x_keyword_search", got.body) + require.NotContains(t, got.body, "attachment_search", got.body) + require.Contains(t, got.body, "exec", "the client-declared custom tool is still a tool call") + if path == "/v1/messages" { + require.Contains(t, got.body, "tool_use", got.body) + } else { + require.Contains(t, got.body, "tool_calls", got.body) + } + }) + } + } +} + +// The xs_/as_ rule is xAI's. The same call_id on an OpenAI account is an ordinary custom tool +// call: it is emitted as a tool call and is not a Grok search to bill. +func TestServerSideSearchRuleAppliesOnlyToGrokAccounts(t *testing.T) { + openAIAccounts := map[string]*Account{ + "openai oauth": {ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}}, + "openai apikey": rawChatCompletionsTestAccount(), + } + t.Run("grok oauth, same stream", func(t *testing.T) { + sse := grokCustomToolCallStream([]string{grokXSearchItemJSON, grokASearchItemJSON}, `[]`) + got := forwardGrokCustomToolCallStream(t, "/v1/messages", true, healthyGrokOAuthGatewayTestAccount(4242, "access-token"), sse) + require.Equal(t, 2, got.searchCount) + require.NotContains(t, got.body, "tool_use", got.body) + }) + for accountName, account := range openAIAccounts { + for _, path := range []string{"/v1/messages", "/v1/chat/completions"} { + for _, terminalOutput := range []string{`[]`, `[` + grokXSearchItemJSON + `,` + grokMessageItemJSON + `]`} { + for _, streaming := range []bool{false, true} { + if !streaming && terminalOutput != `[]` { + continue // the nonstreaming converters never emit a custom_tool_call from a terminal output + } + t.Run(fmt.Sprintf("%s %s terminal=%s stream=%v", accountName, path, terminalOutput[:2], streaming), func(t *testing.T) { + sse := grokCustomToolCallStream([]string{grokXSearchItemJSON, grokASearchItemJSON}, terminalOutput) + got := forwardGrokCustomToolCallStream(t, path, streaming, account, sse) + + require.Equal(t, 0, got.searchCount) + require.Contains(t, got.body, "x_keyword_search", got.body) + if path == "/v1/messages" { + require.Contains(t, got.body, "tool_use", got.body) + } else { + require.Contains(t, got.body, "tool_calls", got.body) + } + }) + } + } + } + } +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 7f0c07ddf4..14aaee67a2 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -834,6 +834,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( requestID string, ) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() + acc.XAIServerSideSearch = account != nil && account.IsGrok() var usage OpenAIUsage if resp == nil || resp.Body == nil { return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") @@ -1020,6 +1021,7 @@ func (s *OpenAIGatewayService) handleAnthropicStreamingResponse( state := apicompat.NewResponsesEventToAnthropicState() state.Model = compositeClientModel(c.Request.Context(), originalModel) + state.XAIServerSideSearch = account != nil && account.IsGrok() var usage OpenAIUsage responseID := "" var firstTokenMs *int diff --git a/backend/internal/service/openai_gateway_response_handling.go b/backend/internal/service/openai_gateway_response_handling.go index 3d1d67af84..ec1427d821 100644 --- a/backend/internal/service/openai_gateway_response_handling.go +++ b/backend/internal/service/openai_gateway_response_handling.go @@ -344,6 +344,7 @@ func (s *OpenAIGatewayService) handleStreamingResponseWithReasoning(ctx context. needModelReplace := originalModel != mappedModel var createdAtStamper responsesCreatedAtStamper streamOutputAccumulator := apicompat.NewBufferedResponseAccumulator() + streamOutputAccumulator.XAIServerSideSearch = account != nil && account.IsGrok() streamDoneItems := newResponsesStreamOutputItems() streamImageOutputs := make([]json.RawMessage, 0, 1) streamSeenImages := make(map[string]struct{})