-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
576 lines (519 loc) · 17.6 KB
/
client.go
File metadata and controls
576 lines (519 loc) · 17.6 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
// Package moderyo provides a Go SDK for the Moderyo Content Moderation API.
//
// Endpoint: POST /v1/moderation
// Field: input (string or []string)
// 27 categories, simplified scores, policy decision, detected phrases, long-text analysis.
package moderyo
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const (
Version = "2.0.7"
DefaultBaseURL = "https://api.moderyo.com"
DefaultTimeout = 30 * time.Second
)
// AllCategories contains all 27 moderation categories.
var AllCategories = []string{
// Standard (11)
"hate", "hate/threatening",
"harassment", "harassment/threatening",
"self-harm", "self-harm/intent", "self-harm/instructions",
"sexual", "sexual/minors",
"violence", "violence/graphic",
// Safety: Self-Harm (4)
"self_harm_ideation", "self_harm_intent", "self_harm_instruction", "self_harm_support",
// Safety: Violence (4)
"violence_general", "violence_severe", "violence_instruction", "violence_glorification",
// Safety: Child Protection (4)
"child_sexual_content", "minor_sexualization", "child_grooming", "age_mention_risk",
// Safety: Extremism (4)
"extremism_violence_call", "extremism_propaganda", "extremism_support", "extremism_symbol_reference",
}
// =============================================================================
// Types
// =============================================================================
// ModerationRequest contains the request body fields.
type ModerationRequest struct {
Input string `json:"input"`
Model string `json:"model,omitempty"`
LongTextMode *bool `json:"long_text_mode,omitempty"`
LongTextThreshold *int `json:"long_text_threshold,omitempty"`
SkipProfanity *bool `json:"skip_profanity,omitempty"`
SkipThreat *bool `json:"skip_threat,omitempty"`
SkipMaskedWord *bool `json:"skip_masked_word,omitempty"`
}
// ModerationOptions contains header-level options (X-Moderyo-*).
type ModerationOptions struct {
Mode string // "enforce" or "shadow"
Risk string // "conservative", "balanced", "aggressive"
Debug bool
PlayerID string
}
// Categories holds boolean flags for all 27 categories.
type Categories map[string]bool
// GetTriggered returns a list of categories that are true.
func (c Categories) GetTriggered() []string {
var triggered []string
for _, cat := range AllCategories {
if c[cat] {
triggered = append(triggered, cat)
}
}
return triggered
}
// CategoryScores holds 0-1 scores for all 27 categories.
type CategoryScores map[string]float64
// GetHighest returns the category with the highest score.
func (s CategoryScores) GetHighest() (string, float64) {
var maxCat string
var maxScore float64
for cat, score := range s {
if score > maxScore {
maxCat = cat
maxScore = score
}
}
return maxCat, maxScore
}
// Above returns categories with a score above threshold.
func (s CategoryScores) Above(threshold float64) map[string]float64 {
result := make(map[string]float64)
for cat, score := range s {
if score > threshold {
result[cat] = score
}
}
return result
}
// SimplifiedScores holds policy-boosted aggregate scores.
type SimplifiedScores struct {
Toxicity float64 `json:"toxicity"`
Hate float64 `json:"hate"`
Harassment float64 `json:"harassment"`
Scam float64 `json:"scam"`
Violence float64 `json:"violence"`
Fraud float64 `json:"fraud"`
}
// TriggeredRule details about the rule that fired.
type TriggeredRule struct {
ID string `json:"id"`
Type string `json:"type"`
Category string `json:"category"`
Threshold float64 `json:"threshold"`
ActualValue float64 `json:"actual_value"`
Matched bool `json:"matched"`
}
// Highlight is a text span highlighted by the engine.
type Highlight struct {
Text string `json:"text"`
Category string `json:"category"`
StartIndex int `json:"start_index"`
EndIndex int `json:"end_index"`
}
// PolicyDecision is the full policy engine output.
type PolicyDecision struct {
Decision string `json:"decision"`
RuleID string `json:"rule_id"`
RuleName string `json:"rule_name"`
Reason string `json:"reason"`
Confidence float64 `json:"confidence"`
Severity string `json:"severity"`
TriggeredRule *TriggeredRule `json:"triggered_rule,omitempty"`
Highlights []Highlight `json:"highlights,omitempty"`
}
// DetectedPhrase is a detected phrase with label.
type DetectedPhrase struct {
Text string `json:"text"`
Label string `json:"label"`
}
// SentenceAnalysis is a per-sentence analysis result.
type SentenceAnalysis struct {
Index int `json:"index"`
Text string `json:"text"`
Start int `json:"start"`
End int `json:"end"`
CharCount int `json:"char_count"`
Toxicity float64 `json:"toxicity"`
Decision string `json:"decision"`
}
// LongTextHighlight is a long-text highlight.
type LongTextHighlight struct {
Text string `json:"text"`
Start int `json:"start"`
End int `json:"end"`
Score float64 `json:"score"`
Source string `json:"source"`
Basis string `json:"basis"`
}
// ProcessingInfo contains processing metadata for long-text analysis.
type ProcessingInfo struct {
Mode string `json:"mode"`
OriginalCharCount int `json:"original_char_count"`
ProcessedCharCount int `json:"processed_char_count"`
OriginalSentenceCount int `json:"original_sentence_count"`
FinalSentenceCount int `json:"final_sentence_count"`
Truncated bool `json:"truncated"`
TruncationReason string `json:"truncation_reason,omitempty"`
InferenceTimeMs int `json:"inference_time_ms"`
}
// LongTextAnalysis contains the full long-text analysis result.
type LongTextAnalysis struct {
OverallToxicity float64 `json:"overall_toxicity"`
MaxToxicity float64 `json:"max_toxicity"`
Top3MeanToxicity float64 `json:"top3_mean_toxicity"`
DecisionConfidence float64 `json:"decision_confidence"`
SignalConfidence float64 `json:"signal_confidence"`
Sentences []SentenceAnalysis `json:"sentences"`
Highlights []LongTextHighlight `json:"highlights"`
Processing ProcessingInfo `json:"processing"`
}
// ModerationResult is the full moderation response.
type ModerationResult struct {
ID string `json:"id"`
Model string `json:"model"`
Flagged bool `json:"flagged"`
Action string `json:"action"`
Categories Categories `json:"categories"`
CategoryScores CategoryScores `json:"category_scores"`
Scores SimplifiedScores `json:"scores"`
PolicyDecision *PolicyDecision `json:"policy_decision,omitempty"`
DetectedPhrases []DetectedPhrase `json:"detected_phrases,omitempty"`
Mode string `json:"mode,omitempty"`
Risk string `json:"risk,omitempty"`
SafetyScore *int `json:"safety_score,omitempty"`
LongTextAnalysis *LongTextAnalysis `json:"long_text_analysis,omitempty"`
AbuseSignals map[string]interface{} `json:"abuse_signals,omitempty"`
ShadowDecision map[string]interface{} `json:"shadow_decision,omitempty"`
}
// IsBlocked returns true if the action is "block".
func (r *ModerationResult) IsBlocked() bool { return r.Action == "block" }
// IsFlagged returns true if the action is "flag" or flagged is true.
func (r *ModerationResult) IsFlagged() bool { return r.Action == "flag" || r.Flagged }
// IsAllowed returns true if content is allowed and not flagged.
func (r *ModerationResult) IsAllowed() bool { return r.Action == "allow" && !r.Flagged }
// BatchResult contains batch moderation results.
type BatchResult struct {
Results []ModerationResult
Total int
FlaggedCount int
BlockedCount int
}
// =============================================================================
// Client
// =============================================================================
// ClientOption configures the client.
type ClientOption func(*Client)
// Client is the Moderyo API client.
type Client struct {
apiKey string
baseURL string
httpClient *http.Client
maxRetries int
}
// WithBaseURL sets the base URL.
func WithBaseURL(url string) ClientOption {
return func(c *Client) { c.baseURL = strings.TrimRight(url, "/") }
}
// WithTimeout sets the HTTP timeout.
func WithTimeout(d time.Duration) ClientOption {
return func(c *Client) { c.httpClient.Timeout = d }
}
// WithMaxRetries sets max retry attempts.
func WithMaxRetries(n int) ClientOption {
return func(c *Client) { c.maxRetries = n }
}
// WithHTTPClient sets a custom HTTP client.
func WithHTTPClient(hc *http.Client) ClientOption {
return func(c *Client) { c.httpClient = hc }
}
// NewClient creates a new Moderyo client.
func NewClient(apiKey string, opts ...ClientOption) *Client {
c := &Client{
apiKey: apiKey,
baseURL: DefaultBaseURL,
httpClient: &http.Client{Timeout: DefaultTimeout},
maxRetries: 2,
}
for _, opt := range opts {
opt(c)
}
return c
}
// NewClientFromEnv creates a client using MODERYO_API_KEY env var.
func NewClientFromEnv(opts ...ClientOption) (*Client, error) {
key := os.Getenv("MODERYO_API_KEY")
if key == "" {
return nil, &AuthenticationError{Message: "MODERYO_API_KEY environment variable not set"}
}
return NewClient(key, opts...), nil
}
// =============================================================================
// Public Methods
// =============================================================================
// Moderate sends a simple text moderation request.
func (c *Client) Moderate(ctx context.Context, input string) (*ModerationResult, error) {
return c.ModerateWithOptions(ctx, &ModerationRequest{Input: input}, nil)
}
// ModerateWithOptions sends a moderation request with full configuration.
func (c *Client) ModerateWithOptions(ctx context.Context, req *ModerationRequest, opts *ModerationOptions) (*ModerationResult, error) {
if req.Model == "" {
req.Model = "omni-moderation-latest"
}
body, err := json.Marshal(req)
if err != nil {
return nil, &ValidationError{Message: fmt.Sprintf("failed to marshal request: %v", err)}
}
headers := c.buildHeaders(opts)
respBody, err := c.doWithRetry(ctx, http.MethodPost, "/v1/moderation", body, headers)
if err != nil {
return nil, err
}
return transformResponse(respBody)
}
// ModerateBatch moderates multiple texts and returns a BatchResult.
func (c *Client) ModerateBatch(ctx context.Context, texts []string, opts *ModerationOptions) (*BatchResult, error) {
results := make([]ModerationResult, 0, len(texts))
for _, text := range texts {
r, err := c.ModerateWithOptions(ctx, &ModerationRequest{Input: text}, opts)
if err != nil {
return nil, err
}
results = append(results, *r)
}
flagged, blocked := 0, 0
for _, r := range results {
if r.Flagged {
flagged++
}
if r.IsBlocked() {
blocked++
}
}
return &BatchResult{
Results: results,
Total: len(results),
FlaggedCount: flagged,
BlockedCount: blocked,
}, nil
}
// HealthCheck checks API health.
func (c *Client) HealthCheck(ctx context.Context) (bool, error) {
_, err := c.doWithRetry(ctx, http.MethodGet, "/health", nil, nil)
return err == nil, err
}
// =============================================================================
// Internal: headers
// =============================================================================
func (c *Client) buildHeaders(opts *ModerationOptions) map[string]string {
headers := map[string]string{
"Authorization": "Bearer " + c.apiKey,
"Content-Type": "application/json",
"User-Agent": "moderyo-go/" + Version,
}
if opts == nil {
return headers
}
if opts.Mode != "" {
headers["X-Moderyo-Mode"] = opts.Mode
}
if opts.Risk != "" {
headers["X-Moderyo-Risk"] = opts.Risk
}
if opts.Debug {
headers["X-Moderyo-Debug"] = "true"
}
if opts.PlayerID != "" {
headers["X-Moderyo-Player-Id"] = opts.PlayerID
}
return headers
}
// =============================================================================
// Internal: HTTP with retry
// =============================================================================
func (c *Client) doWithRetry(ctx context.Context, method, path string, body []byte, headers map[string]string) ([]byte, error) {
url := c.baseURL + path
var lastErr error
for attempt := 0; attempt <= c.maxRetries; attempt++ {
var bodyReader io.Reader
if body != nil {
bodyReader = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
if err != nil {
return nil, &NetworkError{Message: fmt.Sprintf("failed to create request: %v", err), Cause: err}
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := c.httpClient.Do(req)
if err != nil {
lastErr = err
if attempt < c.maxRetries {
time.Sleep(time.Duration(math.Pow(2, float64(attempt))) * time.Second)
continue
}
isTimeout := os.IsTimeout(err)
return nil, &NetworkError{Message: err.Error(), IsTimeout: isTimeout, Cause: err}
}
respBody, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode >= 400 {
// Retry on 429 / 5xx
if attempt < c.maxRetries && (resp.StatusCode == 429 || resp.StatusCode >= 500) {
wait := time.Duration(math.Pow(2, float64(attempt))) * time.Second
if ra := resp.Header.Get("Retry-After"); ra != "" {
if secs, err := strconv.Atoi(ra); err == nil {
wait = time.Duration(secs) * time.Second
}
}
time.Sleep(wait)
continue
}
return nil, handleErrorResponse(resp.StatusCode, respBody, resp.Header)
}
return respBody, nil
}
return nil, &NetworkError{Message: "request failed after retries", Cause: lastErr}
}
// =============================================================================
// Internal: error handling
// =============================================================================
func handleErrorResponse(status int, body []byte, headers http.Header) error {
var errResp struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
message := string(body)
if json.Unmarshal(body, &errResp) == nil && errResp.Error.Message != "" {
message = errResp.Error.Message
}
requestID := headers.Get("X-Request-Id")
switch status {
case 401:
return &AuthenticationError{Message: message, RequestID: requestID}
case 402:
return &QuotaExceededError{Message: message, RequestID: requestID}
case 429:
retryAfter := 60.0
if ra := headers.Get("Retry-After"); ra != "" {
if secs, err := strconv.ParseFloat(ra, 64); err == nil {
retryAfter = secs
}
}
limit, _ := strconv.Atoi(headers.Get("X-RateLimit-Limit"))
remaining, _ := strconv.Atoi(headers.Get("X-RateLimit-Remaining"))
return &RateLimitError{
Message: message,
RetryAfter: retryAfter,
Limit: limit,
Remaining: remaining,
RequestID: requestID,
}
case 400, 422:
return &ValidationError{Message: message, RequestID: requestID}
default:
return &APIError{Code: "API_ERROR", Message: message, StatusCode: status, RequestID: requestID}
}
}
// =============================================================================
// Internal: response transformation
// =============================================================================
func transformResponse(data []byte) (*ModerationResult, error) {
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
return nil, &ValidationError{Message: fmt.Sprintf("failed to parse response: %v", err)}
}
result := &ModerationResult{
Categories: make(Categories),
CategoryScores: make(CategoryScores),
Action: "allow",
}
// id, model
if v, ok := raw["id"]; ok {
json.Unmarshal(v, &result.ID)
}
if v, ok := raw["model"]; ok {
json.Unmarshal(v, &result.Model)
}
// results[0]
if v, ok := raw["results"]; ok {
var results []map[string]json.RawMessage
if json.Unmarshal(v, &results) == nil && len(results) > 0 {
r0 := results[0]
if fl, ok := r0["flagged"]; ok {
json.Unmarshal(fl, &result.Flagged)
}
if cats, ok := r0["categories"]; ok {
json.Unmarshal(cats, &result.Categories)
}
if scores, ok := r0["category_scores"]; ok {
json.Unmarshal(scores, &result.CategoryScores)
}
}
}
// Fill defaults for missing categories
for _, cat := range AllCategories {
if _, ok := result.Categories[cat]; !ok {
result.Categories[cat] = false
}
if _, ok := result.CategoryScores[cat]; !ok {
result.CategoryScores[cat] = 0
}
}
// Simplified scores
if v, ok := raw["scores"]; ok {
json.Unmarshal(v, &result.Scores)
}
// Policy decision
if v, ok := raw["policy_decision"]; ok {
var pd PolicyDecision
if json.Unmarshal(v, &pd) == nil {
result.PolicyDecision = &pd
result.Action = strings.ToLower(pd.Decision)
}
} else if result.Flagged {
result.Action = "flag"
}
// Detected phrases
if v, ok := raw["detected_phrases"]; ok {
json.Unmarshal(v, &result.DetectedPhrases)
}
// Long-text analysis
if v, ok := raw["long_text_analysis"]; ok {
var lta LongTextAnalysis
if json.Unmarshal(v, <a) == nil {
result.LongTextAnalysis = <a
}
}
// Metadata
if v, ok := raw["mode"]; ok {
json.Unmarshal(v, &result.Mode)
}
if v, ok := raw["risk"]; ok {
json.Unmarshal(v, &result.Risk)
}
if v, ok := raw["safety_score"]; ok {
var ss int
if json.Unmarshal(v, &ss) == nil {
result.SafetyScore = &ss
}
}
if v, ok := raw["abuse_signals"]; ok {
json.Unmarshal(v, &result.AbuseSignals)
}
if v, ok := raw["shadow_decision"]; ok {
json.Unmarshal(v, &result.ShadowDecision)
}
return result, nil
}