|
@@ -41,6 +41,27 @@ func (r *ChatResult) GetContentString() (string, error) {
|
|
|
return content, err
|
|
|
}
|
|
|
|
|
|
+func (r *ChatResult) GetContentJsonStr() (string, error) {
|
|
|
+ var (
|
|
|
+ content string = ""
|
|
|
+ err error
|
|
|
+ )
|
|
|
+ if r.err == nil && len(r.Choices) > 0 {
|
|
|
+ content = r.Choices[0].Message.Content
|
|
|
+ } else if r.err == nil && len(r.Choices) == 0 {
|
|
|
+ err = errors.New("choices empty")
|
|
|
+ }
|
|
|
+ if !IsOpenaiModel(r.Model) { //不支持Response Schema的要特殊处理一下
|
|
|
+ var isJsonContent bool
|
|
|
+ content, isJsonContent = ExtractJSONContent(content)
|
|
|
+ if !isJsonContent {
|
|
|
+ return "", errors.New("invalid json content")
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return content, err
|
|
|
+}
|
|
|
+
|
|
|
// ParseContentAs 解析 Message Content 中的 JSON 到指定的 Go 结构体
|
|
|
// target 必须是一个指向目标结构体实例的指针 (e.g., &MyStruct{})
|
|
|
func (r *ChatResult) ParseContentAs(target any) error {
|
|
@@ -58,13 +79,7 @@ func (r *ChatResult) ParseContentAs(target any) error {
|
|
|
return errors.New("invalid json content")
|
|
|
}
|
|
|
}
|
|
|
- err = json.Unmarshal([]byte(content), target)
|
|
|
- if err != nil {
|
|
|
- return fmt.Errorf("parseContent err: failed to unmarshal content JSON "+
|
|
|
- "into target type '%w'", err)
|
|
|
- }
|
|
|
-
|
|
|
- return nil
|
|
|
+ return ParseContentAs(content, target, false)
|
|
|
}
|
|
|
|
|
|
func AnyToBytes(in any) ([]byte, error) {
|
|
@@ -162,9 +177,10 @@ func WrapJSON(input any, warpKey string, checkValid bool) ([]byte, error) {
|
|
|
return outputBytes, nil
|
|
|
}
|
|
|
|
|
|
-func ParseContentAs(content string, target any) error {
|
|
|
- // 清理可能的 Markdown ```json ``` 包装
|
|
|
- if strings.HasPrefix(content, "```json") && strings.HasSuffix(content, "```") {
|
|
|
+func ParseContentAs(content string, target any, removeJsonBlock bool) error {
|
|
|
+
|
|
|
+ if removeJsonBlock &&
|
|
|
+ strings.HasPrefix(content, "```json") && strings.HasSuffix(content, "```") {
|
|
|
content = strings.TrimSuffix(strings.TrimPrefix(content, "```json"), "```")
|
|
|
content = strings.TrimSpace(content)
|
|
|
}
|