clavata

package module
v1.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 24, 2025 License: Apache-2.0 Imports: 23 Imported by: 0

README

Clavata Go SDK

Go Reference Go Report Card

The official Go SDK for the Clavata Content Evaluation API.

Clavata helps you automatically detect and filter unwanted content in text, images, and other media. This SDK provides a simple and idiomatic Go interface for integrating Clavata's moderation capabilities into your applications.

Features

  • Simple API - Easy-to-use client with sensible defaults
  • Multiple content types - Text, images, files, and URLs
  • Flexible evaluation - Sync, async, streaming, and batch processing
  • Robust error handling - Automatic retries with exponential backoff
  • Type safety - Full Go type definitions for all API responses
  • Context support - Built-in context.Context support for timeouts and cancellation

Installation

go get github.com/clavataai/gosdk

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    clavata "github.com/clavataai/gosdk"
)

func main() {
    // Create a new client
    client, err := clavata.New(
        clavata.WithAPIKey("your-api-key"),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // Evaluate content
    report, err := client.EvaluateOne(
        context.Background(),
        "your-policy-id",
        clavata.NewTextContent("Content to evaluate"),
        clavata.JobOptions{},
    )
    if err != nil {
        log.Fatal(err)
    }

    // Check results
    if report.Result == clavata.OutcomeTrue {
        fmt.Printf("Content flagged! Actions: %v\n", report.Actions)
        fmt.Printf("Matches: %v\n", report.Matches)
    } else {
        fmt.Println("Input did not match any labels at the current threshold of %d", report.Threshold)
    }
}

Content Types

The SDK supports multiple content types:

// Text content
textContent := clavata.NewTextContent("Your text here")

// Image from bytes
imageContent := clavata.NewImageContent(imageBytes)

// Image from file
fileContent := clavata.NewImageFileContent("path/to/image.jpg")

// Image from URL
urlContent := clavata.NewImageURLContent("https://example.com/image.jpg")

Evaluation Methods

Synchronous - Single Content

Perfect for real-time moderation:

report, err := client.EvaluateOne(
    ctx,
    "policy-id",
    clavata.NewTextContent("content"),
    clavata.JobOptions{Threshold: 0.8},
)
Streaming - Multiple Content

Ideal for processing multiple items with real-time results:

request := clavata.NewEvaluateRequestBuilder().
    PolicyID("policy-id").
    AddContent(
        clavata.NewTextContent("First content"),
        clavata.NewTextContent("Second content"),
    ).
    Build()

// Using iterator (Go 1.23+)
for report, err := range client.EvaluateIter(ctx, request) {
    if err != nil {
        log.Printf("Error: %v", err)
        continue
    }
    fmt.Printf("Result: %s\n", report.Result)
}

// Using channel
ch, err := client.Evaluate(ctx, request)
if err != nil {
    log.Fatal(err)
}

for result := range ch {
    if result.Error != nil {
        log.Printf("Error: %v", result.Error)
        continue
    }
    fmt.Printf("Result: %s\n", result.Report.Result)
}
Asynchronous Jobs

For batch processing large amounts of content:

// Create job
job, err := client.CreateJob(ctx, &clavata.CreateJobRequest{
    PolicyID: "policy-id",
    Content: []clavata.Contenter{
        clavata.NewTextContent("content 1"),
        clavata.NewTextContent("content 2"),
    },
    WebhookURL: "https://your-app.com/webhook", // Optional
})

// Check job status
job, err = client.GetJob(ctx, job.ID)
if job.Status == clavata.JobStatusCompleted {
    for _, report := range job.Results {
        fmt.Printf("Result: %s\n", report.Result)
    }
}

Configuration

Custom Timeouts
client, err := clavata.New(
    clavata.WithAPIKey("your-api-key"),
    clavata.WithTimeout(60 * time.Second),
)
Custom Retry Behavior
client, err := clavata.New(
    clavata.WithAPIKey("your-api-key"),
    clavata.WithRetryConfig(clavata.RetryConfig{
        MaxRetries:              5,
        InitialInterval:         500 * time.Millisecond,
        MaxInterval:            30 * time.Second,
        Multiplier:             2.0,
        RandomizationFactor:    0.1,
    }),
)
Disable Retries
client, err := clavata.New(
    clavata.WithAPIKey("your-api-key"),
    clavata.WithDisableRetry(),
)

Error Handling

The SDK automatically handles rate limiting and transient errors with exponential backoff. For permanent errors, you'll receive detailed error information.

Standard Error Handling
report, err := client.EvaluateOne(ctx, "policy-id", content, options)
if err != nil {
    // Check for specific precheck failures directly
    if errors.Is(err, clavata.ErrContentCSAM) {
        log.Printf("CSAM content detected")
        return
    }

    // Check for other precheck failures
    if errors.Is(err, clavata.ErrContentInvalidFormat) {
        log.Printf("Invalid image format")
        return
    }

    // Or extract ContentError for both error type and content hash
    var contentErr *clavata.ContentError
    if errors.As(err, &contentErr) {
        log.Printf("Content %s failed precheck: %v", contentErr.ContentHash, contentErr.Err)
        return
    }

    // Handle other errors
    if errors.Is(err, clavata.ErrAPIKeyRequired) {
        log.Fatal("API key is required")
    }
    log.Printf("Evaluation failed: %v", err)
    return
}

Precheck Failures

Before content evaluation, Clavata runs prechecks to identify known issues that would prevent evaluation. This helps catch problems early and protects against processing illegal or invalid content.

Common Precheck Failures
  • CSAM Detection: Content matches known Child Sexual Abuse Material
  • Invalid Image Format: Corrupted or unsupported image data
  • Invalid Data: Incomplete or malformed content
Handling Precheck Failures

When a precheck failure occurs, the SDK returns a ContentError that includes:

  • The specific error type
  • The content hash of the problematic content

You can handle precheck failures in two ways:

Option 1: Direct Error Type Checking

If you only need to check the error type and don't need the content hash, you can check directly:

report, err := client.EvaluateOne(ctx, "policy-id", content, options)
if err != nil {
    // Check specific error types directly
    switch {
    case errors.Is(err, clavata.ErrContentCSAM):
        // Handle CSAM content - do not process further
        log.Printf("CSAM content detected")
        return
    case errors.Is(err, clavata.ErrContentInvalidFormat):
        // Handle invalid format - possibly retry with different content
        log.Printf("Invalid image format")
        return
    case errors.Is(err, clavata.ErrContentInvalidData):
        // Handle invalid data - content may be corrupted
        log.Printf("Invalid content data")
        return
    }

    // Handle other errors
    log.Printf("Evaluation failed: %v", err)
    return
}
Option 2: Extract ContentError for Additional Details

If you need both the error type and content hash:

report, err := client.EvaluateOne(ctx, "policy-id", content, options)
if err != nil {
    var contentErr *clavata.ContentError
    if errors.As(err, &contentErr) {
        // Handle precheck failure with access to content hash
        fmt.Printf("Content failed precheck: %v\n", contentErr.Err)
        fmt.Printf("Content hash: %s\n", contentErr.ContentHash)

        // Check specific error types
        switch {
        case errors.Is(contentErr.Err, clavata.ErrContentCSAM):
            // Handle CSAM content - do not process further
            log.Printf("CSAM content detected: %s", contentErr.ContentHash)
        case errors.Is(contentErr.Err, clavata.ErrContentInvalidFormat):
            // Handle invalid format - possibly retry with different content
            log.Printf("Invalid image format: %s", contentErr.ContentHash)
        case errors.Is(contentErr.Err, clavata.ErrContentInvalidData):
            // Handle invalid data - content may be corrupted
            log.Printf("Invalid content data: %s", contentErr.ContentHash)
        }
        return
    }

    // Handle other errors
    log.Printf("Evaluation failed: %v", err)
    return
}
Error Types

The SDK defines specific error types for different precheck failures:

// Content errors
var (
    ErrContentCSAM          = errors.New("content is CSAM, cannot evaluate")
    ErrContentInvalidFormat = errors.New("content is invalid format")
    ErrContentInvalidData   = errors.New("content incomplete or includes invalid data")
)

Response Structure

type Report struct {
    PolicyID        string            // ID of the evaluated policy
    ContentHash     string            // Hash of the content
    Result          Outcome           // Overall result (TRUE/FALSE/FAILED)
    Threshold       float64           // Threshold used for evaluation
    Matches         map[string]float64 // Labels that exceeded threshold
    Actions         []string          // Recommended actions
    LabelReports    map[string]LabelReport // Detailed per-label results
}

type LabelReport struct {
    LabelName string   // Name of the label
    Score     float64  // Score (0.0 to 1.0)
    Outcome   Outcome  // Result for this label
    Actions   string   // Actions for this label
}

Requirements

  • Go 1.23.0 or later
  • Valid Clavata API key

Getting an API Key

  1. Sign up at clavata.ai
  2. Create a policy for your content moderation needs
  3. Generate an API key in your dashboard
  4. Use the policy ID and API key in your integration

Documentation

Support

License

This SDK is distributed under the Apache 2.0 License. See LICENSE for more information.


Made with ❤️ by the Clavata team.

Documentation

Overview

Package clavata provides the official Go SDK for the Clavata Content Moderation API.

Clavata is a content moderation platform that helps you automatically detect and filter unwanted content in text, images, and other media. This SDK provides a simple and idiomatic Go interface for integrating Clavata's moderation capabilities into your applications.

Quick Start

To get started, you'll need a Clavata API key. Contact [email protected] to request one.

import "github.com/clavataai/gosdk"

// Create a client
client, err := clavata.New(clavata.WithAPIKey("your-api-key"))
if err != nil {
	log.Fatal(err)
}
defer client.Close()

// Evaluate content
report, err := client.EvaluateOne(
	context.Background(),
	"your-policy-id",
	clavata.NewTextContent("Content to moderate"),
	clavata.JobOptions{},
)
if err != nil {
	log.Fatal(err)
}

if report.Result == clavata.OutcomeTrue {
	fmt.Println("Content flagged:", report.Actions)
}

Content Types

The SDK supports multiple content types:

  • Text content: clavata.NewTextContent("your text")
  • Image data: clavata.NewImageContent(imageBytes)
  • Image files: clavata.NewImageFileContent("path/to/image.jpg")
  • Image URLs: clavata.NewImageURLContent("https://example.com/image.jpg")

Evaluation Methods

The SDK provides several ways to evaluate content:

  • EvaluateOne: Evaluate a single piece of content synchronously
  • Evaluate: Evaluate multiple pieces of content with streaming results
  • EvaluateIter: Same as Evaluate but returns a Go iterator for easier handling
  • CreateJob: Create an asynchronous job for batch processing

Error Handling and Retries

The SDK automatically handles rate limiting and transient errors with configurable exponential backoff. You can customize retry behavior:

client, err := clavata.New(
	clavata.WithAPIKey("your-api-key"),
	clavata.WithRetryConfig(clavata.RetryConfig{
		MaxRetries:      3,
		InitialInterval: 500 * time.Millisecond,
		MaxInterval:     30 * time.Second,
		Multiplier:      2.0,
	}),
)

Content Checks and Possible Failure Modes

Before content evaluation, Clavata runs prechecks to identify known issues that would prevent evaluation. Common precheck failures include:

  • CSAM content detected (matches known illegal material)
  • Invalid image format or corrupted data
  • Unsupported media types

When a precheck failure occurs, the SDK returns a ContentError that includes both the specific error and the ContentHash of the problematic content:

report, err := client.EvaluateOne(ctx, policyID, content, options)
if err != nil {
	// Option 1: Check specific error types directly (if you don't need content hash)
	if errors.Is(err, clavata.ErrContentCSAM) {
		// Handle CSAM content directly
		return
	}

	// Option 2: Extract ContentError to get both error type and content hash
	var contentErr *clavata.ContentError
	if errors.As(err, &contentErr) {
		fmt.Printf("Content failed precheck: %v\n", contentErr.Err)
		fmt.Printf("Content hash: %s\n", contentErr.ContentHash)

		// Check specific error types
		if errors.Is(contentErr.Err, clavata.ErrContentCSAM) {
			// Handle CSAM content
		}
	}
}

Timeouts

Configure request timeouts as needed:

client, err := clavata.New(
	clavata.WithAPIKey("your-api-key"),
	clavata.WithTimeout(60 * time.Second),
)

For more information and examples, visit: https://docs.clavata.ai

Example

Example demonstrates how to create a Clavata client and evaluate content.

package main

import (
	"context"
	"fmt"
	"log"

	clavata "github.com/clavataai/gosdk"
)

func main() {
	// Create a new client with your API key
	client, err := clavata.New(clavata.WithAPIKey("your-api-key-here"))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	// Create some content to evaluate
	content := clavata.NewTextContent("Hello, world!")

	// Evaluate the content against a policy
	ctx := context.Background()
	report, err := client.EvaluateOne(ctx, "your-policy-id", content, clavata.JobOptions{})
	if err != nil {
		log.Printf("Error evaluating content: %v", err)
		return
	}

	// Process the report
	fmt.Printf("Policy: %s, Overall result: %s\n", report.PolicyID, report.Result)
	for labelName, score := range report.Matches {
		fmt.Printf("  %s: %.2f\n", labelName, score)
	}
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrAPIKeyRequired   = errors.New("API key is required")
	ErrInvalidEndpoint  = errors.New("invalid endpoint")
	ErrClientConnection = errors.New("failed to create client for Clavata API")

	// Content errors
	ErrContentCSAM          = errors.New("content is CSAM, cannot evaluate")
	ErrContentInvalidFormat = errors.New("content is invalid format")
	ErrContentInvalidData   = errors.New("content incomplete or includes invalid data")
)
View Source
var Version = "v1.1.2"

The SDK version that should align with the git tag used to publish the SDK.

Functions

func WithAPIKey

func WithAPIKey(apiKey string) option

WithAPIKey sets the API key for the client. If you do not have an API key, please reach out to [email protected] to request one.

func WithDisableRetry

func WithDisableRetry() option

WithDisableRetry disables automatic retry on rate limits

func WithEndpoint

func WithEndpoint(endpoint string) option

WithEndpoint sets the endpoint for the client. Unless you have been told to set a different endpoint, there's no need to set this flag.

func WithInsecure

func WithInsecure(insecure bool) option

WithInsecure sets the insecure flag for the client. This is only used by Clavata for testing purposes and should not be used in production.

func WithRetryConfig

func WithRetryConfig(retryConfig RetryConfig) option

WithRetryConfig sets custom retry configuration for the client

func WithTimeout

func WithTimeout(timeout time.Duration) option

WithTimeout sets the default timeout for requests. If not set, the default timeout is 30 seconds.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the main Clavata SDK client

func New

func New(options ...option) (*Client, error)

New creates a new Clavata client

func (*Client) Close

func (c *Client) Close() error

Close closes the client connection. You can do this with defer to ensure that the connection is always cleaned up.

func (*Client) CloseOnExit

func (c *Client) CloseOnExit()

CloseOnExit registers the client for cleanup. This can be useful if you are using a long lived instance of the client and want to make sure it is always closed before exit.

func (*Client) CreateJob

func (c *Client) CreateJob(ctx context.Context, req *CreateJobRequest) (*Job, error)

CreateJob creates a new content evaluation job

func (*Client) Evaluate

func (c *Client) Evaluate(ctx context.Context, req *EvaluateRequest) (chan EvaluateResult, error)

Evaluate creates a streaming evaluation job and returns a channel. You can read from the channel to receive the reports as they become available. If an error occurs, the channel will be closed and the error will be sent on the channel.

func (*Client) EvaluateIter

func (c *Client) EvaluateIter(ctx context.Context, req *EvaluateRequest) iter.Seq2[*Report, error]

EvaluateIter creates a streaming evaluation job and returns a go iterator. You can loop over it with a for..range loop to receive the reports as they become available. The convenience of this function is that each iteration loop will return an error if one occurred. Otherwise, the report will be returned as the first value.

func (*Client) EvaluateOne

func (c *Client) EvaluateOne(
	ctx context.Context,
	policyId string,
	content Contenter,
	options JobOptions,
) (*Report, error)

EvaluateOne is sugar for times when you only need to evaluate a single content item and get its report.

Example

ExampleClient_EvaluateOne demonstrates how to evaluate a single piece of content.

package main

import (
	"context"
	"fmt"
	"log"

	clavata "github.com/clavataai/gosdk"
)

func main() {
	client, err := clavata.New(clavata.WithAPIKey("your-api-key-here"))
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	ctx := context.Background()
	content := clavata.NewTextContent("Sample text to evaluate")

	report, err := client.EvaluateOne(ctx, "content-safety-policy", content, clavata.JobOptions{
		Threshold: 0.7,
		Expedited: true,
	})
	if err != nil {
		log.Printf("Error: %v", err)
		return
	}

	fmt.Printf("Evaluation completed for policy %s\n", report.PolicyID)
	fmt.Printf("Content hash: %s\n", report.ContentHash)
	fmt.Printf("Overall result: %s\n", report.Result)
}

func (*Client) GetJob

func (c *Client) GetJob(ctx context.Context, jobID string) (*Job, error)

GetJob retrieves a job by its UUID

func (*Client) ListJobs

func (c *Client) ListJobs(ctx context.Context, req *ListJobsRequest) (*ListJobsResponse, error)

ListJobs lists jobs with optional filtering

type ContentError

type ContentError struct {
	// Err is the specific error that occurred during precheck. Will be one of the ErrContent*
	// errors found in this package.
	Err error
	// ContentHash is the hash of the content that caused the failure
	ContentHash string
}

ContentError is returned when content fails precheck validation before evaluation. It contains both the specific error and the ContentHash of the problematic content, allowing applications to identify and handle specific content issues.

Common scenarios include:

  • CSAM content detected (ErrContentCSAM)
  • Invalid image format (ErrContentInvalidFormat)
  • Corrupted or incomplete data (ErrContentInvalidData)

Because ContentError implements Unwrap(), you can check error types directly:

// Direct error type checking (no content hash access)
if errors.Is(err, ErrContentCSAM) {
	// Handle CSAM content
}

// Or extract ContentError for both error type and content hash
var contentErr *ContentError
if errors.As(err, &contentErr) {
	log.Printf("Content %s failed precheck: %v", contentErr.ContentHash, contentErr.Err)
}
Example

ExampleContentError demonstrates how to handle precheck failures.

// Simulate an error that might occur during content evaluation
err := errors.New("simulated precheck failure")

// In practice, this would be an error returned from client.EvaluateOne()
// or client.Evaluate()

// Check for specific content errors
if errors.Is(err, ErrContentCSAM) {
	fmt.Println("Content contains CSAM and cannot be evaluated")
	return
}

if errors.Is(err, ErrContentInvalidFormat) {
	fmt.Println("Content has an invalid format")
	return
}

// Or extract the ContentError for more details
var contentErr *ContentError
if errors.As(err, &contentErr) {
	fmt.Printf("Content %s failed precheck: %v\n", contentErr.ContentHash, contentErr.Err)
	return
}

// Handle other types of errors
fmt.Printf("Other error: %v\n", err)
Output:

Other error: simulated precheck failure

func (*ContentError) Error

func (c *ContentError) Error() string

Error returns a string representation of the error.

func (*ContentError) FromPrecheckFailure

func (c *ContentError) FromPrecheckFailure(precheckFailure *gatewayv1.PrecheckFailure) error

FromPrecheckFailure extracts the error and content hash from a precheck failure.

func (*ContentError) Unwrap

func (c *ContentError) Unwrap() error

Unwrap returns the underlying error.

type Contenter

type Contenter interface {
	// AddMetadata allows you to add a key/value pair to the content. This metadata will be included
	// in the `Report` for this piece of content, allowing you to include IDs or other information
	// that is meaningful to your system.
	AddMetadata(key, value string) Contenter
	// contains filtered or unexported methods
}

Contenter is an interface that represents a content input to send to the API.

func NewImageContent

func NewImageContent(imageData []byte) Contenter

NewImageContent can be used to create an image input to send to the API.

func NewImageFileContent

func NewImageFileContent(imageFile string) Contenter

NewImageFileContent can be used to create an image input from a file available on the local file system to send to the API.

func NewImageURLContent

func NewImageURLContent(imageURL string) Contenter

NewImageURLContent can be used to create an image input from a URL to send to the API.

func NewTextContent

func NewTextContent(text string) Contenter

NewTextContent can be used to create a text input to send to the API.

type CreateJobRequest

type CreateJobRequest struct {
	// The ID of the policy to evaluate the content against.
	PolicyID string
	// The content to evaluate.
	Content []Contenter
	// The options for the job.
	Options JobOptions
	// WebhookURL is the URL to call when the job is complete. Must be HTTPS and will be called with POST.
	WebhookURL string
}

CreateJobRequest is the request type for the CreateJob method.

type CreateJobRequestBuilder

type CreateJobRequestBuilder struct {
	// contains filtered or unexported fields
}

CreateJobRequestBuilder simplifies the construction of a CreateJobRequest. First, create the builder with `NewCreateJobRequestBuilder()`. Then, use the builder to set the policy ID, content, options, and webhook. Finally, call `Build()` to create the request.

Example:

builder := NewCreateJobRequestBuilder()
req := builder.PolicyID("policy-id").AddContent(NewTextContent("Hello, world!")).Build()

You can then use the request with the CreateJob method.

func NewCreateJobRequestBuilder

func NewCreateJobRequestBuilder() *CreateJobRequestBuilder

NewCreateJobRequestBuilder creates a new CreateJobRequestBuilder.

func (*CreateJobRequestBuilder) AddContent

func (b *CreateJobRequestBuilder) AddContent(content ...Contenter) *CreateJobRequestBuilder

AddContent adds content to the request.

func (*CreateJobRequestBuilder) Build

Build creates a new CreateJobRequest from the builder.

func (*CreateJobRequestBuilder) Expedited

func (b *CreateJobRequestBuilder) Expedited(expedited bool) *CreateJobRequestBuilder

Expedited sets the expedited flag for the request.

func (*CreateJobRequestBuilder) Options

Options sets the options for the request.

func (*CreateJobRequestBuilder) PolicyID

PolicyID sets the policy ID for the request.

func (*CreateJobRequestBuilder) Threshold

func (b *CreateJobRequestBuilder) Threshold(threshold float64) *CreateJobRequestBuilder

Threshold sets the threshold for the request.

func (*CreateJobRequestBuilder) Webhook

Webhook sets the webhook for the request.

type EvaluateRequest

type EvaluateRequest struct {
	// The content to evaluate.
	Content []Contenter
	// The ID of the policy to evaluate all of the supplied content against.
	PolicyID string
	// Options that will impact how the job is evaluated.
	Options JobOptions
}

EvaluateRequest is the request type for the Evaluate method.

type EvaluateRequestBuilder

type EvaluateRequestBuilder struct {
	// contains filtered or unexported fields
}

EvaluateRequestBuilder simplifies the construction of an EvaluateRequest. First, create the builder with `NewEvaluateRequestBuilder()`. Then, use the builder to set the policy ID, content, and options. Finally, call `Build()` to create the request.

Example:

builder := NewEvaluateRequestBuilder()
req := builder.PolicyID("policy-id").AddContent(NewTextContent("Hello, world!")).Build()

You can then use the request with the Evaluate method.

func NewEvaluateRequestBuilder

func NewEvaluateRequestBuilder() *EvaluateRequestBuilder

NewEvaluateRequestBuilder creates a new EvaluateRequestBuilder.

func (*EvaluateRequestBuilder) AddContent

func (b *EvaluateRequestBuilder) AddContent(content ...Contenter) *EvaluateRequestBuilder

AddContent adds content to the request.

func (*EvaluateRequestBuilder) Build

Build creates a new EvaluateRequest from the builder.

func (*EvaluateRequestBuilder) Expedited

func (b *EvaluateRequestBuilder) Expedited(expedited bool) *EvaluateRequestBuilder

Expedited sets the expedited flag for the request.

func (*EvaluateRequestBuilder) Options

Options sets the options for the request.

func (*EvaluateRequestBuilder) PolicyID

func (b *EvaluateRequestBuilder) PolicyID(policyID string) *EvaluateRequestBuilder

PolicyID sets the policy ID for the request.

func (*EvaluateRequestBuilder) Threshold

func (b *EvaluateRequestBuilder) Threshold(threshold float64) *EvaluateRequestBuilder

Threshold sets the threshold for the request.

type EvaluateResult

type EvaluateResult struct {
	Report *Report
	Error  error
}

EvaluateResult is the result of an evaluation. If an error occurs, the Error field will be set. Otherwise, the Report field will be set to the report for the current piece of content.

type Job

type Job struct {
	ID          string
	CustomerID  string
	Status      JobStatus
	Results     []Report
	CreatedAt   time.Time
	UpdatedAt   time.Time
	CompletedAt time.Time
}

A Job is the result of a request to CreateJob. Each job will contain as many reports as there were pieces of content included in the job request.

type JobOptions

type JobOptions struct {
	// If set, the job will be evaluated with the given threshold. A threshold of 0.0 will be
	// considered unset and the server default will be used (0.50).
	Threshold float64
	// If set, this will prioritze speed over accuracy. In most cases, the accuracy difference is
	// minimal. For image content, expedited mode generally improves latency by 20-30%.
	Expedited bool
}

JobOptions allow you to configure certain aspects of how the job is processed.

type JobStatus

type JobStatus string

JobStatus represents the status of a job

const (
	// JobStatusUnspecified is the zero value. Should not be used.
	JobStatusUnspecified JobStatus = "UNSPECIFIED"
	// JobStatusPending means the job is in queue and will be evaluated soon.
	JobStatusPending JobStatus = "PENDING"
	// JobStatusRunning means the job is being evaluated.
	JobStatusRunning JobStatus = "RUNNING"
	// JobStatusCompleted means the job has been evaluated and the results are available.
	JobStatusCompleted JobStatus = "COMPLETED"
	// JobStatusFailed means the job failed to evaluate.
	JobStatusFailed JobStatus = "FAILED"
	// JobStatusCanceled means the job was canceled, typically by the user.
	JobStatusCanceled JobStatus = "CANCELED"
)

func (JobStatus) String

func (j JobStatus) String() string

String returns the string representation of the job status.

type LabelReport

type LabelReport struct {
	// LabelName is the name of the label that was evaluated as defined in the policy. This field
	// will always match the key it is associated with in the `Matches` map of the `Report`.
	LabelName string
	// Score is the score of the label. Can be between 0.0 and 1.0. In rare cases, the score may be
	// -1.0, which means that evaluation failed.
	Score float64
	// Outcome is the outcome of the label. If the score is greater than the threshold, the outcome
	// will be TRUE.
	Outcome Outcome
	// Actions is the string that was associated with the `LABEL` in the policy.
	//
	// Example:
	// LABEL "Foo": "Action1, Action2" { ... }
	//
	// In this case, the Actions field will contain "Action1, Action2".
	Actions string
}

LabelReport provides details about the evaluation of a single piece of content against a single label's definition.

type ListJobsQuery

type ListJobsQuery struct {
	// Filter on the time the job was created.
	CreatedAt TimeRange
	// Filter on the time the job was last updated.
	UpdatedAt TimeRange
	// Filter on the time the job was completed.
	CompletedAt TimeRange
	// Filter on the status of the job.
	Status JobStatus
	// If set, only jobs that used this PolicyID will be returned.
	PolicyID string
}

ListJobsQuery is the query type for the ListJobs method.

type ListJobsRequest

type ListJobsRequest struct {
	// The query to use to filter the jobs.
	Query ListJobsQuery
	// The maximum number of jobs to return on a single page. If set to `0` this field will be
	// considered unset and the default will be used.(Default: 1000)
	PageSize int
	// The token to use to get the next page of results. This token will be returned by the server
	// in the `NextPageToken` field of the response. It should be passed back to the server in the
	// `PageToken` field of the next request to get the next page of results.
	PageToken string
}

ListJobsRequest is the request type for the ListJobs method.

func NewListJobsRequest

func NewListJobsRequest(query ListJobsQuery, pageSize int) *ListJobsRequest

NewListJobsRequest creates a new ListJobsRequest with the given query and page size.

func (*ListJobsRequest) NextPage

func (l *ListJobsRequest) NextPage(resp *ListJobsResponse) *ListJobsRequest

NextPage creates a new ListJobsRequest with the same query and page size, but with the page token set to the provided token. This can be used to get the next page of results from the current response.

Example:

builder := NewListJobsRequestBuilder()
req := builder.Query(ListJobsQuery{Status: JobStatusRunning}).Build()
resp, err := c.ListJobs(ctx, req)
if err != nil {
	return err
}

nextPageReq := req.NextPage(resp)
resp, err = c.ListJobs(ctx, nextPageReq)

type ListJobsRequestBuilder

type ListJobsRequestBuilder struct {
	// contains filtered or unexported fields
}

ListJobsRequestBuilder simplifies the construction of a ListJobsRequest. First, create the builder with `NewListJobsRequestBuilder()`. Then, use the builder to set the query, page size, and page token. Finally, call `Build()` to create the request.

Example:

builder := NewListJobsRequestBuilder()
req := builder.Query(ListJobsQuery{Status: JobStatusRunning}).Build()

This builder, in particular, can be helpful for dealing with pagination as it makes it easy to build requests with the same query and page size, but an updated page token. For example:

builder := NewListJobsRequestBuilder()
builder = builder.Query(ListJobsQuery{Status: JobStatusRunning}).PageSize(100)
resp, err := c.ListJobs(ctx, builder.Build())
if err != nil {
	return err
}

resp, err = c.ListJobs(ctx, builder.NextPage(resp).Build())
if err != nil {
	return err
}

And so on.

func NewListJobsRequestBuilder

func NewListJobsRequestBuilder() *ListJobsRequestBuilder

NewListJobsRequestBuilder creates a new ListJobsRequestBuilder.

func (*ListJobsRequestBuilder) Build

Build creates a new ListJobsRequest from the builder.

func (*ListJobsRequestBuilder) PageSize

func (b *ListJobsRequestBuilder) PageSize(pageSize int) *ListJobsRequestBuilder

PageSize sets the page size for the request.

func (*ListJobsRequestBuilder) PageToken

func (b *ListJobsRequestBuilder) PageToken(pageToken string) *ListJobsRequestBuilder

PageToken sets the page token for the request.

func (*ListJobsRequestBuilder) Query

Query sets the query for the request.

type ListJobsResponse

type ListJobsResponse struct {
	Jobs          []Job
	NextPageToken string
}

ListJobsResponse is the response type for the ListJobs method. It contains the list of jobs that match the query, and a token to use to get the next page of results.

func (*ListJobsResponse) NextPage

func (l *ListJobsResponse) NextPage(
	ctx context.Context, c *Client, req *ListJobsRequest,
) (*ListJobsResponse, error)

NextPage is a helper method that can be used to get the next page of results from the current response. You'll need to provide it with the Clavata client instance and previous request.

type Outcome

type Outcome string

An Outcome is how we represent the result of an evaluation for labels and the overall policy that contains them. While outcomes are generally TRUE or FALSE, they can also have a FAILED status. This is rare, but when it happens it means that a particular label(s) failed to evaluate.

const (
	// OutcomeUnspecified is the zero value. Should not be used.
	OutcomeUnspecified Outcome = "UNSPECIFIED"
	// OutcomeTrue means the label or policy evaluation was true.
	OutcomeTrue Outcome = "TRUE"
	// OutcomeFalse means the label or policy evaluation was false.
	OutcomeFalse Outcome = "FALSE"
	// OutcomeFailed means the label or policy evaluation failed.
	OutcomeFailed Outcome = "FAILED"
)

func (Outcome) String

func (o Outcome) String() string

String returns the string representation of the outcome.

type Report

type Report struct {
	// The ID of the policy that was evaluated.
	PolicyID string
	// The ID of the policy version that was evaluated.
	PolicyVersionID string
	// The FNV-1a hash of the content.
	ContentHash string
	// ContentMetadata will be filled with any metadata that was attached to the content at the time it was created.
	// This can be used to associate an ID your system understands with the report, allowing you to match results
	// to content inputs without the need to calculate the hash.
	ContentMetadata map[string]string
	// The overall outcome of the evaluation. If any label evaluated to true, the result will be true.
	Result Outcome
	// The threshold that was used to decide whether an outcome was true or false.
	Threshold float64

	// Matches is the list of labels that matched the content. Only labels with scores that exceed the threshold
	// will be included in this map. Each key is the label name, and the value is the score of the label.
	Matches map[string]float64
	// Actions is the list of actions associated with the labels that exceeded the threshold. If the same action
	// appears on more than one label, it is only included in this list once.
	Actions []string

	// The raw label reports. All labels are included, regardless of whether they exceeded the threshold. Each
	// key is the label name, and the value is the report, which includes the score the label received, the outcome
	// when the threshold was applied and the actions that were associated with the label.
	LabelReports map[string]LabelReport
}

A Report provides the full details of evaluating a single piece of content against a policy.

type RetryConfig

type RetryConfig struct {
	// MaxRetries is the maximum number of retry attempts (0 means no retry)
	MaxRetries uint64
	// InitialInterval is the initial backoff interval
	InitialInterval time.Duration
	// MaxInterval is the maximum backoff interval between retries.
	MaxInterval time.Duration
	// Multiplier is the backoff multiplier (e.g., 2.0 for exponential backoff)
	Multiplier float64
	// RandomizationFactor adds jitter to prevent thundering herd
	RandomizationFactor float64
}

RetryConfig configures retry behavior for rate-limited requests

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns our recommended retry configuration.

type TimeRange

type TimeRange struct {
	// Start is the start of the time range.
	Start time.Time
	// End is the end of the time range.
	End time.Time
	// Inclusive is whether the range is inclusive. If true, the range will include the start and
	// end times. Ranges are exclusive by default.
	Inclusive bool
}

A TimeRange is a range of time. Used to filter jobs by creation, update, or completion time. Note that if you set `Start` or `End` but not both, the resulting filter will be treated like a simple greater than or less than filter rather than requiring that the time is within the range.

Directories

Path Synopsis
internal
protobufs/gateway/v1
Package v1 is a reverse proxy.
Package v1 is a reverse proxy.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL