gopenai

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2023 License: MIT Imports: 12 Imported by: 0

README

gopenai

codecov goreportcard pipeline

gopenai is an unofficial package that provides bindings for the OpenAI API. It exposes a collection of interfaces for interacting with models, completions, edits, images, embeddings, files, fine tunes, and moderations.

Config

To use the package, you'll need to create a Config struct with your OpenAI API key and organization ID. You can also set a custom request timeout.

cfg := Config{
    APIKey: os.Getenv("OPENAI_API_KEY"),
    OrganizationID: "YOUR_ORGANIZATION_ID",
    RequestTimeout: time.Second * 30
}

Client

You can create a new client that uses the config you created with New().

c := gopenai.New(cfg)

The client provides access to the different APIs.

modelsAPI := c.Models()
completionsAPI := c.Completions()
editsAPI := c.Edits()
imagesAPI := c.Images()
embeddingsAPI := c.Embeddings()
filesAPI := c.Files()
fineTunesAPI := c.FineTunes()
moderationsAPI := c.Moderations()

ModelsAPI

The Models API allows you to get a list of all models, get a model by ID, and delete a model by ID.

models, err := modelsAPI.GetAll()
model, err := modelsAPI.GetByID(id)
deletedModel, err := modelsAPI.DeleteByID(id)

CompletionsAPI

The Completions API allows you to create a completion.

params := CompletionParams{
    Model: "YOUR_MODEL",
    Prompt: "YOUR_PROMPT",
    Suffix: "YOUR_SUFFIX",
    MaxTokens: 30,
    Temperature: 1.0,
    TopP: 0.9,
    N: 10,
    Logprobs: 1,
    Echo: true,
    Stop: ".",
    PresencePenalty: 0.0,
    FrequencyPenalty: 0.0,
    BestOf: 3,
    User: "YOUR_USER"
}

completion, err := completionsAPI.Create(params)

ChatCompletionsAPI

The Chat Completions API allows you to create a chat completion.

params := ChatCompletionParams{
    Model: "gpt-3.5-turbo",
    Messages: []ChatCompletionMessage{
        {Role: ChatCompletionMessageRoleSystem, Content: "SYSTEM_INSTRUCTION"},
        {Role: ChatCompletionMessageRoleUser, Content: "USER_MESSAGE"},
    },
    Temperature: 0.8,
    TopP: 0.9,
    N: 10,
    Stop: ".",
    PresencePenalty: 0.0,
    FrequencyPenalty: 0.0,
    LogitBias: map[string]interface{}{
        "2435": -100,
        "640": -100,
    },
    User: "YOUR_USER",
}

completion, err := chatCompletionsAPI.Create(params)

EditsAPI

The Edits API provides methods for creating edits.

params := EditParams{
    Model: "model_name",
    Input: "input_text",
    Instruction: "edit_instruction",
    N: 10,
    Temperature: 0.5,
    TopP: 0.8,
}

edit, err := editsAPI.Create(params)

Images API

The Images API provides methods for creating, editing, and creating variations of images.

Create

The Create method creates a new image based on the given input.

params := gopenai.ImageGenerationParams{
    Prompt: "This is a test prompt",
    N: 10,
    Size: gopenai.ImageSize1024x1024,
    ResponseFormat: gopenai.ImageResponseFormatURL,
    User: "username",
}

images, err := imagesAPI.Create(params)

Edit

The Edit method edits an existing image based on the given input.

params := gopenai.ImageEditParams{
    Image: "path/to/image.png",
    Mask: "path/to/mask.png",
    Prompt: "This is a test prompt",
    N: 10,
    Size: gopenai.ImageSize1024x1024,
    ResponseFormat: gopenai.ImageResponseFormatURL,
    User: "username",
}

images, err := imagesAPI.Edit(params)

Create Variations

The CreateVariations method creates variations of an existing image based on the given input.

params := gopenai.ImageVariationParams{
    Image: "path/to/image.png",
    N: 10,
    Size: gopenai.ImageSize1024x1024,
    ResponseFormat: gopenai.ImageResponseFormatURL,
    User: "username",
}

images, err := imagesAPI.CreateVariations(params)

Embeddings API

The Embeddings API provides methods to create embeddings from the OpenAI models.

Create

The Create method takes an EmbeddingParams struct as a parameter and returns an Embedding struct.

params := gopenai.EmbeddingParams{
    Model: "text-embedding-ada-002",
    Input: "This is a string to be embedded",
    User: "user@example.com",
}

embedding, err := embeddingsAPI.Create(params)

Files API

The Files API provides methods to manage files, such as creating, deleting and downloading files.

GetAll

The GetAll method returns a list of File structs.

files, err := filesAPI.GetAll()
GetByID

The GetByID method takes an ID as a parameter and returns a File struct.

file, err := filesAPI.GetByID("<file_id>")
Create

The Create method takes a FileParams struct as a parameter and returns a File struct.

params := gopenai.FileParams{
    File: "<path_to_file>",
    Purpose: "fine-tune",
}

file, err := filesAPI.Create(params)
DeleteByID

The DeleteByID method takes an ID as a parameter and returns a DeletedFile struct.

deleted, err := filesAPI.DeleteByID("<file_id>")
DownloadByID

The DownloadByID method takes an ID and a destination io.Writer as parameters and returns an error.

err := filesAPI.DownloadByID("<file_id>", os.Stdout)

FineTunes API

The FineTunes API provides methods to manage fine tunes, such as creating and cancelling fine tunes.

GetAll

The GetAll method returns a list of FineTune structs.

fineTunes, err := fineTunesAPI.GetAll()
GetByID

The GetByID method takes an ID as a parameter and returns a FineTune struct.

fineTune, err := fineTunesAPI.GetByID("<fine_tune_id>")
Create

The Create method takes a FineTuneParams struct as a parameter and returns a FineTune struct.

params := gopenai.FineTuneParams{
    TrainingFile: "<training_file_id>",
    ValidationFile: "<validation_file_id>",
    Model: "curie",
    NEpochs: 3,
    BatchSize: 16,
    LearningRateMultiplier: 0.1,
    PromptLossWeight: 0.5,
    ComputeClassificationMetrics: true,
    ClassificationNClasses: 2,
    ClassificationPositiveClass: "positive",
    ClassificationBetas: []float64{0.5, 0.5},
    Suffix: "my_suffix",
}

fineTune, err := fineTunesAPI.Create(params)
Cancel

The Cancel method takes an ID as a parameter and returns a FineTune struct.

fineTune, err := fineTunesAPI.Cancel("<fine_tune_id>")
GetEvents

The GetEvents method takes a fine tune ID as a parameter and returns a list of FineTuneEvent structs.

events, err := fineTunesAPI.GetEvents("<fine_tune_id>")

Moderations API

The Moderations API provides methods to manage moderations, such as creating moderations.

Create

The Create method takes a ModerationParams struct as a parameter and returns a Moderation struct.

params := gopenai.ModerationParams{
    Input: "This is a string to be moderated",
    Model: "text-moderation-stable",
}

moderation, err := moderationsAPI.Create(params)

TODO

  • add more tests

Documentation

Overview

Package gopenai provides Go bindings for the OpenAI API.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrRequestTimeout is an error that indicates a request has timed out.
	ErrRequestTimeout = errors.New("request timeout")
)

Functions

This section is empty.

Types

type ChatCompletion added in v1.2.0

type ChatCompletion struct {
	ID      string                 `json:"id"`
	Object  string                 `json:"object"`
	Created int                    `json:"created"`
	Choices []ChatCompletionChoice `json:"choices"`
	Usage   TokenUsage             `json:"usage"`
}

ChatCompletion represents a chat completion of a prompt generated by the API.

type ChatCompletionChoice added in v1.2.0

type ChatCompletionChoice struct {
	Index        int                   `json:"index"`
	Message      ChatCompletionMessage `json:"message"`
	FinishReason string                `json:"finish_reason"`
}

ChatCompletionChoice represents a single completion for a given prompt.

type ChatCompletionMessage added in v1.2.0

type ChatCompletionMessage struct {
	Role    ChatCompletionMessageRole `json:"role"`
	Content string                    `json:"content"`
}

ChatCompletionMessage represents a message in a chat conversation

type ChatCompletionMessageRole added in v1.2.0

type ChatCompletionMessageRole string

ChatCompletionMessageRole is an enum type representing the role of a message in a chat conversation (system, user, or assistant).

const (
	ChatCompletionMessageRoleSystem    ChatCompletionMessageRole = "system"
	ChatCompletionMessageRoleUser      ChatCompletionMessageRole = "user"
	ChatCompletionMessageRoleAssistant ChatCompletionMessageRole = "assistant"
)

ChatCompletionMessageRole enum values

type ChatCompletionParams added in v1.2.0

type ChatCompletionParams struct {
	Model            string                  `json:"model"`
	Messages         []ChatCompletionMessage `json:"messages"`
	Temperature      float64                 `json:"temperature,omitempty"`
	TopP             float64                 `json:"top_p,omitempty"`
	N                int                     `json:"n,omitempty"`
	Stop             string                  `json:"stop,omitempty"`
	PresencePenalty  float64                 `json:"presence_penalty,omitempty"`
	FrequencyPenalty float64                 `json:"frequency_penalty,omitempty"`
	LogitBias        LogitBias               `json:"logit_bias,omitempty"`
	User             string                  `json:"user,omitempty"`
}

ChatCompletionParams represents the parameters for a chat completion request, including the model to use, the input messages, and various completion settings.

type ChatCompletionsAPI added in v1.2.0

type ChatCompletionsAPI interface {
	// Create generates a new completion based on the given
	// ChatCompletionParams and returns it as a ChatCompletion object.
	Create(ChatCompletionParams) (ChatCompletion, error)
}

ChatCompletionsAPI is an interface for creating completions.

type Client

type Client interface {
	// Models returns the ModelsAPI for interacting with the models.
	Models() ModelsAPI
	// ChatCompletions returns the ChatCompletionsAPI for interacting with chat completions.
	ChatCompletions() ChatCompletionsAPI
	// Completions returns the CompletionsAPI for interacting with completions.
	Completions() CompletionsAPI
	// Edits returns the EditsAPI for interacting with edits.
	Edits() EditsAPI
	// Images returns the ImagesAPI for interacting with images.
	Images() ImagesAPI
	// Embeddings returns the EmbeddingsAPI for interacting with embeddings.
	Embeddings() EmbeddingsAPI
	// Files returns the FilesAPI for interacting with files.
	Files() FilesAPI
	// FineTunes returns the FineTunesAPI for interacting with fine-tunes.
	FineTunes() FineTunesAPI
	// Moderations returns the ModerationsAPI for interacting with moderations.
	Moderations() ModerationsAPI
}

Client is the interface for interacting with the OpenAI API.

func New

func New(cfg Config) Client

New returns a new OpenAI client with the given configuration. If RequestTimeout is not set in the config, it will be set to defaultRequestTimeout.

type Completion

type Completion struct {
	// ID is the ID of the completion.
	ID string `json:"id"`
	// Created is the UNIX timestamp of when the completion was created.
	Created int `json:"created"`
	// Model is the ID of the model used to generate the completion.
	Model string `json:"model"`
	// Choices is a list of CompletionChoice structs representing
	// the different completions generated for the prompt.
	Choices []CompletionChoice `json:"choices"`
	// Usage is the token usage of the model.
	Usage TokenUsage `json:"usage"`
}

Completion represents the completion of a prompt generated by the API.

type CompletionChoice

type CompletionChoice struct {
	// Text is the generated completion.
	Text string `json:"text"`
	// Index is the index of the completion in the list of choices.
	Index int `json:"index"`
	// Logprobs is the LogProbabilities struct for the completion.
	Logprobs LogProbabilities `json:"logprobs"`
	// FinishReason is the reason why the completion was
	// stopped, such as "max_tokens".
	FinishReason string `json:"finish_reason"`
}

CompletionChoice represents a single completion for a given prompt.

type CompletionParams

type CompletionParams struct {
	// Model is the ID of the model to use for the completion.
	Model string `json:"model"`
	// Prompt is the prompt to generate a completion for.
	Prompt string `json:"prompt,omitempty"`
	// Suffix is the suffix to add to the end of the prompt
	// when generating a completion.
	Suffix string `json:"suffix,omitempty"`
	// MaxTokens is the maximum number of tokens to generate in the completion.
	MaxTokens int `json:"max_tokens,omitempty"`
	// Temperature is a value controlling the randomness of the
	// generated tokens, with higher values leading to more random completions.
	Temperature float64 `json:"temperature,omitempty"`
	// TopP is a value between 0 and 1 controlling the amount of diversity in
	// the generated completions, with higher values leading
	// to less diverse completions.
	TopP float64 `json:"top_p,omitempty"`
	// N is the number of completions to generate for the prompt.
	N int `json:"n,omitempty"`
	// Logprobs specifies if the log probabilities for each token in
	// the completion should be returned.
	Logprobs int `json:"logprobs,omitempty"`
	// Echo specifies if the prompt should be repeated in the returned text.
	Echo bool `json:"echo,omitempty"`
	// Stop is a string that, if encountered in the generated text,
	// will cause completion to stop.
	Stop string `json:"stop,omitempty"`
	// PresencePenalty is the penalty applied to log probabilities of
	// tokens that are not present in the prompt.
	PresencePenalty float64 `json:"presence_penalty,omitempty"`
	// FrequencyPenalty is the penalty applied to log probabilities based
	// on the token's frequency in the training data.
	FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`
	// BestOf specifies the number of best completions to keep, out
	// of all the generated completions.
	BestOf int `json:"best_of,omitempty"`
	// User is a string that can be used to specify a user id.
	User string `json:"user,omitempty"`
}

CompletionParams represents the parameters for generating a completion with the API.

type CompletionsAPI

type CompletionsAPI interface {
	// Create generates a new completion based on the given
	// CompletionParams and returns it as a Completion object.
	Create(CompletionParams) (Completion, error)
}

CompletionsAPI is an interface for creating completions.

type Config

type Config struct {
	APIKey         string
	OrganizationID string
	RequestTimeout time.Duration
}

Config holds the configuration values for the OpenAI client.

type DeletedFile

type DeletedFile struct {
	// ID is the identifier of the file
	ID string `json:"id"`
	// Deleted is whether or not the file was deleted successfully
	Deleted bool `json:"deleted"`
}

DeletedFile represents a file that has been deleted from the OpenAI API

type DeletedModel

type DeletedModel struct {
	// ID is the identifier of the model
	ID string `json:"id"`
	// Deleted is whether or not the model was deleted successfully
	Deleted bool `json:"deleted"`
}

DeletedModel represents a model that has been deleted from the OpenAI API

type Edit

type Edit struct {
	// Created is a timestamp of when the response was created.
	Created int `json:"created"`
	// Choices is a list of possible corrections for the input text.
	Choices []EditChoice `json:"choices"`
	// Usage contains information on the usage of OpenAI's API tokens.
	Usage TokenUsage `json:"usage"`
}

Edit represents a response from OpenAI's GPT-3 API for text correction requests.

type EditChoice

type EditChoice struct {
	// Text is the corrected text.
	Text string `json:"text"`
	// Index is the index of the corrected text.
	Index int `json:"index"`
}

EditChoice represents a possible correction for a piece of text provided by OpenAI's GPT-3 API.

type EditParams

type EditParams struct {
	// Model is the name of the language model to use.
	Model string `json:"model"`
	// Input is the text to be corrected.
	Input string `json:"input,omitempty"`
	// Instruction is a description of the type of correction
	// to perform on the input text.
	Instruction string `json:"instruction"`
	// N is the number of corrections to return.
	N int `json:"n,omitempty"`
	// Temperature is a value used to control the randomness of the response.
	Temperature float64 `json:"temperature,omitempty"`
	// TopP is a value used to control the diversity of the response.
	TopP float64 `json:"top_p,omitempty"`
}

EditParams represents the parameters for a text correction request to OpenAI's GPT-3 API.

type EditsAPI

type EditsAPI interface {
	// Create makes a text correction request to OpenAI's GPT-3 API
	// using the provided parameters.
	Create(EditParams) (Edit, error)
}

EditsAPI is an interface that provides methods for text correction with OpenAI's GPT-3 API.

type Embedding

type Embedding struct {
	// Embedding is the list of numbers that represent the embedding
	Embedding []float64 `json:"embedding"`
	// Model is the name of the model used to generate the embedding
	Model string `json:"model"`
	// Usage is the token usage metadata for the embedding
	Usage TokenUsage `json:"usage"`
}

Embedding represents an embedding generated by OpenAI's API

type EmbeddingParams

type EmbeddingParams struct {
	// Model is the name of the model to use for generating the embedding
	Model string `json:"model"`
	// Input is the text to generate an embedding for
	Input string `json:"input"`
	// User is an optional parameter for providing user metadata with the request
	User string `json:"user,omitempty"`
}

EmbeddingParams represents the parameters for generating an embedding

type EmbeddingsAPI

type EmbeddingsAPI interface {
	// Create generates an embedding for the given parameters
	Create(EmbeddingParams) (Embedding, error)
}

EmbeddingsAPI represents an interface for generating embeddings

type File

type File struct {
	// ID is the identifier of the file
	ID string `json:"id"`
	// Bytes is the number of bytes of the file
	Bytes int `json:"bytes"`
	// CreatedAt is a timestamp of when the file was created
	CreatedAt int `json:"created_at"`
	// Filename is the name of the file
	Filename string `json:"filename"`
	// Purpose is the purpose of the file
	Purpose string `json:"purpose"`
}

File represents a file in the OpenAI API

type FileParams

type FileParams struct {
	// File is the file content
	File string `mapstructure:"file"`
	// Purpose is the purpose of the file
	Purpose string `mapstructure:"purpose"`
}

FileParams contains the parameters to create a new file in the OpenAI API

type FilesAPI

type FilesAPI interface {
	// GetAll returns all the files in the OpenAI API
	GetAll() ([]File, error)
	// GetByID returns a file by its identifier
	GetByID(id string) (File, error)
	// Create creates a new file in the OpenAI API
	Create(FileParams) (File, error)
	// DeleteByID deletes a file by its identifier
	DeleteByID(id string) (DeletedFile, error)
	// DownloadByID downloads a file by its identifier
	DownloadByID(id string, dst io.Writer) error
}

FilesAPI represents the OpenAI API for managing files

type FineTune

type FineTune struct {
	// ID is the unique identifier for the fine-tuning task.
	ID string `json:"id"`
	// Model is the name of the OpenAI GPT-3 model that was fine-tuned.
	Model string `json:"model"`
	// CreatedAt is the timestamp when the fine-tuning task was created.
	CreatedAt int `json:"created_at"`
	// Events are the events that have taken place during the fine-tuning task.
	Events []FineTuneEvent `json:"events"`
	// FineTunedModel is the name of the fine-tuned model that was
	// created as a result of the fine-tuning task.
	FineTunedModel string `json:"fine_tuned_model"`
	// Hyperparams are the hyperparameters used during the fine-tuning task.
	Hyperparams FineTuneHyperparams `json:"hyperparams"`
	// OrganizationID is the ID of the organization that
	// created the fine-tuning task.
	OrganizationID string `json:"organization_id"`
	// ResultFiles are the files associated with the
	// results of the fine-tuning task.
	ResultFiles []File `json:"result_files"`
	// Status is the current status of the fine-tuning task.
	Status string `json:"status"`
	// ValidationFiles are the files used to validate the fine-tuning task.
	ValidationFiles []interface{} `json:"validation_files"`
	// TrainingFiles are the files used to train the fine-tuning task.
	TrainingFiles []File `json:"training_files"`
	// UpdatedAt is the timestamp when the fine-tuning task was last updated.
	UpdatedAt int `json:"updated_at"`
}

FineTune represents the information of a fine-tuning task.

type FineTuneEvent

type FineTuneEvent struct {
	// CreatedAt is the timestamp when the event took place.
	CreatedAt int `json:"created_at"`
	// Level is the severity level of the event.
	Level string `json:"level"`
	// Message is the description of the event.
	Message string `json:"message"`
}

FineTuneEvent represents a single event that has taken place during a fine-tuning task.

type FineTuneHyperparams

type FineTuneHyperparams struct {
	// BatchSize is the size of the batch used during the fine-tuning task.
	BatchSize int `json:"batch_size"`
	// LearningRateMultiplier is the learning rate multiplier used
	// during the fine-tuning task.
	LearningRateMultiplier float64 `json:"learning_rate_multiplier"`
	// NEpochs is the number of epochs used during the fine-tuning task.
	NEpochs int `json:"n_epochs"`
	// PromptLossWeight is the weight assigned to the
	// prompt loss during the fine-tuning task.
	PromptLossWeight float64 `json:"prompt_loss_weight"`
}

FineTuneHyperparams represents the hyperparameters used during a fine-tuning task.

type FineTuneParams

type FineTuneParams struct {
	// TrainingFile is the path to the training file.
	TrainingFile string `json:"training_file"`
	// ValidationFile is the path to the validation file.
	ValidationFile string `json:"validation_file,omitempty"`
	// Model is the identifier of the base model to be fine-tuned.
	Model string `json:"model,omitempty"`
	// NEpochs is the number of training epochs to be performed.
	NEpochs int `json:"n_epochs,omitempty"`
	// BatchSize is the number of samples per training iteration.
	BatchSize int `json:"batch_size,omitempty"`
	// LearningRateMultiplier is the multiplier applied to the learning rate.
	LearningRateMultiplier float64 `json:"learning_rate_multiplier,omitempty"`
	// PromptLossWeight is the weight applied to the prompt loss.
	PromptLossWeight float64 `json:"prompt_loss_weight,omitempty"`
	// ComputeClassificationMetrics indicates whether to compute
	// classification metrics.
	ComputeClassificationMetrics bool `json:"compute_classification_metrics,omitempty"`
	// ClassificationNClasses is the number of classes in the
	// classification task.
	ClassificationNClasses int `json:"classification_n_classes,omitempty"`
	// ClassificationPositiveClass is the positive class label in
	// the classification task.
	ClassificationPositiveClass string `json:"classification_positive_class,omitempty"`
	// ClassificationBetas are the betas for Fbeta metrics computation.
	ClassificationBetas []interface{} `json:"classification_betas,omitempty"`
	// Suffix is an optional string to be appended to the
	// fine-tuned model identifier.
	Suffix string `json:"suffix,omitempty"`
}

FineTuneParams defines the parameters required to create a fine-tune task.

type FineTunesAPI

type FineTunesAPI interface {
	// GetAll retrieves all the fine-tuning models available.
	GetAll() ([]FineTune, error)
	// GetByID retrieves a specific fine-tuning model based on its ID.
	GetByID(id string) (FineTune, error)
	// Create creates a new fine-tuning model.
	Create(FineTuneParams) (FineTune, error)
	// Cancel cancels a specific fine-tuning model based on its ID.
	Cancel(id string) (FineTune, error)
	// GetEvents retrieves all the events of a specific
	// fine-tuning model based on its ID.
	GetEvents(fineTuneID string) ([]FineTuneEvent, error)
}

FineTunesAPI represents the interface for managing fine-tuning models in OpenAI GPT.

type Image

type Image struct {
	// URL is the URL of the image.
	URL string `json:"url,omitempty"`
	// B64JSON is the Base64 encoded string of the image.
	B64JSON string `json:"b64_json,omitempty"`
}

Image represents a single image in response from the OpenAI API.

type ImageEditParams

type ImageEditParams struct {
	// Image is the image to edit.
	Image string `mapstructure:"image"`
	// Mask is the image to use as a mask for the edit.
	Mask string `mapstructure:"mask,omitempty"`
	// Prompt is the prompt text used to edit the images.
	Prompt string `mapstructure:"prompt"`
	// N is the number of images to generate.
	N uint `mapstructure:"n,omitempty"`
	// Size is the size of the images.
	Size ImageSize `mapstructure:"size,omitempty"`
	// ResponseFormat is the format of the image response.
	ResponseFormat ImageResponseFormat `mapstructure:"response_format,omitempty"`
	// User is the name of the user.
	User string `mapstructure:"user,omitempty"`
}

ImageEditParams are the parameters for editing existing images.

type ImageGenerationParams

type ImageGenerationParams struct {
	// Prompt is the prompt text used to generate the images.
	Prompt string `json:"prompt"`
	// N is the number of images to generate.
	N uint `json:"n"`
	// Size is the size of the images.
	Size ImageSize `json:"size"`
	// ResponseFormat is the format of the image response.
	ResponseFormat ImageResponseFormat `json:"response_format"`
	// User is the name of the user.
	User string `json:"user"`
}

ImageGenerationParams are the parameters for generating new images.

type ImageResponseFormat

type ImageResponseFormat string

ImageResponseFormat is a type that defines the format of image response.

const (
	ImageResponseFormatURL     ImageResponseFormat = "url"
	ImageResponseFormatB64JSON ImageResponseFormat = "b64_json"
)

Constants for different types of ImageResponseFormat

type ImageSize

type ImageSize string

ImageSize is a type that defines the size of the image.

const (
	ImageSize256x256   ImageSize = "256x256"
	ImageSize512x512   ImageSize = "512x512"
	ImageSize1024x1024 ImageSize = "1024x1024"
)

Constants for different types of ImageSize

type ImageVariationParams

type ImageVariationParams struct {
	// Image is the image to generate variations from.
	Image string `mapstructure:"image"`
	// N is the number of images to generate.
	N uint `mapstructure:"n,omitempty"`
	// Size is the size of the images.
	Size ImageSize `mapstructure:"size,omitempty"`
	// ResponseFormat is the format of the image response.
	ResponseFormat ImageResponseFormat `mapstructure:"response_format,omitempty"`
	// User is an optional field that allows to specify a
	// user identifier for the API request.
	User string `mapstructure:"user,omitempty"`
}

ImageVariationParams are the parameters for generating variations of existing images.

type ImagesAPI

type ImagesAPI interface {
	// Create generates new images based on the given prompt.
	Create(ImageGenerationParams) ([]Image, error)
	// Edit modifies an existing image based on the given prompt and mask.
	Edit(ImageEditParams) ([]Image, error)
	// CreateVariations generates variations of an existing image.
	CreateVariations(ImageVariationParams) ([]Image, error)
}

ImagesAPI is an interface that defines the methods for generating and manipulating images with OpenAI's API.

type LogProbabilities

type LogProbabilities struct {
	// TextOffset represents the text offsets of each token in the prompt.
	TextOffset []int `json:"text_offset"`
	// TokenLogprobs is an array of log-probabilities of each generated token.
	TokenLogprobs []float64 `json:"token_logprobs"`
	// Tokens is an array of generated tokens.
	Tokens []string `json:"tokens"`
	// TopLogprobs is an array of dictionaries, each containing the
	// log-probabilities of the top-k completions for each position in the prompt.
	TopLogprobs []map[string]float64 `json:"top_logprobs"`
}

LogProbabilities represents the log-probabilities of generated tokens and the text offsets of each token in the prompt.

type LogitBias added in v1.2.0

type LogitBias map[string]interface{}

LogitBias is a type alias for a map with string keys and interface{} values, used to specify logit bias in the completion request.

type Model

type Model struct {
	// ID is the unique identifier for the model.
	ID string `json:"id"`
	// OwnedBy is the name of the user or organization that owns the model.
	OwnedBy string `json:"owned_by"`
	// Created is the timestamp indicating when the model was created.
	Created uint `json:"created"`
	// Root is the root model in the lineage of the model.
	Root string `json:"root"`
	// Parent is the parent model in the lineage of the model.
	Parent interface{} `json:"parent"`
	// Permission is a slice of ModelPermission objects
	// representing the permissions on the model.
	Permission []ModelPermission `json:"permission"`
}

Model represents information about an OpenAI model.

type ModelPermission

type ModelPermission struct {
	// ID is the unique identifier for the model permission.
	ID string `json:"id"`
	// Created is the timestamp indicating when the permission was created.
	Created uint `json:"created"`
	// AllowCreateEngine represents the permission to
	// create engines for the model.
	AllowCreateEngine bool `json:"allow_create_engine"`
	// AllowSampling represents the permission to sample the model.
	AllowSampling bool `json:"allow_sampling"`
	// AllowLogprobs represents the permission to retrieve
	// log probabilities from the model.
	AllowLogprobs bool `json:"allow_logprobs"`
	// AllowSearchIndices represents the permission to
	// search the indices of the model.
	AllowSearchIndices bool `json:"allow_search_indices"`
	// AllowView represents the permission to view the model's metadata.
	AllowView bool `json:"allow_view"`
	// AllowFineTuning represents the permission to fine-tune the model.
	AllowFineTuning bool `json:"allow_fine_tuning"`
	// Organization is the name of the organization that owns the model.
	Organization string `json:"organization"`
	// Group is the group that the model belongs to.
	Group interface{} `json:"group"`
	// IsBlocking indicates whether this permission blocks other permissions.
	IsBlocking bool `json:"is_blocking"`
}

ModelPermission represents a permission a user has on an OpenAI model.

type ModelsAPI

type ModelsAPI interface {
	// GetAll returns all available models.
	GetAll() ([]Model, error)
	// GetByID returns the model with the specified ID.
	GetByID(id string) (Model, error)
	// DeleteByID deletes a model by its identifier
	DeleteByID(id string) (DeletedModel, error)
}

ModelsAPI is the interface for the OpenAI models API.

type Moderation

type Moderation struct {
	// ID is the identifier of the moderation.
	ID string `json:"id"`
	// Model is the name of the model that was used for the moderation.
	Model string `json:"model"`
	// Results contains the moderation result for each individual prompt.
	Results []ModerationResult `json:"results"`
}

Moderation represents the response of moderation API. It contains the moderation ID, the used model and the moderation results.

type ModerationParams

type ModerationParams struct {
	// Input is the text input to be moderated
	Input string `json:"input"`
	// Model is the name of the model to be used for moderation
	Model string `json:"model,omitempty"`
}

ModerationParams represents the parameters to use for moderation

type ModerationResult

type ModerationResult struct {
	// Categories represents the different moderation categories.
	Categories ModerationResultCategories `json:"categories"`
	// CategoryScores represents the scores of the different
	// moderation categories.
	CategoryScores ModerationResultCategoryScores `json:"category_scores"`
	// Flagged indicates whether the prompt is flagged by the model or not.
	Flagged bool `json:"flagged"`
}

ModerationResult represents the moderation result for an individual prompt. It contains the moderation categories, category scores and whether the prompt is flagged or not.

type ModerationResultCategories

type ModerationResultCategories struct {
	// Hate indicates whether the prompt contains hate content.
	Hate bool `json:"hate"`
	// HateThreatening indicates whether the prompt contains
	// hate threatening content.
	HateThreatening bool `json:"hate/threatening"`
	// SelfHarm indicates whether the prompt contains self-harm content.
	SelfHarm bool `json:"self-harm"`
	// Sexual indicates whether the prompt contains sexual content.
	Sexual bool `json:"sexual"`
	// SexualMinors indicates whether the prompt contains
	// sexual content with minors.
	SexualMinors bool `json:"sexual/minors"`
	// Violence indicates whether the prompt contains violent content.
	Violence bool `json:"violence"`
	// ViolenceGraphic indicates whether the prompt contains
	// graphic violent content.
	ViolenceGraphic bool `json:"violence/graphic"`
}

ModerationResultCategories represents the different moderation categories for a prompt.

type ModerationResultCategoryScores

type ModerationResultCategoryScores struct {
	// Hate is the score for the hate category.
	Hate float64 `json:"hate"`
	// HateThreatening is the score for the hate threatening category.
	HateThreatening float64 `json:"hate/threatening"`
	// SelfHarm is the score for the self-harm category.
	SelfHarm float64 `json:"self-harm"`
	// Sexual is the score for the sexual category.
	Sexual float64 `json:"sexual"`
	// SexualMinors is the score for the sexual with minors category.
	SexualMinors float64 `json:"sexual/minors"`
	// Violence is the score for the violent category.
	Violence float64 `json:"violence"`
	// ViolenceGraphic is the score for the graphic violent category.
	ViolenceGraphic float64 `json:"violence/graphic"`
}

ModerationResultCategoryScores represents the scores of the different moderation categories for a prompt.

type ModerationsAPI

type ModerationsAPI interface {
	Create(ModerationParams) (Moderation, error)
}

ModerationsAPI is the interface for the OpenAI moderations API.

type TokenUsage

type TokenUsage struct {
	// PromptTokens is the number of tokens in the prompt text.
	PromptTokens int `json:"prompt_tokens"`
	// CompletionTokens is the number of tokens generated by the completion request.
	CompletionTokens int `json:"completion_tokens"`
	// TotalTokens is the sum of prompt tokens and completion tokens.
	TotalTokens int `json:"total_tokens"`
}

TokenUsage represents the usage of tokens for a GPT-3 completion request.

Jump to

Keyboard shortcuts

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