diff --git a/backend/internal/pkg/apicompat/responses_to_anthropic.go b/backend/internal/pkg/apicompat/responses_to_anthropic.go index 5eab6d9489..a1c6485164 100644 --- a/backend/internal/pkg/apicompat/responses_to_anthropic.go +++ b/backend/internal/pkg/apicompat/responses_to_anthropic.go @@ -67,11 +67,10 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo Name: "web_search", Input: inputJSON, }) - emptyResults, _ := json.Marshal([]struct{}{}) blocks = append(blocks, AnthropicContentBlock{ Type: "web_search_tool_result", ToolUseID: toolUseID, - Content: emptyResults, + Content: webSearchCallResults(&item), }) } } @@ -670,9 +669,6 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve state.ContentBlockIndex++ // Emit web_search_tool_result block (start + stop). - // Content is empty because OpenAI does not expose individual search results; - // the model consumes them internally and produces text output. - emptyResults, _ := json.Marshal([]struct{}{}) idx2 := state.ContentBlockIndex events = append(events, AnthropicStreamEvent{ Type: "content_block_start", @@ -680,7 +676,7 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve ContentBlock: &AnthropicContentBlock{ Type: "web_search_tool_result", ToolUseID: toolUseID, - Content: emptyResults, + Content: webSearchCallResults(evt.Item), }, }) events = append(events, AnthropicStreamEvent{ diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources.go b/backend/internal/pkg/apicompat/responses_web_search_sources.go new file mode 100644 index 0000000000..39efc7370d --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_web_search_sources.go @@ -0,0 +1,57 @@ +package apicompat + +import ( + "encoding/json" + "slices" +) + +const webSearchSourcesInclude = "web_search_call.action.sources" + +// IncludeWebSearchSources asks a hosted web_search to report the pages it +// used; without it a web_search_call carries only its query. +func IncludeWebSearchSources(req *ResponsesRequest) { + for _, tool := range req.Tools { + if tool.Type == "web_search" { + if !slices.Contains(req.Include, webSearchSourcesInclude) { + req.Include = append(req.Include, webSearchSourcesInclude) + } + return + } + } +} + +type webSearchResult struct { + Type string `json:"type"` + URL string `json:"url"` + Title string `json:"title"` +} + +// webSearchCallResults is the web_search_tool_result content for one call: a +// search's action.sources, or the single page a completed open_page opened. +// Sources are decoded entry by entry, so one malformed entry cannot fail the +// terminal event that carries the call. +func webSearchCallResults(item *ResponsesOutput) json.RawMessage { + results := []webSearchResult{} + if action := item.Action; action != nil { + var sources []json.RawMessage + if json.Unmarshal(action.Sources, &sources) == nil && sources != nil { + for _, raw := range sources { + var source map[string]any + _ = json.Unmarshal(raw, &source) + if rawURL, ok := source["url"].(string); ok && rawURL != "" { + results = append(results, newWebSearchResult(rawURL)) + } + } + } else if action.Type == "open_page" && item.Status == "completed" && action.URL != "" { + results = append(results, newWebSearchResult(action.URL)) + } + } + out, _ := json.Marshal(results) + return out +} + +// newWebSearchResult uses the URL as the title because Responses sources carry +// no title and the Anthropic block requires one. +func newWebSearchResult(rawURL string) webSearchResult { + return webSearchResult{Type: "web_search_result", URL: rawURL, Title: rawURL} +} diff --git a/backend/internal/pkg/apicompat/responses_web_search_sources_test.go b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go new file mode 100644 index 0000000000..07742de86c --- /dev/null +++ b/backend/internal/pkg/apicompat/responses_web_search_sources_test.go @@ -0,0 +1,110 @@ +//go:build unit + +package apicompat + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" +) + +const ( + webSearchCallWithTwoSources = `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q1","sources":[` + + `{"type":"url","url":"https://a.example/1"},{"type":"url","url":"https://a.example/2"}]}}` + webSearchCallWithOneSource = `{"type":"web_search_call","id":"ws_2","status":"completed","action":{"type":"search","query":"q2","sources":[` + + `{"type":"url","url":"https://b.example/1"}]}}` + webSearchSourcesWantWS1 = `[{"type":"web_search_result","url":"https://a.example/1","title":"https://a.example/1"},` + + `{"type":"web_search_result","url":"https://a.example/2","title":"https://a.example/2"}]` + webSearchSourcesWantWS2 = `[{"type":"web_search_result","url":"https://b.example/1","title":"https://b.example/1"}]` +) + +func decodeWebSearchItem(t *testing.T, raw string) ResponsesOutput { + t.Helper() + var item ResponsesOutput + require.NoError(t, json.Unmarshal([]byte(raw), &item)) + return item +} + +// webSearchResultContents returns each web_search_tool_result content keyed by +// the server_tool_use id it answers. +func webSearchResultContents(blocks []AnthropicContentBlock) map[string]string { + out := map[string]string{} + for _, block := range blocks { + if block.Type == "web_search_tool_result" { + out[block.ToolUseID] = string(block.Content) + } + } + return out +} + +func nonStreamingWebSearchResults(t *testing.T, items ...string) map[string]string { + t.Helper() + resp := &ResponsesResponse{ID: "resp_ws", Status: "completed"} + for _, raw := range items { + resp.Output = append(resp.Output, decodeWebSearchItem(t, raw)) + } + return webSearchResultContents(ResponsesToAnthropic(resp, "gpt-5.5").Content) +} + +func streamingWebSearchResults(t *testing.T, items ...string) map[string]string { + t.Helper() + state := NewResponsesEventToAnthropicState() + events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.created", + Response: &ResponsesResponse{ID: "resp_ws", Model: "gpt-5.5"}, + }, state) + for i, raw := range items { + item := decodeWebSearchItem(t, raw) + events = append(events, ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{ + Type: "response.output_item.done", + OutputIndex: i, + Item: &item, + }, state)...) + } + var blocks []AnthropicContentBlock + for _, evt := range events { + if evt.Type == "content_block_start" && evt.ContentBlock != nil { + blocks = append(blocks, *evt.ContentBlock) + } + } + return webSearchResultContents(blocks) +} + +func TestResponsesEventToAnthropic_WebSearchSources(t *testing.T) { + got := streamingWebSearchResults(t, webSearchCallWithTwoSources, webSearchCallWithOneSource) + require.Len(t, got, 2) + require.JSONEq(t, webSearchSourcesWantWS1, got["srvtoolu_ws_1"]) + require.JSONEq(t, webSearchSourcesWantWS2, got["srvtoolu_ws_2"]) +} + +func TestResponsesToAnthropic_WebSearchSources(t *testing.T) { + got := nonStreamingWebSearchResults(t, webSearchCallWithTwoSources, webSearchCallWithOneSource) + require.Len(t, got, 2) + require.JSONEq(t, webSearchSourcesWantWS1, got["srvtoolu_ws_1"]) + require.JSONEq(t, webSearchSourcesWantWS2, got["srvtoolu_ws_2"]) +} + +func TestWebSearchSourcesEntryRules(t *testing.T) { + got := nonStreamingWebSearchResults(t, `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q",`+ + `"sources":[{"url":"https://a"},{"url":""},{"url":1},"https://b",{"title":"x"}]}}`) + require.JSONEq(t, `[{"type":"web_search_result","url":"https://a","title":"https://a"}]`, got["srvtoolu_ws_1"]) +} + +func TestWebSearchOpenPageReturnsSinglePage(t *testing.T) { + got := nonStreamingWebSearchResults(t, `{"type":"web_search_call","id":"ws_1","status":"completed",`+ + `"action":{"type":"open_page","url":"https://docs.example/page?id=1#top"}}`) + require.JSONEq(t, `[{"type":"web_search_result","url":"https://docs.example/page?id=1#top","title":"https://docs.example/page?id=1#top"}]`, + got["srvtoolu_ws_1"]) +} + +func TestWebSearchOpenPageRequiresCompletedURL(t *testing.T) { + for name, item := range map[string]string{ + "in progress": `{"type":"web_search_call","id":"ws_1","status":"in_progress","action":{"type":"open_page","url":"https://docs.example/page"}}`, + "empty url": `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":""}}`, + } { + t.Run(name, func(t *testing.T) { + require.JSONEq(t, `[]`, nonStreamingWebSearchResults(t, item)["srvtoolu_ws_1"]) + }) + } +} diff --git a/backend/internal/pkg/apicompat/types.go b/backend/internal/pkg/apicompat/types.go index 130f0ff63b..a603d64147 100644 --- a/backend/internal/pkg/apicompat/types.go +++ b/backend/internal/pkg/apicompat/types.go @@ -492,6 +492,10 @@ func (o *ResponsesOutput) UnmarshalJSON(data []byte) error { type WebSearchAction struct { Type string `json:"type,omitempty"` // "search" Query string `json:"query,omitempty"` // primary search query + URL string `json:"url,omitempty"` // open_page / find_in_page target + // Sources stays raw: a strictly typed entry of an unexpected shape would + // fail decoding the whole terminal event that carries this call. + Sources json.RawMessage `json:"sources,omitempty"` } // ResponsesSummary is a summary text block inside a reasoning output. diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 4756d83383..ca58d0aeaf 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -214,6 +214,9 @@ func (s *OpenAIGatewayService) ForwardAsAnthropic( logFields = append(logFields, zap.Bool("compat_turn_state_attached", true)) } logger.L().Debug("openai messages: model mapping applied", logFields...) + if account.Platform == PlatformOpenAI { + apicompat.IncludeWebSearchSources(responsesReq) + } // 4. Marshal Responses request body, then apply the ChatGPT/Codex transform. responsesBody, err := json.Marshal(responsesReq) diff --git a/backend/internal/service/openai_gateway_messages_web_search_sources_test.go b/backend/internal/service/openai_gateway_messages_web_search_sources_test.go new file mode 100644 index 0000000000..9c859cc3b0 --- /dev/null +++ b/backend/internal/service/openai_gateway_messages_web_search_sources_test.go @@ -0,0 +1,123 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const messagesWebSearchBody = `{"model":"gpt-5.5","max_tokens":64,"stream":true, + "tools":[{"type":"web_search_20250305","name":"web_search"}], + "messages":[{"role":"user","content":"search the web"}]}` + +const messagesWithoutWebSearchBody = `{"model":"gpt-5.5","max_tokens":64,"stream":true, + "messages":[{"role":"user","content":"hello"}]}` + +const webSearchCompletedSSE = "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ws\",\"status\":\"completed\",\"output\":[],\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + +func codexOAuthWebSearchTestAccount() *Account { + return &Account{ + ID: 1, Name: "openai-oauth", Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1, + Credentials: map[string]any{"access_token": "oauth-token", "chatgpt_account_id": "chatgpt-acc"}, + } +} + +func upstreamInclude(body []byte) []string { + var include []string + for _, v := range gjson.GetBytes(body, "include").Array() { + include = append(include, v.String()) + } + return include +} + +func forwardMessagesWebSearch(t *testing.T, account *Account, requestBody, upstreamSSE string) (*httpUpstreamRecorder, *httptest.ResponseRecorder) { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + upstream := &httpUpstreamRecorder{resp: &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(upstreamSSE)), + }} + svc := &OpenAIGatewayService{ + httpUpstream: upstream, + cfg: rawChatCompletionsTestConfig(), + } + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "gpt-5.5") + require.NoError(t, err) + return upstream, rec +} + +func forwardGrokMessages(t *testing.T, requestBody string) *httpUpstreamRecorder { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", bytes.NewReader(body)) + account := healthyGrokOAuthGatewayTestAccount(71, "access-token") + repo := &grokQuotaAccountRepo{mockAccountRepoForPlatform: &mockAccountRepoForPlatform{accountsByID: map[int64]*Account{71: account}}} + upstream := &httpUpstreamRecorder{resp: grokMessagesSSECompletedResponse("resp_grok_ws", 0)} + svc := &OpenAIGatewayService{httpUpstream: upstream, grokTokenProvider: NewGrokTokenProvider(repo, nil), accountRepo: repo} + + _, err := svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + require.NoError(t, err) + return upstream +} + +func TestForwardAsAnthropic_WebSearchRequestsSources(t *testing.T) { + for name, account := range map[string]*Account{ + "openai apikey": rawChatCompletionsTestAccount(), + "codex oauth": codexOAuthWebSearchTestAccount(), + } { + t.Run(name, func(t *testing.T) { + upstream, _ := forwardMessagesWebSearch(t, account, messagesWebSearchBody, webSearchCompletedSSE) + require.Equal(t, []string{"reasoning.encrypted_content", "web_search_call.action.sources"}, upstreamInclude(upstream.lastBody)) + }) + } +} + +func TestForwardAsAnthropic_WebSearchSourcesNotRequestedWithoutTool(t *testing.T) { + for name, account := range map[string]*Account{ + "openai apikey": rawChatCompletionsTestAccount(), + "codex oauth": codexOAuthWebSearchTestAccount(), + } { + t.Run(name, func(t *testing.T) { + upstream, _ := forwardMessagesWebSearch(t, account, messagesWithoutWebSearchBody, webSearchCompletedSSE) + require.NotContains(t, upstreamInclude(upstream.lastBody), "web_search_call.action.sources") + }) + } + t.Run("grok with web_search tool", func(t *testing.T) { + upstream := forwardGrokMessages(t, messagesWebSearchBody) + require.NotEmpty(t, gjson.GetBytes(upstream.lastBody, "tools").Array(), "the web_search tool reaches xAI") + require.NotContains(t, upstreamInclude(upstream.lastBody), "web_search_call.action.sources") + }) +} + +// A source entry of an unexpected shape must not cost the terminal event that +// carries it: that would turn a finished answer into a missing-terminal error. +func TestWebSearchMalformedSourcesKeepTerminalEvent(t *testing.T) { + sse := "data: {\"type\":\"response.created\",\"response\":{\"id\":\"resp_ws\",\"model\":\"gpt-5.5\"}}\n\n" + + "data: {\"type\":\"response.output_text.delta\",\"output_index\":0,\"content_index\":0,\"delta\":\"found it\"}\n\n" + + "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_ws\",\"status\":\"completed\",\"output\":[" + + "{\"type\":\"message\",\"id\":\"msg_1\",\"role\":\"assistant\",\"status\":\"completed\",\"content\":[{\"type\":\"output_text\",\"text\":\"found it\"}]}," + + "{\"type\":\"web_search_call\",\"id\":\"ws_1\",\"status\":\"completed\",\"action\":{\"type\":\"search\",\"query\":\"q\",\"sources\":[\"https://a\"]}}]," + + "\"usage\":{\"input_tokens\":5,\"output_tokens\":2,\"total_tokens\":7}}}\n\n" + _, rec := forwardMessagesWebSearch(t, rawChatCompletionsTestAccount(), messagesWebSearchBody, sse) + + out := strings.TrimSpace(rec.Body.String()) + require.True(t, strings.HasSuffix(out, `{"type":"message_stop"}`), "body: %s", out) +}