-
Notifications
You must be signed in to change notification settings - Fork 59
/
custom.go
69 lines (58 loc) · 1.65 KB
/
custom.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
package custompolicy
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/sashabaranov/go-openai"
goopenai "github.com/sashabaranov/go-openai"
)
type OpenAiDetector struct {
client *goopenai.Client
rt time.Duration
}
func NewOpenAiDetector(rt time.Duration, key string) *OpenAiDetector {
return &OpenAiDetector{
client: goopenai.NewClient(key),
rt: rt,
}
}
type result struct {
RelevantTextsFound bool `json:"relevant_texts_found"`
}
func (c *OpenAiDetector) Detect(input []string, requirements []string) (bool, error) {
requirement := strings.Join(requirements, ",")
resp, err := c.client.CreateChatCompletion(
context.Background(),
openai.ChatCompletionRequest{
Model: openai.GPT4Turbo0125,
Messages: []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
Content: "You are a text classifier. You take in an array of strings and ouput JSON with one field called relevant_texts_found. relevant_texts_found is a boolean field that indicates whether or not the given text contains: " + requirement,
},
{
Role: openai.ChatMessageRoleUser,
Content: fmt.Sprintf("this is the input [%s]", strings.Join(input, " ,")),
},
},
ResponseFormat: &goopenai.ChatCompletionResponseFormat{
Type: goopenai.ChatCompletionResponseFormatTypeJSONObject,
},
},
)
if err != nil {
return false, err
}
if len(resp.Choices) == 1 {
r := &result{}
err = json.Unmarshal([]byte(resp.Choices[0].Message.Content), r)
if err != nil {
return false, err
}
return r.RelevantTextsFound, nil
}
return false, errors.New("there are no choices from OpenAI")
}