forked from tinfoilsh/content-moderator-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
224 lines (187 loc) · 5.75 KB
/
main.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
)
const (
systemPrompt = `You are a content moderator. Analyze the following text and respond with 'safe' if the content is safe, or 'unsafe' followed by the category codes (e.g., 'unsafe\nS1,S2') if any violations are detected.`
modelName = "llama-guard3:1b"
ollamaURL = "http://localhost:11434"
)
type analyzeRequest struct {
Messages []string `json:"messages"`
}
type analysisScores struct {
ThreatOfHarm float64 `json:"threat_of_harm"`
CommercialSolicitation float64 `json:"commercial_solicitation"`
}
type analysisResult struct {
Content string `json:"content"`
Scores analysisScores `json:"scores"`
IsSafe bool `json:"is_safe"`
}
type ollamaRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type ollamaResponse struct {
Message Message `json:"message"`
}
func handleAnalyze(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req analyzeRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
if len(req.Messages) == 0 {
http.Error(w, "Messages array cannot be empty", http.StatusBadRequest)
return
}
results := make([]analysisResult, 0, len(req.Messages))
for _, message := range req.Messages {
result, err := analyzeMessage(r.Context(), message)
if err != nil {
log.Printf("Error analyzing message '%s': %v", message, err)
continue
}
results = append(results, result)
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(results); err != nil {
log.Printf("Error encoding response: %v", err)
}
}
func analyzeMessage(ctx context.Context, message string) (analysisResult, error) {
ollamaReq := ollamaRequest{
Model: modelName,
Messages: []Message{
{Role: "system", Content: systemPrompt},
{Role: "user", Content: message},
},
}
reqBody, err := json.Marshal(ollamaReq)
if err != nil {
return analysisResult{}, fmt.Errorf("marshaling request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, ollamaURL+"/api/chat", bytes.NewReader(reqBody))
if err != nil {
return analysisResult{}, fmt.Errorf("creating request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return analysisResult{}, fmt.Errorf("making request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return analysisResult{}, fmt.Errorf("unexpected status code %d: %s", resp.StatusCode, body)
}
var ollamaResp ollamaResponse
if err := json.NewDecoder(resp.Body).Decode(&ollamaResp); err != nil {
return analysisResult{}, fmt.Errorf("decoding response: %w", err)
}
outputStr := ollamaResp.Message.Content
violations := parseViolations(outputStr)
result := analysisResult{
Content: message,
Scores: calculateScores(violations),
IsSafe: !containsUnsafe(outputStr),
}
log.Printf("Analysis Result - Safe: %v, Threat Score: %.1f, Commercial Score: %.1f",
result.IsSafe,
result.Scores.ThreatOfHarm,
result.Scores.CommercialSolicitation)
return result, nil
}
func parseViolations(output string) []string {
parts := strings.Split(output, "\n")
if len(parts) <= 1 {
return nil
}
return strings.Split(strings.TrimSpace(parts[1]), ",")
}
func calculateScores(violations []string) analysisScores {
var scores analysisScores
for _, v := range violations {
switch strings.TrimSpace(v) {
case "S1":
scores.ThreatOfHarm = 1.0
case "S2", "S8":
scores.CommercialSolicitation = 1.0
}
}
return scores
}
func containsUnsafe(output string) bool {
return strings.Contains(strings.ToLower(output), "unsafe")
}
func corsMiddleware(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next(w, r)
}
}
func handleOllamaHealth(w http.ResponseWriter, r *http.Request) {
req, err := http.NewRequestWithContext(r.Context(), http.MethodGet, ollamaURL+"/api/version", nil)
if err != nil {
http.Error(w, fmt.Sprintf("creating version request: %v", err), http.StatusServiceUnavailable)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("connecting to Ollama: %v", err), http.StatusServiceUnavailable)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
http.Error(w, fmt.Sprintf("unexpected version status code %d: %s", resp.StatusCode, body), http.StatusBadGateway)
return
}
w.Write([]byte("ollama: "))
// Forward the version response to the client
if _, err := io.Copy(w, resp.Body); err != nil {
log.Printf("Error copying response: %v", err)
}
}
func main() {
mux := http.NewServeMux()
// Health check endpoint
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Content moderation service is running"))
})
mux.HandleFunc("/api/health", corsMiddleware(handleOllamaHealth))
// Analysis endpoint
mux.HandleFunc("/api/analyze", corsMiddleware(handleAnalyze))
port := os.Getenv("PORT")
if port == "" {
port = "80"
}
addr := ":" + port
log.Printf("Server starting on %s", addr)
if err := http.ListenAndServe(addr, mux); err != nil {
log.Fatal(err)
}
}