openai

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2023 License: MIT Imports: 8 Imported by: 0

README

OpenAI Go Client

Installation

go get github.com/KirillMironov/openai

Usage

package main

import (
	"context"
	"log"
	"os"
	"time"

	"github.com/KirillMironov/openai"
)

func main() {
	apiKey := os.Getenv("OPENAI_API_KEY")

	client := openai.NewClient(apiKey, openai.WithTimeout(time.Second*20))

	completion, err := client.Completion(context.Background(), openai.CompletionRequest{
		Model:     "text-davinci-003",
		Prompt:    []string{"Example prompt"},
		MaxTokens: 100,
	})
	if err != nil {
		log.Fatal(err)
	}

	log.Println(completion.Choices[0].Text)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ChatCompletionRequest added in v0.2.0

type ChatCompletionRequest struct {
	Model            string                         `json:"model"`
	Messages         []ChatCompletionRequestMessage `json:"messages"`
	Temperature      float64                        `json:"temperature,omitempty"`
	TopP             float64                        `json:"top_p,omitempty"`
	N                int                            `json:"n,omitempty"`
	Stream           bool                           `json:"stream,omitempty"`
	Stop             []string                       `json:"stop,omitempty"`
	MaxTokens        int                            `json:"max_tokens,omitempty"`
	PresencePenalty  float64                        `json:"presence_penalty,omitempty"`
	FrequencyPenalty float64                        `json:"frequency_penalty,omitempty"`
	LogitBias        map[string]int                 `json:"logit_bias,omitempty"`
	User             string                         `json:"user,omitempty"`
}

type ChatCompletionRequestMessage added in v0.2.0

type ChatCompletionRequestMessage struct {
	Role    ChatRole `json:"role"`
	Content string   `json:"content"`
	Name    string   `json:"name,omitempty"`
}

type ChatCompletionResponse added in v0.2.0

type ChatCompletionResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int    `json:"created"`
	Model   string `json:"model"`
	Choices []struct {
		Index        int                           `json:"index"`
		Message      ChatCompletionResponseMessage `json:"message"`
		FinishReason string                        `json:"finish_reason"`
	} `json:"choices"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

type ChatCompletionResponseMessage added in v0.2.0

type ChatCompletionResponseMessage struct {
	Role    ChatRole `json:"role"`
	Content string   `json:"content"`
}

type ChatRole added in v0.2.0

type ChatRole string
const (
	ChatRoleSystem    ChatRole = "system"
	ChatRoleUser      ChatRole = "user"
	ChatRoleAssistant ChatRole = "assistant"
)

type Client

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

func NewClient

func NewClient(apiKey string, options ...ClientOption) *Client

func (*Client) CancelFineTune

func (c *Client) CancelFineTune(ctx context.Context, id string) (FineTune, error)

CancelFineTune immediately cancel a fine-tune job.

func (*Client) ChatCompletion added in v0.2.0

func (c *Client) ChatCompletion(ctx context.Context, request ChatCompletionRequest) (ChatCompletionResponse, error)

ChatCompletion creates a completion for the chat message.

func (*Client) Completion

func (c *Client) Completion(ctx context.Context, request CompletionRequest) (CompletionResponse, error)

Completion creates a completion for the provided prompt and parameters.

func (*Client) CreateFineTune

func (c *Client) CreateFineTune(ctx context.Context, request FineTuneRequest) (FineTune, error)

CreateFineTune creates a job that fine-tunes a specified model from a given dataset.

func (*Client) DeleteFile

func (c *Client) DeleteFile(ctx context.Context, id string) (DeleteFileResponse, error)

DeleteFile deletes a file.

func (*Client) DeleteModel

func (c *Client) DeleteModel(ctx context.Context, id string) (DeleteModelResponse, error)

DeleteModel delete a fine-tuned model. You must have the Owner role in your organization.

func (*Client) Edit

func (c *Client) Edit(ctx context.Context, request EditRequest) (EditResponse, error)

Edit creates a new edit for the provided input, instruction, and parameters.

func (*Client) Embedding

func (c *Client) Embedding(ctx context.Context, request EmbeddingRequest) (EmbeddingResponse, error)

Embedding creates an embedding vector representing the input text.

func (*Client) File

func (c *Client) File(ctx context.Context, id string) (File, error)

File returns information about a specific file.

func (*Client) FileContent

func (c *Client) FileContent(ctx context.Context, id string) (string, error)

FileContent returns the contents of the specified file.

func (*Client) Files

func (c *Client) Files(ctx context.Context) (FilesResponse, error)

Files returns a list of files that belong to the user's organization.

func (*Client) FineTune

func (c *Client) FineTune(ctx context.Context, id string) (FineTune, error)

FineTune gets info about the fine-tune job.

func (*Client) FineTuneEvents

func (c *Client) FineTuneEvents(ctx context.Context, id string) (FineTuneEventsResponse, error)

FineTuneEvents get fine-grained status updates for a fine-tune job.

func (*Client) FineTunes

func (c *Client) FineTunes(ctx context.Context) (FineTunesResponse, error)

FineTunes list your organization's fine-tuning jobs.

func (*Client) Image

func (c *Client) Image(ctx context.Context, request ImageRequest) (ImageResponse, error)

Image given a prompt and/or an input image, the model will generate a new image.

func (*Client) ImageEdit

func (c *Client) ImageEdit(ctx context.Context, request ImageEditRequest) (ImageEditResponse, error)

ImageEdit creates an edited or extended image given an original image and a prompt.

func (*Client) ImageVariation

func (c *Client) ImageVariation(ctx context.Context, request ImageVariationRequest) (ImageVariationResponse, error)

ImageVariation creates a variation of a given image.

func (*Client) Model

func (c *Client) Model(ctx context.Context, id string) (Model, error)

Model retrieves a model instance, providing basic information about the model such as the owner and permissioning.

func (*Client) Models

func (c *Client) Models(ctx context.Context) (ModelsResponse, error)

Models lists the currently available models, and provides basic information about each one such as the owner and availability.

func (*Client) Moderation

func (c *Client) Moderation(ctx context.Context, request ModerationRequest) (ModerationResponse, error)

Moderation classifies if text violates OpenAI's Content Policy

func (*Client) Transcription added in v0.2.0

func (c *Client) Transcription(ctx context.Context, request TranscriptionRequest) (TranscriptionResponse, error)

Transcription transcribes audio into the input language.

func (*Client) Translation added in v0.2.0

func (c *Client) Translation(ctx context.Context, request TranslationRequest) (TranslationResponse, error)

Translation translates audio into English.

func (*Client) UploadFile

func (c *Client) UploadFile(ctx context.Context, request UploadFileRequest) (File, error)

UploadFile upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB.

type ClientOption

type ClientOption func(*Client)

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

func WithOrganization

func WithOrganization(organization string) ClientOption

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

type CompletionRequest

type CompletionRequest struct {
	Model            string         `json:"model"`
	Prompt           []string       `json:"prompt,omitempty"`
	Suffix           string         `json:"suffix,omitempty"`
	MaxTokens        int            `json:"max_tokens,omitempty"`
	Temperature      float64        `json:"temperature,omitempty"`
	TopP             float64        `json:"top_p,omitempty"`
	N                int            `json:"n,omitempty"`
	Stream           bool           `json:"stream,omitempty"`
	Logprobs         int            `json:"logprobs,omitempty"`
	Echo             bool           `json:"echo,omitempty"`
	Stop             []string       `json:"stop,omitempty"`
	PresencePenalty  float64        `json:"presence_penalty,omitempty"`
	FrequencyPenalty float64        `json:"frequency_penalty,omitempty"`
	BestOf           int            `json:"best_of,omitempty"`
	LogitBias        map[string]int `json:"logit_bias,omitempty"`
	User             string         `json:"user,omitempty"`
}

type CompletionResponse

type CompletionResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int    `json:"created"`
	Model   string `json:"model"`
	Choices []struct {
		Text     string `json:"text"`
		Index    int    `json:"index"`
		Logprobs struct {
			Tokens        []string             `json:"tokens"`
			TokenLogprobs []float64            `json:"token_logprobs"`
			TopLogprobs   []map[string]float64 `json:"top_logprobs"`
			TextOffset    []int                `json:"text_offset"`
		} `json:"logprobs"`
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

type DeleteFileResponse

type DeleteFileResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
}

type DeleteModelResponse

type DeleteModelResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
}

type EditRequest

type EditRequest struct {
	Model       string  `json:"model"`
	Input       string  `json:"input,omitempty"`
	Instruction string  `json:"instruction"`
	N           int     `json:"n,omitempty"`
	Temperature float64 `json:"temperature,omitempty"`
	TopP        float64 `json:"top_p,omitempty"`
}

type EditResponse

type EditResponse struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int    `json:"created"`
	Model   string `json:"model"`
	Choices []struct {
		Text     string `json:"text"`
		Index    int    `json:"index"`
		Logprobs struct {
			Tokens        []string             `json:"tokens"`
			TokenLogprobs []float64            `json:"token_logprobs"`
			TopLogprobs   []map[string]float64 `json:"top_logprobs"`
			TextOffset    []int                `json:"text_offset"`
		} `json:"logprobs"`
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

type EmbeddingRequest

type EmbeddingRequest struct {
	Model string   `json:"model"`
	Input []string `json:"input"`
	User  string   `json:"user,omitempty"`
}

type EmbeddingResponse

type EmbeddingResponse struct {
	Object string `json:"object"`
	Model  string `json:"model"`
	Data   []struct {
		Index     int       `json:"index"`
		Object    string    `json:"object"`
		Embedding []float64 `json:"embedding"`
	} `json:"data"`
	Usage struct {
		PromptTokens int `json:"prompt_tokens"`
		TotalTokens  int `json:"total_tokens"`
	} `json:"usage"`
}

type Error

type Error struct {
	StatusCode int    `json:"-"`
	Message    string `json:"message"`
	Type       string `json:"type"`
}

func (Error) Error

func (e Error) Error() string

type File

type File struct {
	ID            string         `json:"id"`
	Object        string         `json:"object"`
	Bytes         int            `json:"bytes"`
	CreatedAt     int            `json:"created_at"`
	Filename      string         `json:"filename"`
	Purpose       string         `json:"purpose"`
	Status        string         `json:"status"`
	StatusDetails map[string]any `json:"status_details"`
}

type FilesResponse

type FilesResponse struct {
	Object string `json:"object"`
	Data   []File `json:"data"`
}

type FineTune

type FineTune struct {
	ID              string          `json:"id"`
	Object          string          `json:"object"`
	CreatedAt       int             `json:"created_at"`
	UpdatedAt       int             `json:"updated_at"`
	Model           string          `json:"model"`
	FineTunedModel  string          `json:"fine_tuned_model"`
	OrganizationID  string          `json:"organization_id"`
	Status          string          `json:"status"`
	Hyperparams     map[string]any  `json:"hyperparams"`
	TrainingFiles   []File          `json:"training_files"`
	ValidationFiles []File          `json:"validation_files"`
	ResultFiles     []File          `json:"result_files"`
	Events          []FineTuneEvent `json:"events"`
}

type FineTuneEvent

type FineTuneEvent struct {
	Object    string `json:"object"`
	CreatedAt int    `json:"created_at"`
	Level     string `json:"level"`
	Message   string `json:"message"`
}

type FineTuneEventsResponse

type FineTuneEventsResponse struct {
	Object string          `json:"object"`
	Data   []FineTuneEvent `json:"data"`
}

type FineTuneRequest

type FineTuneRequest struct {
	TrainingFile                 string    `json:"training_file"`
	ValidationFile               string    `json:"validation_file,omitempty"`
	Model                        string    `json:"model,omitempty"`
	NEpochs                      int       `json:"n_epochs,omitempty"`
	BatchSize                    int       `json:"batch_size,omitempty"`
	LearningRateMultiplier       float64   `json:"learning_rate_multiplier,omitempty"`
	PromptLossWeight             float64   `json:"prompt_loss_weight,omitempty"`
	ComputeClassificationMetrics bool      `json:"compute_classification_metrics,omitempty"`
	ClassificationNClasses       int       `json:"classification_n_classes,omitempty"`
	ClassificationPositiveClass  string    `json:"classification_positive_class,omitempty"`
	ClassificationBetas          []float64 `json:"classification_betas,omitempty"`
	Suffix                       string    `json:"suffix,omitempty"`
}

type FineTunesResponse

type FineTunesResponse struct {
	Object string     `json:"object"`
	Data   []FineTune `json:"data"`
}

type ImageEditRequest

type ImageEditRequest struct {
	Image          formdata.File       `form:"image"`
	Mask           formdata.File       `form:"mask,omitempty"`
	Prompt         string              `form:"prompt"`
	N              int                 `form:"n,omitempty"`
	Size           ImageSize           `form:"size,omitempty"`
	ResponseFormat ImageResponseFormat `form:"response_format,omitempty"`
	User           string              `form:"user,omitempty"`
}

type ImageEditResponse

type ImageEditResponse struct {
	Created int `json:"created"`
	Data    []struct {
		URL     string `json:"url"`
		B64JSON string `json:"b64_json"`
	} `json:"data"`
}

type ImageRequest

type ImageRequest struct {
	Prompt         string              `json:"prompt"`
	N              int                 `json:"n,omitempty"`
	Size           ImageSize           `json:"size,omitempty"`
	ResponseFormat ImageResponseFormat `json:"response_format,omitempty"`
	User           string              `json:"user,omitempty"`
}

type ImageResponse

type ImageResponse struct {
	Created int `json:"created"`
	Data    []struct {
		URL     string `json:"url"`
		B64JSON string `json:"b64_json"`
	} `json:"data"`
}

type ImageResponseFormat

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

type ImageSize

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

type ImageVariationRequest

type ImageVariationRequest struct {
	Image          formdata.File       `form:"image"`
	N              int                 `form:"n,omitempty"`
	Size           ImageSize           `form:"size,omitempty"`
	ResponseFormat ImageResponseFormat `form:"response_format,omitempty"`
	User           string              `form:"user,omitempty"`
}

type ImageVariationResponse

type ImageVariationResponse struct {
	Created int `json:"created"`
	Data    []struct {
		URL     string `json:"url"`
		B64JSON string `json:"b64_json"`
	} `json:"data"`
}

type Model

type Model struct {
	ID      string `json:"id"`
	Object  string `json:"object"`
	Created int    `json:"created"`
	OwnedBy string `json:"owned_by"`
}

type ModelsResponse

type ModelsResponse struct {
	Object string  `json:"object"`
	Data   []Model `json:"data"`
}

type ModerationRequest

type ModerationRequest struct {
	Input []string `json:"input"`
	Model string   `json:"model,omitempty"`
}

type ModerationResponse

type ModerationResponse struct {
	ID      string `json:"id"`
	Model   string `json:"model"`
	Results []struct {
		Flagged    bool `json:"flagged"`
		Categories struct {
			Hate            bool `json:"hate"`
			HateThreatening bool `json:"hate/threatening"`
			SelfHarm        bool `json:"self-harm"`
			Sexual          bool `json:"sexual"`
			SexualMinors    bool `json:"sexual/minors"`
			Violence        bool `json:"violence"`
			ViolenceGraphic bool `json:"violence/graphic"`
		} `json:"categories"`
		CategoryScores struct {
			Hate            float64 `json:"hate"`
			HateThreatening float64 `json:"hate/threatening"`
			SelfHarm        float64 `json:"self-harm"`
			Sexual          float64 `json:"sexual"`
			SexualMinors    float64 `json:"sexual/minors"`
			Violence        float64 `json:"violence"`
			ViolenceGraphic float64 `json:"violence/graphic"`
		} `json:"category_scores"`
	} `json:"results"`
}

type TranscriptionRequest added in v0.2.0

type TranscriptionRequest struct {
	File           formdata.File               `form:"file"`
	Model          string                      `json:"model"`
	Prompt         string                      `json:"prompt,omitempty"`
	ResponseFormat TranscriptionResponseFormat `json:"response_format,omitempty"`
	Temperature    float64                     `json:"temperature,omitempty"`
	Language       string                      `json:"language,omitempty"`
}

type TranscriptionResponse added in v0.2.0

type TranscriptionResponse struct {
	Text string `json:"text"`
}

type TranscriptionResponseFormat added in v0.2.0

type TranscriptionResponseFormat string
const (
	TranscriptionResponseFormatJSON        TranscriptionResponseFormat = "json"
	TranscriptionResponseFormatText        TranscriptionResponseFormat = "text"
	TranscriptionResponseFormatSRT         TranscriptionResponseFormat = "srt"
	TranscriptionResponseFormatVerboseJSON TranscriptionResponseFormat = "verbose_json"
	TranscriptionResponseFormatVTT         TranscriptionResponseFormat = "vtt"
)

type TranslationRequest added in v0.2.0

type TranslationRequest struct {
	File           formdata.File             `form:"file"`
	Model          string                    `json:"model"`
	Prompt         string                    `json:"prompt,omitempty"`
	ResponseFormat TranslationResponseFormat `json:"response_format,omitempty"`
	Temperature    float64                   `json:"temperature,omitempty"`
}

type TranslationResponse added in v0.2.0

type TranslationResponse struct {
	Text string `json:"text"`
}

type TranslationResponseFormat added in v0.2.0

type TranslationResponseFormat string
const (
	TranslationResponseFormatJSON        TranslationResponseFormat = "json"
	TranslationResponseFormatText        TranslationResponseFormat = "text"
	TranslationResponseFormatSRT         TranslationResponseFormat = "srt"
	TranslationResponseFormatVerboseJSON TranslationResponseFormat = "verbose_json"
	TranslationResponseFormatVTT         TranslationResponseFormat = "vtt"
)

type UploadFileRequest

type UploadFileRequest struct {
	File    formdata.File `form:"file"`
	Purpose string        `form:"purpose"`
}

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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