fix: initialize contentBlocks with an empty slice and improve content handling in ConvertOpenAIResponseToClaudeNonStream

This commit is contained in:
Luis Pater
2025-10-17 08:47:09 +08:00
parent 3dd0844b98
commit 9cdef937af

View File

@@ -466,7 +466,7 @@ func ConvertOpenAIResponseToClaudeNonStream(_ context.Context, _ string, origina
}, },
} }
var contentBlocks []interface{} contentBlocks := make([]interface{}, 0)
hasToolCall := false hasToolCall := false
if choices := root.Get("choices"); choices.Exists() && choices.IsArray() && len(choices.Array()) > 0 { if choices := root.Get("choices"); choices.Exists() && choices.IsArray() && len(choices.Array()) > 0 {
@@ -477,7 +477,8 @@ func ConvertOpenAIResponseToClaudeNonStream(_ context.Context, _ string, origina
} }
if message := choice.Get("message"); message.Exists() { if message := choice.Get("message"); message.Exists() {
if contentArray := message.Get("content"); contentArray.Exists() && contentArray.IsArray() { if contentResult := message.Get("content"); contentResult.Exists() {
if contentResult.IsArray() {
var textBuilder strings.Builder var textBuilder strings.Builder
var thinkingBuilder strings.Builder var thinkingBuilder strings.Builder
@@ -503,7 +504,7 @@ func ConvertOpenAIResponseToClaudeNonStream(_ context.Context, _ string, origina
thinkingBuilder.Reset() thinkingBuilder.Reset()
} }
for _, item := range contentArray.Array() { for _, item := range contentResult.Array() {
typeStr := item.Get("type").String() typeStr := item.Get("type").String()
switch typeStr { switch typeStr {
case "text": case "text":
@@ -551,6 +552,15 @@ func ConvertOpenAIResponseToClaudeNonStream(_ context.Context, _ string, origina
flushThinking() flushThinking()
flushText() flushText()
} else if contentResult.Type == gjson.String {
textContent := contentResult.String()
if textContent != "" {
contentBlocks = append(contentBlocks, map[string]interface{}{
"type": "text",
"text": textContent,
})
}
}
} }
if toolCalls := message.Get("tool_calls"); toolCalls.Exists() && toolCalls.IsArray() { if toolCalls := message.Get("tool_calls"); toolCalls.Exists() && toolCalls.IsArray() {