Skip to content

Commit

Permalink
chore: check for models before sending moderation requets to openai e…
Browse files Browse the repository at this point in the history
…ndpoint
  • Loading branch information
Munar committed Jul 12, 2023
1 parent f028c28 commit e579559
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions moderation.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package openai

import (
"context"
"errors"
"net/http"
)

Expand All @@ -18,6 +19,15 @@ const (
ModerationText001 = "text-moderation-001"
)

var (
ErrModerationInvalidModel = errors.New("this model is not supported with moderation, please use text-moderation-stable or text-moderation-latest instead") //nolint:lll
)

var validModerationModel = map[string]struct{}{
ModerationTextStable: {},
ModerationTextLatest: {},
}

// ModerationRequest represents a request structure for moderation API.
type ModerationRequest struct {
Input string `json:"input,omitempty"`
Expand Down Expand Up @@ -63,6 +73,10 @@ type ModerationResponse struct {
// Moderations — perform a moderation api call over a string.
// Input can be an array or slice but a string will reduce the complexity.
func (c *Client) Moderations(ctx context.Context, request ModerationRequest) (response ModerationResponse, err error) {
if _, ok := validModerationModel[request.Model]; len(request.Model) > 0 && !ok {
err = ErrModerationInvalidModel
return
}
req, err := c.newRequest(ctx, http.MethodPost, c.fullURL("/moderations", request.Model), withBody(&request))
if err != nil {
return
Expand Down
12 changes: 12 additions & 0 deletions moderation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ func TestModerations(t *testing.T) {
checks.NoError(t, err, "Moderation error")
}

// TestModerationsWithIncorrectModel Tests passing an incorrect model to Moderations request.
func TestModerationsWithIncorrectModel(t *testing.T) {
client, server, teardown := setupOpenAITestServer()
defer teardown()
server.RegisterHandler("/v1/moderations", handleModerationEndpoint)
_, err := client.Moderations(context.Background(), ModerationRequest{
Model: GPT3Dot5Turbo,
Input: "I want to kill them.",
})
checks.ErrorIs(t, err, ErrModerationInvalidModel)
}

// handleModerationEndpoint Handles the moderation endpoint by the test server.
func handleModerationEndpoint(w http.ResponseWriter, r *http.Request) {
var err error
Expand Down

0 comments on commit e579559

Please sign in to comment.