|
@@ -6,6 +6,7 @@ import (
|
|
|
"github.com/google/uuid"
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
|
"strconv"
|
|
|
+ "strings"
|
|
|
"time"
|
|
|
"wechat-api/ent/contact"
|
|
|
"wechat-api/ent/contactfield"
|
|
@@ -222,23 +223,10 @@ func (l *CronTask) openaiRequest(messages string, template []custom_types.Contac
|
|
|
if err == nil && resp != nil && len(resp.Choices) > 0 {
|
|
|
logx.Info("resp.Choices: ", resp.Choices[0].Message.Content)
|
|
|
// 尝试第一层解析成 string
|
|
|
- var inner string
|
|
|
- if err := json.Unmarshal([]byte(resp.Choices[0].Message.Content), &inner); err == nil {
|
|
|
- // 成功表示 data 是个被编码过的 JSON 字符串
|
|
|
- resp.Choices[0].Message.Content = inner
|
|
|
- }
|
|
|
- // 解析最终目标
|
|
|
- var items []ResponseItem
|
|
|
- err := json.Unmarshal([]byte(resp.Choices[0].Message.Content), &items)
|
|
|
+ items, err := parseContent(resp.Choices[0].Message.Content)
|
|
|
if err != nil {
|
|
|
return nil, err
|
|
|
}
|
|
|
-
|
|
|
- //var items []ResponseItem
|
|
|
- //err = json.Unmarshal([]byte(resp.Choices[0].Message.Content), &items)
|
|
|
- //if err != nil {
|
|
|
- // return nil, err
|
|
|
- //}
|
|
|
return items, nil
|
|
|
} else if resp != nil && len(resp.Choices) == 0 {
|
|
|
return nil, err
|
|
@@ -447,3 +435,30 @@ func contains(strs []string, target string) bool {
|
|
|
}
|
|
|
return false
|
|
|
}
|
|
|
+
|
|
|
+func parseContent(content string) ([]ResponseItem, error) {
|
|
|
+ content = strings.TrimSpace(content)
|
|
|
+
|
|
|
+ // ① 双引号包裹的再来一次:"{\"dataIndex\":...}"
|
|
|
+ if unq, err := strconv.Unquote(content); err == nil {
|
|
|
+ return parseContent(unq) // 尝试递归
|
|
|
+ }
|
|
|
+
|
|
|
+ // ② 数组形式
|
|
|
+ if strings.HasPrefix(content, "[") {
|
|
|
+ var list []ResponseItem
|
|
|
+ if err := json.Unmarshal([]byte(content), &list); err == nil {
|
|
|
+ return list, nil
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ③ 单对象形式
|
|
|
+ if strings.HasPrefix(content, "{") {
|
|
|
+ var item ResponseItem
|
|
|
+ if err := json.Unmarshal([]byte(content), &item); err == nil {
|
|
|
+ return []ResponseItem{item}, nil
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return nil, fmt.Errorf("unsupported content format: %q", content)
|
|
|
+}
|