diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items.go b/backend/internal/service/openai_gateway_buffered_hosted_items.go index 133ae6dc55..c0e74c4abf 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items.go @@ -2,7 +2,6 @@ package service import ( "encoding/json" - "slices" "sort" "strings" @@ -10,93 +9,314 @@ import ( "github.com/tidwall/gjson" ) -// openAICompatAccumulatedItemTypes are the output item types that -// apicompat.BufferedResponseAccumulator rebuilds from deltas. Every other type -// can only be recovered from its response.output_item.done event. -var openAICompatAccumulatedItemTypes = map[string]struct{}{ - "reasoning": {}, - "message": {}, - "function_call": {}, - "custom_tool_call": {}, +// openAICompatOutputSlot is everything the upstream stream said about one output +// item: the item of its output_item.added and output_item.done events and the +// text, refusal and argument deltas that arrived for it. +type openAICompatOutputSlot struct { + index int64 + indexed bool + itemType string + added *apicompat.ResponsesOutput + done *apicompat.ResponsesOutput + reasoning strings.Builder + text strings.Builder + refusal strings.Builder + args strings.Builder + argsDone string } -type openAICompatHostedItem struct { - index int64 - indexed bool - raw json.RawMessage +// openAICompatOutputSlots records the output items of a buffered upstream stream +// so that an empty terminal output can be rebuilt from them. +type openAICompatOutputSlots struct { + slots []*openAICompatOutputSlot } -// openAICompatHostedItems collects the response.output_item.done items of types -// the delta accumulator does not produce, such as web_search_call and -// image_generation_call. -type openAICompatHostedItems struct { - items []openAICompatHostedItem +func openAICompatIsToolCallType(itemType string) bool { + return itemType == "function_call" || itemType == "custom_tool_call" } -func (h *openAICompatHostedItems) Observe(payload []byte) { - if h == nil || strings.TrimSpace(gjson.GetBytes(payload, "type").String()) != "response.output_item.done" || !gjson.ValidBytes(payload) { +func (o *openAICompatOutputSlots) Observe(payload []byte) { + if o == nil { return } - item := gjson.GetBytes(payload, "item") - if !item.IsObject() { - return - } - itemType := strings.TrimSpace(item.Get("type").String()) - if _, ok := openAICompatAccumulatedItemTypes[itemType]; ok || itemType == "" { - return - } - entry := openAICompatHostedItem{raw: json.RawMessage(item.Raw)} - if index := gjson.GetBytes(payload, "output_index"); index.Exists() { - entry.index, entry.indexed = index.Int(), true - for i := range h.items { - if h.items[i].indexed && h.items[i].index == entry.index { - h.items[i] = entry - return + switch strings.TrimSpace(gjson.GetBytes(payload, "type").String()) { + case "response.output_item.added": + if item, ok := openAICompatEventItem(payload); ok { + slot := o.slot(payload, item.Type, item.ID, false, true) + slot.added = &item + } + case "response.output_item.done": + if item, ok := openAICompatEventItem(payload); ok { + slot := o.slot(payload, item.Type, item.ID, true, true) + slot.done = &item + } + case "response.output_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + _, _ = o.slot(payload, "message", "", false, true).text.WriteString(delta) + } + case "response.refusal.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + _, _ = o.slot(payload, "message", "", false, true).refusal.WriteString(delta) + } + case "response.reasoning_summary_text.delta", "response.reasoning_text.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + _, _ = o.slot(payload, "reasoning", "", false, true).reasoning.WriteString(delta) + } + case "response.function_call_arguments.delta", "response.custom_tool_call_input.delta": + if delta := gjson.GetBytes(payload, "delta").String(); delta != "" { + if slot := o.slot(payload, "function_call", "", false, false); slot != nil { + _, _ = slot.args.WriteString(delta) + } + } + case "response.function_call_arguments.done": + if slot := o.slot(payload, "function_call", "", false, false); slot != nil { + if completed := gjson.GetBytes(payload, "arguments").String(); completed != "" { + slot.argsDone = completed + } + } + case "response.custom_tool_call_input.done": + if slot := o.slot(payload, "function_call", "", false, false); slot != nil { + if completed := gjson.GetBytes(payload, "input").String(); completed != "" { + slot.argsDone = completed } } } - h.items = append(h.items, entry) } -// fillTerminalOutput gives an empty terminal output the collected hosted items -// ahead of what the accumulator rebuilds, after its leading reasoning item. -// Only terminals that carry a result are filled; the output of response.failed -// and error terminals never reaches the client and is left as the upstream sent it. -// Hosted items keep their output_index order; items reported without an -// output_index follow the indexed ones in arrival order. -func (h *openAICompatHostedItems) fillTerminalOutput(eventType string, response *apicompat.ResponsesResponse, acc *apicompat.BufferedResponseAccumulator) { +func openAICompatEventItem(payload []byte) (apicompat.ResponsesOutput, bool) { + var item apicompat.ResponsesOutput + raw := gjson.GetBytes(payload, "item") + if !raw.IsObject() || !gjson.ValidBytes(payload) || json.Unmarshal([]byte(raw.Raw), &item) != nil { + return item, false + } + item.Type = strings.TrimSpace(item.Type) + return item, item.Type != "" +} + +// slot finds the slot an event belongs to. A done event whose item has an id +// belongs to the slot that already holds a done item with that id, so a repeated +// item replaces its earlier copy and items that merely share an output_index stay +// apart. Otherwise an event with an output_index belongs to the newest slot of +// that index (an added event: the newest one that has none yet; a done event +// without an id replaces the done item of that slot). An event without an +// output_index belongs to the newest unindexed slot of its kind (a done event: +// the oldest one still without a done item), and an added event always starts a +// new slot, so unindexed items keep arrival order. With create unset, a missing +// slot returns nil. +func (o *openAICompatOutputSlots) slot(payload []byte, kind, id string, done, create bool) *openAICompatOutputSlot { + index := gjson.GetBytes(payload, "output_index") + added := strings.TrimSpace(gjson.GetBytes(payload, "type").String()) == "response.output_item.added" + matches := func(slot *openAICompatOutputSlot) bool { + if slot.itemType == "" || slot.itemType == kind { + return true + } + return openAICompatIsToolCallType(kind) && openAICompatIsToolCallType(slot.itemType) + } + newest := func(accept func(*openAICompatOutputSlot) bool) *openAICompatOutputSlot { + for i := len(o.slots) - 1; i >= 0; i-- { + if accept(o.slots[i]) { + return o.slots[i] + } + } + return nil + } + var found *openAICompatOutputSlot + if done && id != "" { + found = newest(func(slot *openAICompatOutputSlot) bool { return slot.done != nil && slot.done.ID == id }) + } + if found == nil { + switch { + case index.Exists(): + atIndex := func(slot *openAICompatOutputSlot) bool { return slot.indexed && slot.index == index.Int() } + switch { + case done && id != "": + found = newest(func(slot *openAICompatOutputSlot) bool { return atIndex(slot) && slot.done == nil }) + case added: + found = newest(func(slot *openAICompatOutputSlot) bool { return atIndex(slot) && slot.added == nil }) + default: + found = newest(atIndex) + } + case added: + case done: + for _, slot := range o.slots { + if !slot.indexed && slot.done == nil && slot.itemType == kind { + found = slot + break + } + } + default: + found = newest(func(slot *openAICompatOutputSlot) bool { return !slot.indexed && matches(slot) }) + } + } + if found == nil { + if !create { + return nil + } + found = &openAICompatOutputSlot{} + if index.Exists() { + found.index, found.indexed = index.Int(), true + } + o.slots = append(o.slots, found) + } + if found.itemType == "" || done || added { + found.itemType = kind + } + return found +} + +// fillTerminalOutput rebuilds an empty terminal output from the stream's output +// items, in output_index order, items without an output_index after the indexed +// ones in arrival order. Items with the same output_index keep arrival order. An item that received output_item.done is taken from +// that event, completed with the deltas where the event left a text, refusal or +// the arguments empty; an item that never received it is rebuilt from its +// deltas. Only terminals that carry a result are filled; the output of +// response.failed and error terminals never reaches the client and is left as +// the upstream sent it. +func (o *openAICompatOutputSlots) fillTerminalOutput(eventType string, response *apicompat.ResponsesResponse) { switch strings.TrimSpace(eventType) { - case "response.completed", "response.done", "response.incomplete": + case "response.completed", "response.done", "response.incomplete", "response.cancelled", "response.canceled": default: return } - if h == nil || len(h.items) == 0 || response == nil || len(response.Output) > 0 { + if o == nil || response == nil || len(response.Output) > 0 { return } - sort.SliceStable(h.items, func(i, j int) bool { - a, b := h.items[i], h.items[j] + slots := append([]*openAICompatOutputSlot(nil), o.slots...) + sort.SliceStable(slots, func(i, j int) bool { + a, b := slots[i], slots[j] if a.indexed != b.indexed { return a.indexed } return a.indexed && a.index < b.index }) - hosted := make([]apicompat.ResponsesOutput, 0, len(h.items)) - for _, entry := range h.items { - var item apicompat.ResponsesOutput - if err := json.Unmarshal(entry.raw, &item); err == nil { - hosted = append(hosted, item) + for _, slot := range slots { + if item, ok := slot.build(); ok { + response.Output = append(response.Output, item) } } - if len(hosted) == 0 { - return +} + +func (s *openAICompatOutputSlot) build() (apicompat.ResponsesOutput, bool) { + switch s.itemType { + case "reasoning": + return s.buildReasoning() + case "message": + return s.buildMessage() + case "function_call", "custom_tool_call": + return s.buildToolCall() } - var output []apicompat.ResponsesOutput - if acc != nil && acc.HasContent() { - output = acc.BuildOutput() + if s.done == nil { + return apicompat.ResponsesOutput{}, false } - at := 0 - for at < len(output) && output[at].Type == "reasoning" { - at++ + return *s.done, true +} + +func openAICompatReasoningItemText(item apicompat.ResponsesOutput) string { + var text strings.Builder + for _, part := range item.Summary { + if part.Type == "summary_text" { + _, _ = text.WriteString(part.Text) + } } - response.Output = slices.Insert(output, at, hosted...) + if text.Len() == 0 { + for _, part := range item.Content { + if part.Type == "reasoning_text" { + _, _ = text.WriteString(part.Text) + } + } + } + return text.String() +} + +func (s *openAICompatOutputSlot) buildReasoning() (apicompat.ResponsesOutput, bool) { + item := apicompat.ResponsesOutput{Type: "reasoning"} + if s.done != nil { + item = *s.done + } + if s.reasoning.Len() > 0 && openAICompatReasoningItemText(item) == "" { + item.Summary = []apicompat.ResponsesSummary{{Type: "summary_text", Text: s.reasoning.String()}} + item.Content = nil + } + return item, s.done != nil || s.reasoning.Len() > 0 +} + +func (s *openAICompatOutputSlot) buildMessage() (apicompat.ResponsesOutput, bool) { + item := apicompat.ResponsesOutput{Type: "message", Role: "assistant"} + if s.done != nil { + item = *s.done + item.Content = append([]apicompat.ResponsesContentPart(nil), item.Content...) + } + if s.text.Len() > 0 { + filled := false + hasText := false + for i := range item.Content { + part := &item.Content[i] + if part.Type != "output_text" { + continue + } + if strings.TrimSpace(part.Text) != "" { + hasText = true + break + } + if !filled { + part.Text, filled = s.text.String(), true + } + } + if !hasText && !filled { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "output_text", Text: s.text.String()}) + } + } + if s.refusal.Len() > 0 { + hasRefusal := false + for _, part := range item.Content { + if part.Type == "refusal" && part.Refusal != "" { + hasRefusal = true + } + } + if !hasRefusal { + item.Content = append(item.Content, apicompat.ResponsesContentPart{Type: "refusal", Refusal: s.refusal.String()}) + } + } + return item, s.done != nil || s.text.Len() > 0 || s.refusal.Len() > 0 +} + +// buildToolCall returns a function_call item. A custom_tool_call is returned in +// that form as well, with its input as the arguments, because that is the shape +// the Chat Completions and Messages converters render as a tool call. +func (s *openAICompatOutputSlot) buildToolCall() (apicompat.ResponsesOutput, bool) { + if s.done == nil && s.added == nil { + return apicompat.ResponsesOutput{}, false + } + var item apicompat.ResponsesOutput + if s.done != nil { + item = *s.done + } else { + item = *s.added + } + if s.added != nil { + if item.CallID == "" { + item.CallID = s.added.CallID + } + if item.Name == "" { + item.Name = s.added.Name + } + if item.Namespace == "" { + item.Namespace = s.added.Namespace + } + if item.EncryptedFunctionArgs == nil { + item.EncryptedFunctionArgs = s.added.EncryptedFunctionArgs + } + } + arguments := item.Arguments + if item.Type == "custom_tool_call" { + arguments = item.Input + } + if arguments == "" { + arguments = s.argsDone + } + if arguments == "" { + arguments = s.args.String() + } + item.Type, item.Input, item.Arguments = "function_call", "", arguments + return item, true } diff --git a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go index 435d3fe6a3..87159ed762 100644 --- a/backend/internal/service/openai_gateway_buffered_hosted_items_test.go +++ b/backend/internal/service/openai_gateway_buffered_hosted_items_test.go @@ -8,6 +8,7 @@ import ( "io" "net/http" "net/http/httptest" + "strconv" "strings" "testing" @@ -344,3 +345,63 @@ func TestBufferedCompat_FailedTerminalKeepsErrorPayload(t *testing.T) { }) } } + +func readBufferedOutputItems(t *testing.T, sse string) []string { + t.Helper() + gin.SetMode(gin.TestMode) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + account := &Account{ID: 1, Platform: PlatformOpenAI, Type: AccountTypeOAuth, Concurrency: 1} + response, _, _, _, err := (&OpenAIGatewayService{}).readOpenAICompatBufferedTerminal( + bufferedHostedItemsSSEResponse(sse), c, account, "openai chat buffered", "req-1") + require.NoError(t, err) + require.NotNil(t, response) + var items []string + for _, item := range response.Output { + items = append(items, item.Type+":"+item.ID+":"+item.Arguments+":"+item.Input) + } + return items +} + +// Items that share an output_index stay apart; the same item reported again +// replaces its earlier copy; equal indexes keep arrival order. +func TestReadOpenAICompatBufferedTerminal_DoneItemsMergeByItemID(t *testing.T) { + done := func(index int, id string) string { + return `{"type":"response.output_item.done","output_index":` + strconv.Itoa(index) + `,"item":{"type":"web_search_call","id":"` + id + `","status":"completed"}}` + } + items := readBufferedOutputItems(t, bufferedItemsSSE( + bufferedHostedItemsCreated, + done(0, "ws_a"), done(0, "ws_b"), done(1, "ws_c"), done(0, "ws_a"), + bufferedHostedItemsCompleted, + )) + require.Equal(t, []string{"web_search_call:ws_a::", "web_search_call:ws_b::", "web_search_call:ws_c::"}, items) +} + +// The done item is the upstream's final form of an item; deltas only complete a +// text, refusal or arguments field that the done item left empty, and rebuild an +// item that never got a done event. +func TestReadOpenAICompatBufferedTerminal_DoneItemsWinOverDeltas(t *testing.T) { + items := readBufferedOutputItems(t, bufferedItemsSSE( + bufferedHostedItemsCreated, + `{"type":"response.output_item.added","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\"stale\":1}"}`, + `{"type":"response.function_call_arguments.done","output_index":0,"arguments":"{\"a\":1}"}`, + `{"type":"response.output_item.done","output_index":0,"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get","arguments":""}}`, + `{"type":"response.output_item.added","output_index":1,"item":{"type":"function_call","id":"fc_2","call_id":"call_2","name":"get","arguments":""}}`, + `{"type":"response.function_call_arguments.delta","output_index":1,"delta":"{\"b\":2}"}`, + `{"type":"response.output_item.done","output_index":2,"item":{"type":"function_call","id":"fc_3","call_id":"call_3","name":"get","arguments":"{\"c\":3}"}}`, + bufferedHostedItemsCompleted, + )) + require.Equal(t, []string{ + `function_call:fc_1:{"a":1}:`, + `function_call:fc_2:{"b":2}:`, + `function_call:fc_3:{"c":3}:`, + }, items) +} + +func TestForwardAsAnthropic_CancelledTerminalKeepsHostedOutputItems(t *testing.T) { + cancelled := `{"type":"response.cancelled","response":{"id":"resp_1","status":"cancelled","output":[],"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}` + out := forwardBufferedHostedItems(t, "/v1/messages", bufferedHostedItemsMessagesBody, + bufferedItemsSSE(bufferedHostedItemsCreated, bufferedHostedItemsWebSearchDone, cancelled)) + require.Equal(t, "server_tool_use", gjson.Get(out, "content.0.type").String(), out) +} diff --git a/backend/internal/service/openai_gateway_buffered_stream_parity_test.go b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go new file mode 100644 index 0000000000..455c5e5875 --- /dev/null +++ b/backend/internal/service/openai_gateway_buffered_stream_parity_test.go @@ -0,0 +1,347 @@ +//go:build unit + +package service + +import ( + "bytes" + "context" + "fmt" + "net/http" + "net/http/httptest" + "sort" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +const bufferedParityMessagesBody = `{"model":"gpt-5.5","max_tokens":4096,"stream":%t,"thinking":{"type":"enabled","budget_tokens":2048},"tools":[{"name":"record_version","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"USER_PROMPT_PLACEHOLDER"}]}` + +const bufferedParityChatBody = `{"model":"gpt-5.5","stream":%t,"reasoning_effort":"medium","tools":[{"type":"function","function":{"name":"record_version","parameters":{"type":"object"}}}],"messages":[{"role":"user","content":"USER_PROMPT_PLACEHOLDER"}]}` + +func bufferedParityReasoning(index int, id, text, encrypted string) []string { + summary := `[]` + if text != "" { + summary = fmt.Sprintf(`[{"type":"summary_text","text":%q}]`, text) + } + events := []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"reasoning","id":%q,"summary":[]}}`, index, id), + } + if text != "" { + events = append(events, + fmt.Sprintf(`{"type":"response.reasoning_summary_part.added","output_index":%d,"summary_index":0,"part":{"type":"summary_text","text":""}}`, index), + fmt.Sprintf(`{"type":"response.reasoning_summary_text.delta","output_index":%d,"summary_index":0,"delta":%q}`, index, text), + fmt.Sprintf(`{"type":"response.reasoning_summary_text.done","output_index":%d,"summary_index":0,"text":%q}`, index, text), + ) + } + return append(events, fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"reasoning","id":%q,"summary":%s,"encrypted_content":%q}}`, index, id, summary, encrypted)) +} + +func bufferedParityWebSearch(index int, id, query string) []string { + return []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"web_search_call","id":%q,"status":"in_progress"}}`, index, id), + fmt.Sprintf(`{"type":"response.web_search_call.in_progress","output_index":%d,"item_id":%q}`, index, id), + fmt.Sprintf(`{"type":"response.web_search_call.searching","output_index":%d,"item_id":%q}`, index, id), + fmt.Sprintf(`{"type":"response.web_search_call.completed","output_index":%d,"item_id":%q}`, index, id), + fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"web_search_call","id":%q,"status":"completed","action":{"type":"search","query":%q}}}`, index, id, query), + } +} + +func bufferedParityFunctionCall(index int) []string { + return []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"function_call","id":"fc_1","call_id":"call_c","name":"record_version","arguments":""}}`, index), + fmt.Sprintf(`{"type":"response.function_call_arguments.delta","output_index":%d,"item_id":"fc_1","delta":"{\"version\""}`, index), + fmt.Sprintf(`{"type":"response.function_call_arguments.delta","output_index":%d,"item_id":"fc_1","delta":":\"1.25\"}"}`, index), + fmt.Sprintf(`{"type":"response.function_call_arguments.done","output_index":%d,"item_id":"fc_1","arguments":"{\"version\":\"1.25\"}"}`, index), + fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"function_call","id":"fc_1","call_id":"call_c","name":"record_version","arguments":"{\"version\":\"1.25\"}","status":"completed"}}`, index), + } +} + +func bufferedParityMessage(index int, text string) []string { + content := `[{"type":"output_text","text":""}]` + events := []string{ + fmt.Sprintf(`{"type":"response.output_item.added","output_index":%d,"item":{"type":"message","id":"msg_1","role":"assistant","status":"in_progress","phase":"final_answer","content":[]}}`, index), + fmt.Sprintf(`{"type":"response.content_part.added","output_index":%d,"content_index":0,"part":{"type":"output_text","text":""}}`, index), + } + if text != "" { + content = fmt.Sprintf(`[{"type":"output_text","text":%q}]`, text) + events = append(events, + fmt.Sprintf(`{"type":"response.output_text.delta","output_index":%d,"content_index":0,"delta":%q}`, index, text), + fmt.Sprintf(`{"type":"response.output_text.done","output_index":%d,"content_index":0,"text":%q}`, index, text), + ) + } + return append(events, + fmt.Sprintf(`{"type":"response.content_part.done","output_index":%d,"content_index":0,"part":{"type":"output_text","text":%q}}`, index, text), + fmt.Sprintf(`{"type":"response.output_item.done","output_index":%d,"item":{"type":"message","id":"msg_1","role":"assistant","status":"completed","phase":"final_answer","content":%s}}`, index, content), + ) +} + +func bufferedParityStream(terminalOutput string, groups ...[]string) string { + events := []string{bufferedHostedItemsCreated} + for _, group := range groups { + events = append(events, group...) + } + events = append(events, fmt.Sprintf(`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":%s,"usage":{"input_tokens":5,"output_tokens":2,"total_tokens":7}}}`, terminalOutput)) + return bufferedItemsSSE(events...) +} + +// bufferedParityBlocks reduces an Anthropic content array to one line per block. +func bufferedParityBlocks(blocks []gjson.Result) []string { + var lines []string + for _, block := range blocks { + switch block.Get("type").String() { + case "thinking": + lines = append(lines, fmt.Sprintf("thinking %q signature=%q", block.Get("thinking").String(), block.Get("signature").String())) + case "text": + lines = append(lines, fmt.Sprintf("text %q", block.Get("text").String())) + case "tool_use": + lines = append(lines, fmt.Sprintf("tool_use %s %s %s", block.Get("id").String(), block.Get("name").String(), block.Get("input").Raw)) + case "server_tool_use": + lines = append(lines, fmt.Sprintf("server_tool_use %s %s", block.Get("id").String(), block.Get("input").Raw)) + case "web_search_tool_result": + lines = append(lines, fmt.Sprintf("web_search_tool_result %s", block.Get("tool_use_id").String())) + default: + lines = append(lines, "other "+block.Get("type").String()) + } + } + return lines +} + +// bufferedParityStreamBlocks folds an Anthropic SSE body back into content blocks. +func bufferedParityStreamBlocks(t *testing.T, sse string) []string { + t.Helper() + type streamed struct { + kind, id, name, toolUseID, thinking, text, signature, input string + } + byIndex := map[int64]*streamed{} + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok || !gjson.Valid(data) { + continue + } + index := gjson.Get(data, "index").Int() + switch gjson.Get(data, "type").String() { + case "content_block_start": + block := gjson.Get(data, "content_block") + byIndex[index] = &streamed{ + kind: block.Get("type").String(), id: block.Get("id").String(), name: block.Get("name").String(), + toolUseID: block.Get("tool_use_id").String(), input: block.Get("input").Raw, + } + case "content_block_delta": + block := byIndex[index] + require.NotNil(t, block, data) + delta := gjson.Get(data, "delta") + switch delta.Get("type").String() { + case "thinking_delta": + block.thinking += delta.Get("thinking").String() + case "text_delta": + block.text += delta.Get("text").String() + case "signature_delta": + block.signature = delta.Get("signature").String() + case "input_json_delta": + if block.input == "{}" { + block.input = "" + } + block.input += delta.Get("partial_json").String() + } + } + } + indexes := make([]int64, 0, len(byIndex)) + for index := range byIndex { + indexes = append(indexes, index) + } + sort.Slice(indexes, func(i, j int) bool { return indexes[i] < indexes[j] }) + var lines []string + for _, index := range indexes { + block := byIndex[index] + switch block.kind { + case "thinking": + lines = append(lines, fmt.Sprintf("thinking %q signature=%q", block.thinking, block.signature)) + case "text": + lines = append(lines, fmt.Sprintf("text %q", block.text)) + case "tool_use": + lines = append(lines, fmt.Sprintf("tool_use %s %s %s", block.id, block.name, block.input)) + case "server_tool_use": + lines = append(lines, fmt.Sprintf("server_tool_use %s %s", block.id, block.input)) + case "web_search_tool_result": + lines = append(lines, fmt.Sprintf("web_search_tool_result %s", block.toolUseID)) + default: + lines = append(lines, "other "+block.kind) + } + } + return lines +} + +// bufferedParityChat reduces a Chat Completions answer to the fields a client reads. +func bufferedParityChatSummary(reasoning, content string, calls []string, finish string) string { + return fmt.Sprintf("reasoning=%q content=%q tool_calls=%v finish_reason=%s", reasoning, content, calls, finish) +} + +func bufferedParityChatNonStream(body string) string { + message := gjson.Get(body, "choices.0.message") + var calls []string + for _, call := range message.Get("tool_calls").Array() { + calls = append(calls, fmt.Sprintf("%s %s %s", call.Get("id").String(), call.Get("function.name").String(), call.Get("function.arguments").String())) + } + return bufferedParityChatSummary(message.Get("reasoning_content").String(), message.Get("content").String(), calls, gjson.Get(body, "choices.0.finish_reason").String()) +} + +func bufferedParityChatStream(sse string) string { + var reasoning, content, finish string + type call struct{ id, name, args string } + calls := map[int64]*call{} + for _, line := range strings.Split(sse, "\n") { + data, ok := strings.CutPrefix(line, "data: ") + if !ok || !gjson.Valid(data) { + continue + } + choice := gjson.Get(data, "choices.0") + reasoning += choice.Get("delta.reasoning_content").String() + content += choice.Get("delta.content").String() + if reason := choice.Get("finish_reason"); reason.Exists() && reason.Type != gjson.Null { + finish = reason.String() + } + for _, tc := range choice.Get("delta.tool_calls").Array() { + index := tc.Get("index").Int() + if calls[index] == nil { + calls[index] = &call{} + } + if id := tc.Get("id").String(); id != "" { + calls[index].id = id + } + if name := tc.Get("function.name").String(); name != "" { + calls[index].name = name + } + calls[index].args += tc.Get("function.arguments").String() + } + } + indexes := make([]int64, 0, len(calls)) + for index := range calls { + indexes = append(indexes, index) + } + sort.Slice(indexes, func(i, j int) bool { return indexes[i] < indexes[j] }) + var lines []string + for _, index := range indexes { + lines = append(lines, fmt.Sprintf("%s %s %s", calls[index].id, calls[index].name, calls[index].args)) + } + return bufferedParityChatSummary(reasoning, content, lines, finish) +} + +func forwardBufferedParity(t *testing.T, path, requestBody, upstreamSSE string) string { + t.Helper() + gin.SetMode(gin.TestMode) + rec := httptest.NewRecorder() + c, _ := gin.CreateTestContext(rec) + body := []byte(requestBody) + c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + svc := &OpenAIGatewayService{ + httpUpstream: &httpUpstreamRecorder{resp: bufferedHostedItemsSSEResponse(upstreamSSE)}, + cfg: rawChatCompletionsTestConfig(), + } + account := bufferedHostedItemsOAuthAccount() + var err error + if path == "/v1/chat/completions" { + _, err = svc.ForwardAsChatCompletions(context.Background(), c, account, body, "", "") + } else { + _, err = svc.ForwardAsAnthropic(context.Background(), c, account, body, "", "") + } + require.NoError(t, err) + require.Equal(t, http.StatusOK, rec.Code, rec.Body.String()) + return rec.Body.String() +} + +// A buffered /v1/messages or /v1/chat/completions answer must carry what the +// streaming path delivers for the same upstream event stream. The shapes are the +// ones real Codex streams produced; texts are placeholders. +func TestBufferedCompat_MatchesStreamingPathOnRealStreamShapes(t *testing.T) { + reasoningThenMessage := func(terminal string) string { + return bufferedParityStream(terminal, + bufferedParityReasoning(0, "rs_1", "REASON_TEXT_PLACEHOLDER", "ENC_PLACEHOLDER_1"), + bufferedParityMessage(1, "ANSWER_PLACEHOLDER")) + } + signatureOnlyThenEmptyMessage := func(terminal string) string { + return bufferedParityStream(terminal, + bufferedParityReasoning(0, "rs_1", "", "ENC_PLACEHOLDER_1"), + bufferedParityMessage(1, "")) + } + const filledTerminal = `[{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"REASON_TEXT_PLACEHOLDER"}],"encrypted_content":"ENC_PLACEHOLDER_1"},{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"ANSWER_PLACEHOLDER"}]}]` + const signatureOnlyTerminal = `[{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"ENC_PLACEHOLDER_1"},{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":""}]}]` + webSearchTurn := bufferedParityStream(`[]`, + bufferedParityReasoning(0, "rs_1", "REASON_ONE_PLACEHOLDER", "ENC_PLACEHOLDER_1"), + bufferedParityWebSearch(1, "ws_1", "QUERY_ONE_PLACEHOLDER"), + bufferedParityReasoning(2, "rs_2", "REASON_TWO_PLACEHOLDER", "ENC_PLACEHOLDER_2"), + bufferedParityWebSearch(3, "ws_2", "QUERY_TWO_PLACEHOLDER"), + bufferedParityReasoning(4, "rs_3", "REASON_THREE_PLACEHOLDER", "ENC_PLACEHOLDER_3"), + bufferedParityFunctionCall(5)) + + cases := []struct { + name string + sse string + wantMessages []string + wantChat string + }{ + { + name: "reasoning and message, filled terminal", + sse: reasoningThenMessage(filledTerminal), + wantMessages: []string{ + `thinking "REASON_TEXT_PLACEHOLDER" signature="ENC_PLACEHOLDER_1"`, + `text "ANSWER_PLACEHOLDER"`, + }, + wantChat: bufferedParityChatSummary("REASON_TEXT_PLACEHOLDER", "ANSWER_PLACEHOLDER", nil, "stop"), + }, + { + name: "reasoning and message, empty terminal", + sse: reasoningThenMessage(`[]`), + wantMessages: []string{ + `thinking "REASON_TEXT_PLACEHOLDER" signature="ENC_PLACEHOLDER_1"`, + `text "ANSWER_PLACEHOLDER"`, + }, + wantChat: bufferedParityChatSummary("REASON_TEXT_PLACEHOLDER", "ANSWER_PLACEHOLDER", nil, "stop"), + }, + { + name: "signature only reasoning and empty message, filled terminal", + sse: signatureOnlyThenEmptyMessage(signatureOnlyTerminal), + wantMessages: []string{`thinking "" signature="ENC_PLACEHOLDER_1"`}, + wantChat: bufferedParityChatSummary("", "", nil, "stop"), + }, + { + name: "signature only reasoning and empty message, empty terminal", + sse: signatureOnlyThenEmptyMessage(`[]`), + wantMessages: []string{`thinking "" signature="ENC_PLACEHOLDER_1"`}, + wantChat: bufferedParityChatSummary("", "", nil, "stop"), + }, + { + name: "web search turn with a client tool, empty terminal", + sse: webSearchTurn, + wantMessages: []string{ + `thinking "REASON_ONE_PLACEHOLDER" signature="ENC_PLACEHOLDER_1"`, + `server_tool_use srvtoolu_ws_1 {"query":"QUERY_ONE_PLACEHOLDER"}`, + `web_search_tool_result srvtoolu_ws_1`, + `thinking "REASON_TWO_PLACEHOLDER" signature="ENC_PLACEHOLDER_2"`, + `server_tool_use srvtoolu_ws_2 {"query":"QUERY_TWO_PLACEHOLDER"}`, + `web_search_tool_result srvtoolu_ws_2`, + `thinking "REASON_THREE_PLACEHOLDER" signature="ENC_PLACEHOLDER_3"`, + `tool_use call_c record_version {"version":"1.25"}`, + }, + wantChat: bufferedParityChatSummary("REASON_ONE_PLACEHOLDERREASON_TWO_PLACEHOLDERREASON_THREE_PLACEHOLDER", "", []string{`call_c record_version {"version":"1.25"}`}, "tool_calls"), + }, + } + for _, tc := range cases { + t.Run(tc.name+" messages", func(t *testing.T) { + buffered := forwardBufferedParity(t, "/v1/messages", fmt.Sprintf(bufferedParityMessagesBody, false), tc.sse) + streamed := forwardBufferedParity(t, "/v1/messages", fmt.Sprintf(bufferedParityMessagesBody, true), tc.sse) + require.Equal(t, tc.wantMessages, bufferedParityBlocks(gjson.Get(buffered, "content").Array()), buffered) + streamedBlocks := bufferedParityStreamBlocks(t, streamed) + require.Equal(t, tc.wantMessages, streamedBlocks, streamed) + }) + t.Run(tc.name+" chat", func(t *testing.T) { + buffered := forwardBufferedParity(t, "/v1/chat/completions", fmt.Sprintf(bufferedParityChatBody, false), tc.sse) + streamed := forwardBufferedParity(t, "/v1/chat/completions", fmt.Sprintf(bufferedParityChatBody, true), tc.sse) + require.Equal(t, tc.wantChat, bufferedParityChatNonStream(buffered), buffered) + require.Equal(t, tc.wantChat, bufferedParityChatStream(streamed), streamed) + }) + } +} diff --git a/backend/internal/service/openai_gateway_messages.go b/backend/internal/service/openai_gateway_messages.go index 593067e491..b4ba5ba25a 100644 --- a/backend/internal/service/openai_gateway_messages.go +++ b/backend/internal/service/openai_gateway_messages.go @@ -835,7 +835,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( ) (*apicompat.ResponsesResponse, OpenAIUsage, *apicompat.BufferedResponseAccumulator, openAICompatPriorModelAudit, error) { acc := apicompat.NewBufferedResponseAccumulator() acc.XAIServerSideSearch = account != nil && account.IsGrok() - hostedItems := &openAICompatHostedItems{} + outputSlots := &openAICompatOutputSlots{} var usage OpenAIUsage if resp == nil || resp.Body == nil { return nil, usage, acc, openAICompatPriorModelAudit{}, errors.New("upstream response body is nil") @@ -924,7 +924,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if frame, ok := parser.Finish(); ok { payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) - hostedItems.Observe([]byte(payload)) + outputSlots.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err == nil { s.parseSSEUsageBytesWithType([]byte(payload), event.Type, &usage) @@ -940,7 +940,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage) } - hostedItems.fillTerminalOutput(event.Type, response, acc) + outputSlots.fillTerminalOutput(event.Type, response) return response, usage, acc, prior, nil } } @@ -967,7 +967,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( } payload := openAICompatPayloadWithEventType(frame.Data, frame.EventType) payload = string(restoreCodexToolNamesFromContext(c, []byte(payload))) - hostedItems.Observe([]byte(payload)) + outputSlots.Observe([]byte(payload)) var event apicompat.ResponsesStreamEvent if err := json.Unmarshal([]byte(payload), &event); err != nil { @@ -992,7 +992,7 @@ func (s *OpenAIGatewayService) readOpenAICompatBufferedTerminal( if response.Usage != nil { usage = copyOpenAIUsageFromResponsesUsage(response.Usage) } - hostedItems.fillTerminalOutput(event.Type, response, acc) + outputSlots.fillTerminalOutput(event.Type, response) return response, usage, acc, prior, nil }