forked from MartialBE/one-hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck_json_format.go
93 lines (78 loc) · 2.45 KB
/
check_json_format.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package check_channel
import (
"encoding/json"
"one-api/types"
)
type CheckJsonFormatProcess struct {
ModelName string
}
func CreateCheckJsonFormatProcess(modelName string) *CheckJsonFormatProcess {
return &CheckJsonFormatProcess{
ModelName: modelName,
}
}
func (c *CheckJsonFormatProcess) GetName() string {
return "json格式检测"
}
func (c *CheckJsonFormatProcess) GetRequest() *types.ChatCompletionRequest {
jsonSchema := map[string]interface{}{}
json.Unmarshal([]byte(`{"type":"object","properties":{"steps":{"type":"array","items":{"type":"object","properties":{"explanation":{"type":"string"},"output":{"type":"string"}},"required":["explanation","output"],"additionalProperties":false}},"final_answer":{"type":"string"}},"required":["steps","final_answer"],"additionalProperties":false}`), &jsonSchema)
return &types.ChatCompletionRequest{
Model: c.ModelName,
Messages: []types.ChatCompletionMessage{
{
Role: types.ChatMessageRoleSystem,
Content: "You are a helpful math tutor. Guide the user through the solution step by step.",
},
{
Role: types.ChatMessageRoleUser,
Content: "how can I solve 8x + 7 = -23",
},
},
ResponseFormat: &types.ChatCompletionResponseFormat{
Type: "json_schema",
JsonSchema: &types.FormatJsonSchema{
Name: "math_reasoning",
Schema: jsonSchema,
Strict: true,
},
},
}
}
func (c *CheckJsonFormatProcess) Check(req *types.ChatCompletionRequest, resp *types.ChatCompletionResponse, openaiErr *types.OpenAIError) []*CheckResult {
checkResults := make([]*CheckResult, 0)
if openaiErr != nil {
checkResults = append(checkResults, &CheckResult{
Name: "响应",
Status: CheckStatusFailed,
Remark: openaiErr.Message,
})
return checkResults
}
if len(resp.Choices) == 0 {
checkResults = append(checkResults, &CheckResult{
Name: "结构化判断",
Status: CheckStatusFailed,
Remark: "获取响应数据失败",
})
return checkResults
}
result := &CheckResult{
Name: "结构化判断",
Status: CheckStatusFailed,
Remark: "",
}
firstChoice := resp.Choices[0]
content := firstChoice.Message.StringContent()
var jsonSchema map[string]interface{}
// 判断content是否是json
err := json.Unmarshal([]byte(content), &jsonSchema)
if err != nil {
result.Remark = "返回结果不是json"
} else {
result.Remark = "返回结果是json"
result.Status = CheckStatusSuccess
}
checkResults = append(checkResults, result)
return checkResults
}