58 lines
1.3 KiB
Go
58 lines
1.3 KiB
Go
package util
|
|
|
|
import (
|
|
"strings"
|
|
|
|
"github.com/gogf/gf/v2/encoding/gjson"
|
|
"github.com/gogf/gf/v2/util/gconv"
|
|
)
|
|
|
|
// 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 中提取所有 user 文本
|
|
func ExtractUserText(messages map[string]any) map[string]any {
|
|
msgJson := gjson.New(messages)
|
|
|
|
msgs := msgJson.Get("rounds.0.messages")
|
|
if msgs.IsNil() {
|
|
msgs = msgJson.Get("messages")
|
|
}
|
|
var texts []string
|
|
for _, m := range msgs.Array() {
|
|
msg := gjson.New(m)
|
|
if msg.Get("role").String() != "user" {
|
|
continue
|
|
}
|
|
content := msg.Get("content").Val()
|
|
switch c := content.(type) {
|
|
case string:
|
|
texts = append(texts, c)
|
|
case []any:
|
|
for _, item := range c {
|
|
if m, ok := item.(map[string]any); ok {
|
|
if t := gconv.String(m["text"]); t != "" {
|
|
texts = append(texts, t)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return map[string]any{
|
|
"role": "user",
|
|
"content": strings.Join(texts, "\n"),
|
|
}
|
|
}
|