-
Notifications
You must be signed in to change notification settings - Fork 0
/
moderation.go
65 lines (61 loc) · 1.54 KB
/
moderation.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
package groq
import (
"context"
"net/http"
"strings"
"github.com/conneroisu/groq-go/pkg/builders"
"github.com/conneroisu/groq-go/pkg/models"
"github.com/conneroisu/groq-go/pkg/moderation"
)
type (
// Moderation represents the response of a moderation request.
Moderation struct {
// Categories is the categories of the result.
Categories []moderation.HarmfulCategory `json:"categories"`
// Flagged is the flagged status of the result.
Flagged bool `json:"flagged"`
}
)
// Moderate performs a moderation api call over a string.
// Input can be an array or slice but a string will reduce the complexity.
func (c *Client) Moderate(
ctx context.Context,
messages []ChatCompletionMessage,
model models.ModerationModel,
) (response Moderation, err error) {
req, err := builders.NewRequest(
ctx,
c.header,
http.MethodPost,
c.fullURL(chatCompletionsSuffix, withModel(model)),
builders.WithBody(&struct {
Messages []ChatCompletionMessage `json:"messages"`
Model models.ModerationModel `json:"model,omitempty"`
}{
Messages: messages,
Model: model,
}),
)
if err != nil {
return
}
var resp ChatCompletionResponse
err = c.sendRequest(req, &resp)
if err != nil {
return
}
if strings.Contains(resp.Choices[0].Message.Content, "unsafe") {
response.Flagged = true
split := strings.Split(
strings.Split(resp.Choices[0].Message.Content, "\n")[1],
",",
)
for _, s := range split {
response.Categories = append(
response.Categories,
moderation.SectionMap[strings.TrimSpace(s)],
)
}
}
return
}