Documentation
¶
Overview ¶
Package gopenai provides Go bindings for the OpenAI API.
Index ¶
- Variables
- type ChatCompletion
- type ChatCompletionChoice
- type ChatCompletionMessage
- type ChatCompletionMessageRole
- type ChatCompletionParams
- type ChatCompletionsAPI
- type Client
- type Completion
- type CompletionChoice
- type CompletionParams
- type CompletionsAPI
- type Config
- type DeletedFile
- type DeletedModel
- type Edit
- type EditChoice
- type EditParams
- type EditsAPI
- type Embedding
- type EmbeddingParams
- type EmbeddingsAPI
- type File
- type FileParams
- type FilesAPI
- type FineTune
- type FineTuneEvent
- type FineTuneHyperparams
- type FineTuneParams
- type FineTunesAPI
- type Image
- type ImageEditParams
- type ImageGenerationParams
- type ImageResponseFormat
- type ImageSize
- type ImageVariationParams
- type ImagesAPI
- type LogProbabilities
- type LogitBias
- type Model
- type ModelPermission
- type ModelsAPI
- type Moderation
- type ModerationParams
- type ModerationResult
- type ModerationResultCategories
- type ModerationResultCategoryScores
- type ModerationsAPI
- type TokenUsage
Constants ¶
This section is empty.
Variables ¶
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.
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 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 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.