|
| 1 | +package openai |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "math" |
| 8 | + "net/http" |
| 9 | + "strings" |
| 10 | + |
| 11 | + "github.com/google/uuid" |
| 12 | + "github.com/labstack/echo/v4" |
| 13 | + "github.com/mudler/LocalAI/core/backend" |
| 14 | + "github.com/mudler/LocalAI/core/config" |
| 15 | + "github.com/mudler/LocalAI/core/http/middleware" |
| 16 | + "github.com/mudler/LocalAI/core/schema" |
| 17 | + "github.com/mudler/LocalAI/core/templates" |
| 18 | + "github.com/mudler/LocalAI/pkg/functions" |
| 19 | + "github.com/mudler/LocalAI/pkg/model" |
| 20 | +) |
| 21 | + |
| 22 | +var moderationCategories = []string{ |
| 23 | + "harassment", |
| 24 | + "harassment/threatening", |
| 25 | + "hate", |
| 26 | + "hate/threatening", |
| 27 | + "illicit", |
| 28 | + "illicit/violent", |
| 29 | + "self-harm", |
| 30 | + "self-harm/intent", |
| 31 | + "self-harm/instructions", |
| 32 | + "sexual", |
| 33 | + "sexual/minors", |
| 34 | + "violence", |
| 35 | + "violence/graphic", |
| 36 | +} |
| 37 | + |
| 38 | +type moderationGenerator func(context.Context, string, *config.ModelConfig) (string, backend.TokenUsage, error) |
| 39 | + |
| 40 | +type generatedModeration struct { |
| 41 | + Categories map[string]bool `json:"categories"` |
| 42 | + CategoryScores map[string]float64 `json:"category_scores"` |
| 43 | +} |
| 44 | + |
| 45 | +// ModerationEndpoint implements the text input subset of OpenAI's moderation |
| 46 | +// API using any LocalAI completion model and constrained JSON generation. |
| 47 | +// @Summary Classify text for potentially harmful content. |
| 48 | +// @Tags moderation |
| 49 | +// @Param request body schema.ModerationRequest true "query params" |
| 50 | +// @Success 200 {object} schema.ModerationResponse "Response" |
| 51 | +// @Router /v1/moderations [post] |
| 52 | +func ModerationEndpoint(cl *config.ModelConfigLoader, ml *model.ModelLoader, evaluator *templates.Evaluator, appConfig *config.ApplicationConfig) echo.HandlerFunc { |
| 53 | + return moderationEndpoint(func(ctx context.Context, input string, cfg *config.ModelConfig) (string, backend.TokenUsage, error) { |
| 54 | + prompt := moderationPrompt(input) |
| 55 | + var messages schema.Messages |
| 56 | + if cfg.TemplateConfig.UseTokenizerTemplate { |
| 57 | + messages = schema.Messages{{Role: "user", Content: prompt}} |
| 58 | + prompt = "" |
| 59 | + } else if evaluator != nil { |
| 60 | + if rendered, err := evaluator.EvaluateTemplateForPrompt(templates.CompletionPromptTemplate, *cfg, templates.PromptTemplateData{Input: prompt, SystemPrompt: cfg.SystemPrompt}); err == nil { |
| 61 | + prompt = rendered |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + predict, err := backend.ModelInferenceFunc(ctx, prompt, messages, nil, nil, nil, ml, cfg, cl, appConfig, nil, "", "", nil, nil, nil, nil) |
| 66 | + if err != nil { |
| 67 | + return "", backend.TokenUsage{}, err |
| 68 | + } |
| 69 | + response, err := predict() |
| 70 | + return response.Response, response.Usage, err |
| 71 | + }) |
| 72 | +} |
| 73 | + |
| 74 | +func moderationEndpoint(generate moderationGenerator) echo.HandlerFunc { |
| 75 | + return func(c echo.Context) error { |
| 76 | + input, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_LOCALAI_REQUEST).(*schema.ModerationRequest) |
| 77 | + if !ok || input == nil { |
| 78 | + return echo.NewHTTPError(http.StatusBadRequest, "invalid moderation request") |
| 79 | + } |
| 80 | + if len(input.Input) == 0 { |
| 81 | + return echo.NewHTTPError(http.StatusBadRequest, "input must contain at least one text string") |
| 82 | + } |
| 83 | + if generate == nil { |
| 84 | + return echo.NewHTTPError(http.StatusInternalServerError, "moderation generator is unavailable") |
| 85 | + } |
| 86 | + |
| 87 | + modelConfig, ok := c.Get(middleware.CONTEXT_LOCALS_KEY_MODEL_CONFIG).(*config.ModelConfig) |
| 88 | + if !ok || modelConfig == nil { |
| 89 | + return echo.NewHTTPError(http.StatusBadRequest, "moderation model configuration is unavailable") |
| 90 | + } |
| 91 | + |
| 92 | + grammar, err := moderationGrammar() |
| 93 | + if err != nil { |
| 94 | + return echo.NewHTTPError(http.StatusInternalServerError, "failed to build moderation grammar").SetInternal(err) |
| 95 | + } |
| 96 | + cfg := *modelConfig |
| 97 | + cfg.Grammar = grammar |
| 98 | + maxTokens := 512 |
| 99 | + cfg.Maxtokens = &maxTokens |
| 100 | + |
| 101 | + results := make([]schema.ModerationResult, 0, len(input.Input)) |
| 102 | + promptTokens, completionTokens := 0, 0 |
| 103 | + for _, text := range input.Input { |
| 104 | + if strings.TrimSpace(text) == "" { |
| 105 | + return echo.NewHTTPError(http.StatusBadRequest, "input strings must not be empty") |
| 106 | + } |
| 107 | + raw, usage, err := generate(c.Request().Context(), text, &cfg) |
| 108 | + if err != nil { |
| 109 | + return echo.NewHTTPError(http.StatusInternalServerError, "moderation inference failed").SetInternal(err) |
| 110 | + } |
| 111 | + result, err := parseModerationResult(raw) |
| 112 | + if err != nil { |
| 113 | + return echo.NewHTTPError(http.StatusInternalServerError, "invalid moderation result: "+err.Error()).SetInternal(err) |
| 114 | + } |
| 115 | + results = append(results, result) |
| 116 | + promptTokens += usage.Prompt |
| 117 | + completionTokens += usage.Completion |
| 118 | + } |
| 119 | + |
| 120 | + middleware.StampUsage(c, input.Model, promptTokens, completionTokens) |
| 121 | + return c.JSON(http.StatusOK, schema.ModerationResponse{ |
| 122 | + ID: "modr-" + uuid.NewString(), |
| 123 | + Model: input.Model, |
| 124 | + Results: results, |
| 125 | + }) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +func moderationPrompt(input string) string { |
| 130 | + encoded, _ := json.Marshal(input) |
| 131 | + return `Classify the supplied text for safety moderation. Return only the JSON object required by the grammar. |
| 132 | +For each category, set the boolean to true only when the text matches that category. Give each category a confidence score from 0 to 1. |
| 133 | +The categories are harassment, harassment/threatening, hate, hate/threatening, illicit, illicit/violent, self-harm, self-harm/intent, self-harm/instructions, sexual, sexual/minors, violence, and violence/graphic. |
| 134 | +Text to classify: ` + string(encoded) |
| 135 | +} |
| 136 | + |
| 137 | +func moderationGrammar() (string, error) { |
| 138 | + boolProperties := map[string]any{} |
| 139 | + scoreProperties := map[string]any{} |
| 140 | + for _, category := range moderationCategories { |
| 141 | + boolProperties[category] = map[string]any{"type": "boolean"} |
| 142 | + scoreProperties[category] = map[string]any{"type": "number"} |
| 143 | + } |
| 144 | + structure := functions.JSONFunctionStructure{AnyOf: []functions.Item{{ |
| 145 | + Type: "object", |
| 146 | + Properties: map[string]any{ |
| 147 | + "categories": map[string]any{ |
| 148 | + "type": "object", |
| 149 | + "properties": boolProperties, |
| 150 | + "required": moderationCategories, |
| 151 | + "additionalProperties": false, |
| 152 | + }, |
| 153 | + "category_scores": map[string]any{ |
| 154 | + "type": "object", |
| 155 | + "properties": scoreProperties, |
| 156 | + "required": moderationCategories, |
| 157 | + "additionalProperties": false, |
| 158 | + }, |
| 159 | + }, |
| 160 | + }}} |
| 161 | + return structure.Grammar() |
| 162 | +} |
| 163 | + |
| 164 | +func parseModerationResult(raw string) (schema.ModerationResult, error) { |
| 165 | + var generated generatedModeration |
| 166 | + if err := json.Unmarshal([]byte(strings.TrimSpace(raw)), &generated); err != nil { |
| 167 | + return schema.ModerationResult{}, err |
| 168 | + } |
| 169 | + |
| 170 | + result := schema.ModerationResult{ |
| 171 | + Categories: make(map[string]bool, len(moderationCategories)), |
| 172 | + CategoryScores: make(map[string]float64, len(moderationCategories)), |
| 173 | + CategoryAppliedInputTypes: make(map[string][]string, len(moderationCategories)), |
| 174 | + } |
| 175 | + for _, category := range moderationCategories { |
| 176 | + flagged, exists := generated.Categories[category] |
| 177 | + if !exists { |
| 178 | + return schema.ModerationResult{}, fmt.Errorf("missing category %q", category) |
| 179 | + } |
| 180 | + score, exists := generated.CategoryScores[category] |
| 181 | + if !exists || math.IsNaN(score) || math.IsInf(score, 0) || score < 0 || score > 1 { |
| 182 | + return schema.ModerationResult{}, fmt.Errorf("category %q has an invalid score", category) |
| 183 | + } |
| 184 | + result.Categories[category] = flagged |
| 185 | + result.CategoryScores[category] = score |
| 186 | + result.CategoryAppliedInputTypes[category] = []string{"text"} |
| 187 | + result.Flagged = result.Flagged || flagged |
| 188 | + } |
| 189 | + return result, nil |
| 190 | +} |
0 commit comments