fix(claude): preserve adjacent same-response thinking blocks in openai responses translation

- Parse Claude response ID and content block index from Responses reasoning item IDs so ascending adjacent thinking blocks from the same response stay intact on replay.
- Collapse cross-response, out-of-order, or unattributed trailing thinking runs while deduplicating repeated trailing block indices without dropping earlier same-response blocks.
- Add unit and stream/non-stream round-trip tests covering same-response pairs, cross-response collapses, duplicate indices, and ID parsing edge cases.

Closes: #7831
This commit is contained in:
Luis Pater
2026-11-22 15:38:29 +08:00
parent 737ba4c60d
commit c71aa824e5
2 changed files with 370 additions and 6 deletions

View File

@@ -1,6 +1,8 @@
package responses
import (
"bytes"
"context"
"fmt"
"testing"
@@ -124,6 +126,309 @@ func TestConvertOpenAIResponsesRequestToClaude_NonThinkingBlocksSeparateReasonin
}
}
func TestConvertOpenAIResponsesRequestToClaude_KeepsSameResponseThinkingBlocks(t *testing.T) {
reasoningRaw, reasoningSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-reasoning")
updateRaw, updateSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-update")
// One Claude response returned a reasoning block, a progress-update block,
// and a tool call; the response translator named them rs_<id>_<index>.
raw := responsesRequestFromItems(
responsesReasoningItemWithID("rs_msg_01Same_0", reasoningRaw, "primary reasoning"),
responsesReasoningItemWithID("rs_msg_01Same_1", updateRaw, "progress update"),
responsesFunctionCallItem("call_same", "same_tool"),
responsesFunctionCallOutputItem("call_same", "done"),
)
out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)
content := ojson.GetBytesNoCopy(out, "messages.0.content").Array()
wantTypes := []string{"thinking", "thinking", "tool_use"}
if len(content) != len(wantTypes) {
t.Fatalf("assistant content count = %d, want %d. Output: %s", len(content), len(wantTypes), out)
}
for index, wantType := range wantTypes {
if got := content[index].Get("type").String(); got != wantType {
t.Fatalf("assistant content[%d].type = %q, want %q. Output: %s", index, got, wantType, out)
}
}
if got := content[0].Get("thinking").String(); got != "primary reasoning" {
t.Fatalf("first thinking text = %q, want primary reasoning", got)
}
if got := content[0].Get("signature").String(); got != reasoningSignature {
t.Fatalf("first thinking signature = %q, want reasoning signature %q", got, reasoningSignature)
}
if got := content[1].Get("thinking").String(); got != "progress update" {
t.Fatalf("second thinking text = %q, want progress update", got)
}
if got := content[1].Get("signature").String(); got != updateSignature {
t.Fatalf("second thinking signature = %q, want progress-update signature %q", got, updateSignature)
}
}
func TestConvertOpenAIResponsesRequestToClaude_CollapsesThinkingFromDifferentResponses(t *testing.T) {
firstRaw, _ := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-first")
updateRaw, _ := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-update")
laterRaw, laterSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-later")
// A later response's thinking must not stay adjacent to an earlier
// response's, so the earlier trailing thinking run is replaced as a whole.
raw := responsesRequestFromItems(
responsesReasoningItemWithID("rs_msg_01First_0", firstRaw, "first reasoning"),
responsesReasoningItemWithID("rs_msg_01First_1", updateRaw, "first update"),
responsesReasoningItemWithID("rs_msg_01Later_0", laterRaw, "later reasoning"),
responsesFunctionCallItem("call_later", "later_tool"),
responsesFunctionCallOutputItem("call_later", "done"),
)
out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)
content := ojson.GetBytesNoCopy(out, "messages.0.content").Array()
wantTypes := []string{"thinking", "tool_use"}
if len(content) != len(wantTypes) {
t.Fatalf("assistant content count = %d, want %d. Output: %s", len(content), len(wantTypes), out)
}
for index, wantType := range wantTypes {
if got := content[index].Get("type").String(); got != wantType {
t.Fatalf("assistant content[%d].type = %q, want %q. Output: %s", index, got, wantType, out)
}
}
if got := content[0].Get("signature").String(); got != laterSignature {
t.Fatalf("thinking signature = %q, want latest response signature %q. Output: %s", got, laterSignature, out)
}
}
func TestConvertOpenAIResponsesRequestToClaude_CollapsesDuplicateOrInvalidSameResponseThinking(t *testing.T) {
firstRaw, _ := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-first")
secondRaw, secondSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-second")
cases := []struct {
name string
firstID string
secondID string
}{
{name: "duplicate block index", firstID: "rs_msg_01Dup_0", secondID: "rs_msg_01Dup_0"},
{name: "descending block index", firstID: "rs_msg_01Order_2", secondID: "rs_msg_01Order_1"},
{name: "negative block index", firstID: "rs_msg_01Neg_-1", secondID: "rs_msg_01Neg_0"},
{name: "empty response id", firstID: "rs__0", secondID: "rs__1"},
{name: "signed positive suffix", firstID: "rs_msg_01Plus_+0", secondID: "rs_msg_01Plus_+1"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
raw := responsesRequestFromItems(
responsesReasoningItemWithID(tc.firstID, firstRaw, "first"),
responsesReasoningItemWithID(tc.secondID, secondRaw, "second"),
responsesFunctionCallItem("call_edge", "edge_tool"),
responsesFunctionCallOutputItem("call_edge", "done"),
)
out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)
content := ojson.GetBytesNoCopy(out, "messages.0.content").Array()
wantTypes := []string{"thinking", "tool_use"}
if len(content) != len(wantTypes) {
t.Fatalf("assistant content count = %d, want %d. Output: %s", len(content), len(wantTypes), out)
}
for index, wantType := range wantTypes {
if got := content[index].Get("type").String(); got != wantType {
t.Fatalf("assistant content[%d].type = %q, want %q. Output: %s", index, got, wantType, out)
}
}
if got := content[0].Get("signature").String(); got != secondSignature {
t.Fatalf("thinking signature = %q, want %q. Output: %s", got, secondSignature, out)
}
})
}
}
func TestConvertOpenAIResponsesRequestToClaude_RoundTripsSameResponseAdjacentThinkingBlocks(t *testing.T) {
reasoningRaw, reasoningSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-reasoning")
updateRaw, updateSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-update")
chunks := [][]byte{
[]byte(`data: {"type":"message_start","message":{"id":"msg_01RoundTrip","usage":{"input_tokens":10,"output_tokens":0}}}`),
[]byte(`data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`),
[]byte(`data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"Inspect the repository."}}`),
[]byte(fmt.Sprintf(`data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":%q}}`, reasoningRaw)),
[]byte(`data: {"type":"content_block_stop","index":0}`),
[]byte(`data: {"type":"content_block_start","index":1,"content_block":{"type":"thinking","thinking":""}}`),
[]byte(`data: {"type":"content_block_delta","index":1,"delta":{"type":"thinking_delta","thinking":"Running grep now."}}`),
[]byte(fmt.Sprintf(`data: {"type":"content_block_delta","index":1,"delta":{"type":"signature_delta","signature":%q}}`, updateRaw)),
[]byte(`data: {"type":"content_block_stop","index":1}`),
[]byte(`data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_01RT","name":"exec_command","input":{}}}`),
[]byte(`data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"cmd\":\"ls\"}"}}`),
[]byte(`data: {"type":"content_block_stop","index":2}`),
[]byte(`data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":20}}`),
[]byte(`data: {"type":"message_stop"}`),
}
assertRoundTrip := func(t *testing.T, outputArray ojson.Result) {
t.Helper()
var items []string
outputArray.ForEach(func(_, item ojson.Result) bool {
items = append(items, item.Raw)
return true
})
items = append(items, responsesFunctionCallOutputItem("toolu_01RT", "ok"))
replayReq := responsesRequestFromItems(items...)
claudeReq, err := ConvertOpenAIResponsesRequestToClaude("claude-opus-5-5", replayReq, false)
if err != nil {
t.Fatalf("ConvertOpenAIResponsesRequestToClaude error = %v", err)
}
content := ojson.GetBytesNoCopy(claudeReq, "messages.0.content").Array()
wantTypes := []string{"thinking", "thinking", "tool_use"}
if len(content) != len(wantTypes) {
t.Fatalf("assistant content count = %d, want %d. Output: %s", len(content), len(wantTypes), claudeReq)
}
for index, wantType := range wantTypes {
if got := content[index].Get("type").String(); got != wantType {
t.Fatalf("assistant content[%d].type = %q, want %q. Output: %s", index, got, wantType, claudeReq)
}
}
if got := content[0].Get("thinking").String(); got != "Inspect the repository." {
t.Fatalf("first thinking text = %q, want Inspect the repository.", got)
}
if got := content[0].Get("signature").String(); got != reasoningSignature {
t.Fatalf("first thinking signature = %q, want %q", got, reasoningSignature)
}
if got := content[1].Get("thinking").String(); got != "Running grep now." {
t.Fatalf("second thinking text = %q, want Running grep now.", got)
}
if got := content[1].Get("signature").String(); got != updateSignature {
t.Fatalf("second thinking signature = %q, want %q", got, updateSignature)
}
}
t.Run("stream", func(t *testing.T) {
outputs := translateClaudeResponsesStreamThroughRegistry(chunks)
var completed ojson.Result
for _, output := range outputs {
event, data := parseClaudeResponsesSSEEvent(t, output)
if event == "response.completed" {
completed = data
}
}
if !completed.Exists() {
t.Fatalf("missing response.completed event")
}
assertRoundTrip(t, completed.Get("response.output"))
})
t.Run("non-stream", func(t *testing.T) {
rawResp := ConvertClaudeResponseToOpenAIResponsesNonStream(
context.Background(),
"claude-opus-5-5",
nil,
nil,
bytes.Join(chunks, []byte("\n")),
nil,
)
assertRoundTrip(t, ojson.GetBytesNoCopy(rawResp, "output"))
})
}
func TestParseClaudeReasoningItemID(t *testing.T) {
cases := []struct {
itemID string
wantRespID string
wantIndex int
wantOK bool
}{
{itemID: "rs_msg_011ChF1ocEToPEeFhKVmgRWx_0", wantRespID: "msg_011ChF1ocEToPEeFhKVmgRWx", wantIndex: 0, wantOK: true},
{itemID: "rs_resp_1_12", wantRespID: "resp_1", wantIndex: 12, wantOK: true},
{itemID: "rs_msg", wantRespID: "", wantIndex: -1, wantOK: false},
{itemID: "rs__1", wantRespID: "", wantIndex: -1, wantOK: false},
{itemID: "rs_ _1", wantRespID: "", wantIndex: -1, wantOK: false},
{itemID: "rs_msg_", wantRespID: "", wantIndex: -1, wantOK: false},
{itemID: "rs_msg_-1", wantRespID: "", wantIndex: -1, wantOK: false},
{itemID: "rs_msg_+1", wantRespID: "", wantIndex: -1, wantOK: false},
{itemID: "rs_msg_x", wantRespID: "", wantIndex: -1, wantOK: false},
{itemID: "msg_1_0", wantRespID: "", wantIndex: -1, wantOK: false},
{itemID: "", wantRespID: "", wantIndex: -1, wantOK: false},
}
for _, tc := range cases {
gotRespID, gotIndex, gotOK := parseClaudeReasoningItemID(tc.itemID)
if gotRespID != tc.wantRespID || gotIndex != tc.wantIndex || gotOK != tc.wantOK {
t.Errorf("parseClaudeReasoningItemID(%q) = (%q, %d, %v), want (%q, %d, %v)",
tc.itemID, gotRespID, gotIndex, gotOK, tc.wantRespID, tc.wantIndex, tc.wantOK)
}
}
}
func TestConvertOpenAIResponsesRequestToClaude_CollapsesReplayedSameResponseThinkingPair(t *testing.T) {
firstRaw, _ := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-first")
firstUpdateRaw, _ := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-first-update")
secondRaw, secondSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-second")
secondUpdateRaw, secondUpdateSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-second-update")
raw := responsesRequestFromItems(
responsesReasoningItemWithID("rs_msg_01Same_0", firstRaw, "first reasoning"),
responsesReasoningItemWithID("rs_msg_01Same_1", firstUpdateRaw, "first update"),
responsesReasoningItemWithID("rs_msg_01Same_0", secondRaw, "replayed reasoning"),
responsesReasoningItemWithID("rs_msg_01Same_1", secondUpdateRaw, "replayed update"),
responsesFunctionCallItem("call_replay", "replay_tool"),
responsesFunctionCallOutputItem("call_replay", "done"),
)
out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)
content := ojson.GetBytesNoCopy(out, "messages.0.content").Array()
wantTypes := []string{"thinking", "thinking", "tool_use"}
if len(content) != len(wantTypes) {
t.Fatalf("assistant content count = %d, want %d. Output: %s", len(content), len(wantTypes), out)
}
for index, wantType := range wantTypes {
if got := content[index].Get("type").String(); got != wantType {
t.Fatalf("assistant content[%d].type = %q, want %q. Output: %s", index, got, wantType, out)
}
}
if got := content[0].Get("signature").String(); got != secondSignature {
t.Fatalf("first thinking signature = %q, want %q", got, secondSignature)
}
if got := content[1].Get("signature").String(); got != secondUpdateSignature {
t.Fatalf("second thinking signature = %q, want %q", got, secondUpdateSignature)
}
}
func TestConvertOpenAIResponsesRequestToClaude_DuplicateTrailingSameResponseThinkingPreservesPrefix(t *testing.T) {
reasoningRaw, reasoningSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-reasoning")
firstUpdateRaw, _ := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-update-first")
secondUpdateRaw, secondUpdateSignature := testClaudeResponsesThinkingSignatureForModel(t, "claude-opus-5-5-update-second")
raw := responsesRequestFromItems(
responsesReasoningItemWithID("rs_msg_01Same_0", reasoningRaw, "primary reasoning"),
responsesReasoningItemWithID("rs_msg_01Same_1", firstUpdateRaw, "first progress update"),
responsesReasoningItemWithID("rs_msg_01Same_1", secondUpdateRaw, "latest progress update"),
responsesFunctionCallItem("call_dup_tail", "dup_tail_tool"),
responsesFunctionCallOutputItem("call_dup_tail", "done"),
)
out, _ := ConvertOpenAIResponsesRequestToClaude("claude-test", raw, false)
content := ojson.GetBytesNoCopy(out, "messages.0.content").Array()
wantTypes := []string{"thinking", "thinking", "tool_use"}
if len(content) != len(wantTypes) {
t.Fatalf("assistant content count = %d, want %d. Output: %s", len(content), len(wantTypes), out)
}
for index, wantType := range wantTypes {
if got := content[index].Get("type").String(); got != wantType {
t.Fatalf("assistant content[%d].type = %q, want %q. Output: %s", index, got, wantType, out)
}
}
if got := content[0].Get("thinking").String(); got != "primary reasoning" {
t.Fatalf("first thinking text = %q, want primary reasoning", got)
}
if got := content[0].Get("signature").String(); got != reasoningSignature {
t.Fatalf("first thinking signature = %q, want %q", got, reasoningSignature)
}
if got := content[1].Get("thinking").String(); got != "latest progress update" {
t.Fatalf("second thinking text = %q, want latest progress update", got)
}
if got := content[1].Get("signature").String(); got != secondUpdateSignature {
t.Fatalf("second thinking signature = %q, want %q", got, secondUpdateSignature)
}
}
func responsesReasoningItemWithID(id, signature, text string) string {
return fmt.Sprintf(`{"type":"reasoning","id":%q,"encrypted_content":%q,"summary":[{"type":"summary_text","text":%q}]}`, id, signature, text)
}
func responsesReasoningItem(signature, text string) string {
return fmt.Sprintf(`{"type":"reasoning","encrypted_content":%q,"summary":[{"type":"summary_text","text":%q}]}`, signature, text)
}

View File

@@ -216,6 +216,9 @@ func convertOpenAIResponsesRequestToClaude(ctx context.Context, modelName string
var pendingRole string
var pendingParts [][]byte
var pendingToolUseParts [][]byte
// Claude response origin of the trailing thinking block in pendingParts.
var pendingThinkingResponseID string
pendingThinkingBlockIndex := -1
var turnHasEmptyWebSearchResult bool
// Anthropic accepts a role=system turn only after a user message and before
// an assistant message or the end of messages. Mid-session system items are
@@ -276,6 +279,8 @@ func convertOpenAIResponsesRequestToClaude(ctx context.Context, modelName string
pendingRole = ""
pendingParts = nil
pendingToolUseParts = nil
pendingThinkingResponseID = ""
pendingThinkingBlockIndex = -1
}
appendParts := func(role string, parts ...[]byte) {
if role == "" || len(parts) == 0 {
@@ -286,6 +291,8 @@ func convertOpenAIResponsesRequestToClaude(ctx context.Context, modelName string
}
pendingRole = role
pendingParts = append(pendingParts, parts...)
pendingThinkingResponseID = ""
pendingThinkingBlockIndex = -1
}
appendToolUse := func(toolUse []byte) {
if len(toolUse) == 0 {
@@ -297,7 +304,7 @@ func convertOpenAIResponsesRequestToClaude(ctx context.Context, modelName string
pendingRole = "assistant"
pendingToolUseParts = append(pendingToolUseParts, toolUse)
}
appendReasoning := func(reasoningPart []byte) {
appendReasoning := func(reasoningPart []byte, responseID string, blockIndex int, hasOrigin bool) {
if len(reasoningPart) == 0 {
return
}
@@ -311,17 +318,36 @@ func convertOpenAIResponsesRequestToClaude(ctx context.Context, modelName string
if len(pendingToolUseParts) > 0 {
pendingParts = append(pendingParts, pendingToolUseParts...)
pendingToolUseParts = nil
pendingThinkingResponseID = ""
pendingThinkingBlockIndex = -1
}
// Adjacent thinking blocks from different responses are rejected by
// Anthropic, so only the latest is kept. Blocks from the same response
// in ascending block index order, such as a reasoning block followed by
// a progress-update block, are replayed unchanged as Anthropic requires.
currentType := ojson.GetBytesNoCopy(reasoningPart, "type").String()
if currentType == "thinking" && len(pendingParts) > 0 {
lastIdx := len(pendingParts) - 1
if ojson.GetBytesNoCopy(pendingParts[lastIdx], "type").String() == "thinking" {
pendingParts[lastIdx] = reasoningPart
sameResponse := hasOrigin && responseID == pendingThinkingResponseID
if currentType == "thinking" {
if sameResponse && blockIndex == pendingThinkingBlockIndex && len(pendingParts) > 0 && ojson.GetBytesNoCopy(pendingParts[len(pendingParts)-1], "type").String() == "thinking" {
// Replaying the same trailing block index replaces only that block.
pendingParts[len(pendingParts)-1] = reasoningPart
return
}
if !(sameResponse && blockIndex > pendingThinkingBlockIndex) {
for len(pendingParts) > 0 && ojson.GetBytesNoCopy(pendingParts[len(pendingParts)-1], "type").String() == "thinking" {
pendingParts = pendingParts[:len(pendingParts)-1]
}
}
}
pendingParts = append(pendingParts, reasoningPart)
if currentType == "thinking" && hasOrigin {
pendingThinkingResponseID = responseID
pendingThinkingBlockIndex = blockIndex
} else {
pendingThinkingResponseID = ""
pendingThinkingBlockIndex = -1
}
}
var inputItems []ojson.Result
@@ -513,7 +539,8 @@ func convertOpenAIResponsesRequestToClaude(ctx context.Context, modelName string
}
case "reasoning":
appendReasoning(convertResponsesReasoningToClaudeThinking(item, preserveEmptyThinkingBlocks))
responseID, blockIndex, hasOrigin := parseClaudeReasoningItemID(item.Get("id").String())
appendReasoning(convertResponsesReasoningToClaudeThinking(item, preserveEmptyThinkingBlocks), responseID, blockIndex, hasOrigin)
case "function_call", "custom_tool_call":
// Map to assistant tool_use. Freeform custom input is wrapped in an
@@ -1174,6 +1201,38 @@ func convertResponsesReasoningToClaudeThinking(item ojson.Result, preserveEmptyT
return thinkingPartDoc.Bytes()
}
// parseClaudeReasoningItemID extracts the Claude response ID and content block
// index from a reasoning item id formatted as rs_<response id>_<block index>
// by the Claude -> Responses translator. Other ids return ok=false.
func parseClaudeReasoningItemID(itemID string) (string, int, bool) {
rest, ok := strings.CutPrefix(itemID, "rs_")
if !ok {
return "", -1, false
}
sep := strings.LastIndexByte(rest, '_')
if sep <= 0 {
return "", -1, false
}
responseID := rest[:sep]
if strings.TrimSpace(responseID) == "" {
return "", -1, false
}
indexStr := rest[sep+1:]
if indexStr == "" {
return "", -1, false
}
for i := 0; i < len(indexStr); i++ {
if indexStr[i] < '0' || indexStr[i] > '9' {
return "", -1, false
}
}
blockIndex, errAtoi := strconv.Atoi(indexStr)
if errAtoi != nil {
return "", -1, false
}
return responseID, blockIndex, true
}
// responsesRedactedThinkingData reports whether encrypted_content carries an
// Anthropic redacted_thinking payload and returns that payload.
func responsesRedactedThinkingData(encryptedContent string) (string, bool) {