refactor: Modularize OpenAI message normalization and prompt building, enhancing MessagesPrepare to support additional content types and tool call formatting.

This commit is contained in:
CJACK
2026-02-18 00:54:54 +08:00
parent 89e93a1674
commit 19289c9008
8 changed files with 449 additions and 25 deletions

View File

@@ -1,6 +1,8 @@
package util
import (
"encoding/json"
"fmt"
"regexp"
"strings"
@@ -68,15 +70,25 @@ func normalizeContent(v any) string {
if !ok {
continue
}
if m["type"] == "text" {
typeStr, _ := m["type"].(string)
typeStr = strings.ToLower(strings.TrimSpace(typeStr))
if typeStr == "text" || typeStr == "output_text" || typeStr == "input_text" {
if txt, ok := m["text"].(string); ok {
parts = append(parts, txt)
continue
}
if txt, ok := m["content"].(string); ok {
parts = append(parts, txt)
}
}
}
return strings.Join(parts, "\n")
default:
return ""
b, err := json.Marshal(v)
if err != nil {
return fmt.Sprintf("%v", v)
}
return string(b)
}
}

View File

@@ -33,6 +33,33 @@ func TestMessagesPrepareRoles(t *testing.T) {
}
}
func TestMessagesPrepareObjectContent(t *testing.T) {
messages := []map[string]any{
{"role": "user", "content": map[string]any{"temp": 18, "ok": true}},
}
got := MessagesPrepare(messages)
if !contains(got, `"temp":18`) || !contains(got, `"ok":true`) {
t.Fatalf("expected serialized object content, got %q", got)
}
}
func TestMessagesPrepareArrayTextVariants(t *testing.T) {
messages := []map[string]any{
{
"role": "user",
"content": []any{
map[string]any{"type": "output_text", "text": "line1"},
map[string]any{"type": "input_text", "text": "line2"},
map[string]any{"type": "image_url", "image_url": "https://example.com/a.png"},
},
},
}
got := MessagesPrepare(messages)
if got != "line1\nline2" {
t.Fatalf("unexpected content from text variants: %q", got)
}
}
func TestConvertClaudeToDeepSeek(t *testing.T) {
store := config.LoadStore()
req := map[string]any{