Files
prompts-core/common/util/mapping.go

100 lines
2.3 KiB
Go

package util
import (
"strings"
"github.com/gogf/gf/v2/encoding/gjson"
)
// ReverseMap 映射 payload 到 mapping
func ReverseMap(mapping map[string]any, payload map[string]any) map[string]any {
jsonObj := gjson.New("{}")
for path, defaultValue := range mapping {
val := gjson.New(payload).Get(path)
if !val.IsNil() {
_ = jsonObj.Set(path, val.Val())
} else if defaultValue != nil {
_ = jsonObj.Set(path, defaultValue)
}
}
return jsonObj.Map()
}
// ExtractUserText 从 messages map 中提取用户文本,返回标准的 user message 结构
func ExtractUserText(messages map[string]any) map[string]any {
var texts []string
// 1) rounds 结构:遍历每轮
if rounds, ok := messages["rounds"].([]any); ok {
for _, round := range rounds {
if rm, ok := round.(map[string]any); ok {
if msgs, ok := rm["messages"].([]any); ok {
texts = append(texts, extractTextFromRoleUser(msgs)...)
}
}
}
} else if msgs, ok := messages["messages"].([]any); ok {
// 2) messages 结构
texts = extractTextFromRoleUser(msgs)
}
// 3) 构建返回结构
return map[string]any{
"role": "user",
"content": strings.Join(texts, "\n"),
}
}
// extractTextFromRoleUser 从 messages 数组中提取所有 role=user 的文本
func extractTextFromRoleUser(msgs []any) []string {
var texts []string
for _, msg := range msgs {
m, ok := msg.(map[string]any)
if !ok {
continue
}
if role, _ := m["role"].(string); role != "user" {
continue
}
texts = append(texts, extractAllText(m["content"])...)
}
return texts
}
// extractAllText 从 content 中提取所有文本(递归,最大兼容)
func extractAllText(content any) []string {
switch c := content.(type) {
case string:
return []string{c}
case []any:
var texts []string
for _, item := range c {
m, ok := item.(map[string]any)
if !ok {
continue
}
if t, ok := m["text"].(string); ok && t != "" {
texts = append(texts, t)
continue
}
for _, v := range m {
texts = append(texts, extractAllText(v)...)
}
}
return texts
case map[string]any:
if t, ok := c["text"].(string); ok && t != "" {
return []string{t}
}
var texts []string
for _, v := range c {
texts = append(texts, extractAllText(v)...)
}
return texts
}
return nil
}