openai

package module
v0.0.0-...-ed23b36 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2023 License: Apache-2.0 Imports: 12 Imported by: 0

README

README

Introduction

This is a Go client for the OpenAI API. It provides a simple interface for accessing the OpenAI API, including functions for uploading files, fine-tuning models, and moderating text. To use this client, you will need an OpenAI API key. You can obtain an API key by signing up for the OpenAI API at https://beta.openai.com/signup/. Once you have an API key, you can use this client to access the OpenAI API and build powerful AI applications.

OpenAI Golang SDK

This is a Golang SDK for the OpenAI API. It provides a simple interface for accessing the various OpenAI API endpoints.

Installation

To install the SDK, simply run:

go get github.com/neoguojing/openai

Usage

To use the SDK, you will need an API key from OpenAI. You can obtain an API key by signing up for an account on the OpenAI website.

Once you have an API key, you can create a new instance of the OpenAI struct:

import "github.com/neoguojing/openai"

openai := openai.NewOpenAI("your-api-key")

You can then use the various methods provided by the SDK to interact with the OpenAI API.

Examples

Here are some examples of how to use the SDK:

// Retrieve a list of available models
modelList, err := openai.Model().List()
if err != nil {
    log.Fatal(err)
}
fmt.Println(modelList)

// Generate completions for a given prompt
completions, err := openai.Completions("Hello, world!", 5)
if err != nil {
    log.Fatal(err)
}
fmt.Println(completions)

// Generate an image from a given prompt
image, err := openai.Image().Generate("A cute cat", 1, "512x512")
if err != nil {
    log.Fatal(err)
}
fmt.Println(image)

Contributing

Contributions are welcome! If you find a bug or have a feature request, please open an issue on the GitHub repository.

License

This SDK is licensed under the Apache License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Audio

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

func (*Audio) Transcriptions

func (o *Audio) Transcriptions(filePath string) (*AudioResponse, error)

func (*Audio) TranscriptionsDirect

func (o *Audio) TranscriptionsDirect(filePath string, input io.Reader) (*AudioResponse, error)

func (*Audio) Translations

func (o *Audio) Translations(filePath string) (*AudioResponse, error)

func (*Audio) TranslationsDirect

func (o *Audio) TranslationsDirect(filePath string, input io.Reader) (*AudioResponse, error)

type AudioResponse

type AudioResponse struct {
	// Text is the text used to generate the audio.
	Text string `json:"text"`
}

AudioResponse represents a response to generate audio.

type Chat

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

func (*Chat) Complete

func (c *Chat) Complete(content string) (*ChatResponse, error)

func (*Chat) Dialogue

func (c *Chat) Dialogue(media models.MediaType, text string, filePath string,
	reader io.Reader) (string, error)

func (*Chat) Edits

func (c *Chat) Edits(content string, instruction string) (*EditChatResponse, error)

func (*Chat) Prepare

func (c *Chat) Prepare(roleName string) *Chat

func (*Chat) Recorder

func (c *Chat) Recorder(media models.MediaType, text string, filePath string,
	reader io.Reader) error

type ChatOption

type ChatOption func(*Chat)

func WithChatModel

func WithChatModel(model string) ChatOption

func WithPlatform

func WithPlatform(p models.Platform) ChatOption

func WithProxy

func WithProxy(proxyURL string) ChatOption

func WithRole

func WithRole(role OpenAIRole) ChatOption

type ChatRequest

type ChatRequest struct {
	// Model is the ID of the model to use for generating the chat response.
	Model string `json:"model"`
	// Messages is an array of messages in the chat.
	Messages []struct {
		// Role is the role of the message sender (system, user, or assistant).
		Role string `json:"role"`
		// Content is the content of the message.
		Content string `json:"content"`
	} `json:"messages"`
}

ChatRequest represents a request to generate a chat response.

type ChatResponse

type ChatResponse struct {
	// ID is the ID of the response.
	ID string `json:"id"`
	// Object is the type of object for the response.
	Object string `json:"object"`
	// Created is the timestamp for when the response was created.
	Created int `json:"created"`
	// Choices is an array of choices for text completion.
	Choices []struct {
		// Index is the index of the choice.
		Index int `json:"index"`
		// Message is the message object for the choice.
		Message struct {
			// Role is the role of the message sender (system, user, or assistant).
			Role string `json:"role"`
			// Content is the content of the message.
			Content string `json:"content"`
		} `json:"message"`
		// FinishReason is the reason for finishing the choice.
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
	// Usage is the usage statistics for the response.
	Usage struct {
		// PromptTokens is the number of tokens in the prompt.
		PromptTokens int `json:"prompt_tokens"`
		// CompletionTokens is the number of tokens in the completion.
		CompletionTokens int `json:"completion_tokens"`
		// TotalTokens is the total number of tokens.
		TotalTokens int `json:"total_tokens"`
	} `json:"usage"`
}

ChatResponse represents a response to generate a chat response.

func (*ChatResponse) GetContent

func (r *ChatResponse) GetContent(options ...ChatResponseOption) (string, error)

CheckChatResponse checks if the chat response is valid.

type ChatResponseOption

type ChatResponseOption func(*ChatResponse)

func WithContentLengthLimit

func WithContentLengthLimit(length int) ChatResponseOption

type CompletionRequest

type CompletionRequest struct {
	// Model is the ID of the model to use for text completion.
	Model string `json:"model"`
	// Prompt is the text prompt to use for text completion.
	Prompt string `json:"prompt"`
	// MaxTokens is the maximum number of tokens to generate in the completion.
	MaxTokens int `json:"max_tokens"`
	// Temperature is the sampling temperature to use for text completion.
	Temperature float64 `json:"temperature"`
	// TopP is the top-p sampling cutoff to use for text completion.
	TopP float64 `json:"top_p"`
	// N is the number of completions to generate.
	N int `json:"n"`
	// Stream specifies whether to stream the response or wait for the entire response.
	Stream bool `json:"stream"`
	// Logprobs specifies the number of log probabilities to generate.
	Logprobs int `json:"logprobs"`
	// Stop is the stop sequence to use for text completion.
	Stop string `json:"stop"`
}

CompletionRequest represents a request to generate text completion.

type CompletionResponse

type CompletionResponse struct {
	// Choices is an array of choices for text completion.
	Choices []struct {
		// Text is the generated text for the choice.
		Text string `json:"text"`
		// Index is the index of the choice.
		Index int `json:"index"`
		// Logprobs is the log probabilities for the choice.
		Logprobs interface{} `json:"logprobs"`
		// FinishReason is the reason for finishing the choice.
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
	// Created is the timestamp for when the response was created.
	Created int `json:"created"`
	// ID is the ID of the response.
	ID string `json:"id"`
	// Model is the ID of the model used for text completion.
	Model string `json:"model"`
	// Object is the type of object for the response.
	Object string `json:"object"`
	// Usage is the usage statistics for the response.
	Usage struct {
		// PromptTokens is the number of tokens in the prompt.
		PromptTokens int `json:"prompt_tokens"`
		// CompletionTokens is the number of tokens in the completion.
		CompletionTokens int `json:"completion_tokens"`
		// TotalTokens is the total number of tokens.
		TotalTokens int `json:"total_tokens"`
	} `json:"usage"`
}

CompletionResponse represents a response to generate text completion.

type DeleteFileResponse

type DeleteFileResponse struct {
	// ID is the ID of the deleted file.
	ID string `json:"id"`
	// Object is the type of object for the response.
	Object string `json:"object"`
	// Deleted is a boolean indicating whether the file was successfully deleted.
	Deleted bool `json:"deleted"`
}

DeleteFileResponse represents a response to delete a file.

type DialogRequest

type DialogRequest struct {
	// Instruction is the instruction for the dialog.
	Instruction string `json:"instruction"`
	// Input is the input for the dialog.
	Input string `json:"input"`
}

DialogRequest represents a request for a dialog.

type EditChatRequest

type EditChatRequest struct {
	// Model is the ID of the model to use for generating the chat response.
	Model string `json:"model"`
	// Messages is an array of messages in the chat.
	Messages []struct {
		// Role is the role of the message sender (system, user, or assistant).
		Role string `json:"role"`
		// Content is the content of the message.
		Content string `json:"content"`
	} `json:"messages"`
	// Instruction is the instruction for editing the chat response.
	Instruction string `json:"instruction"`
}

EditChatRequest represents a request to edit a chat response.

type EditChatResponse

type EditChatResponse struct {
	// Choices is an array of choices for text completion.
	Choices []struct {
		// Text is the generated text for the choice.
		Text string `json:"text"`
		// Index is the index of the choice.
		Index int `json:"index"`
		// Logprobs is the log probabilities for the choice.
		Logprobs interface{} `json:"logprobs"`
		// FinishReason is the reason for finishing the choice.
		FinishReason string `json:"finish_reason"`
	} `json:"choices"`
	// Created is the timestamp for when the response was created.
	Created int `json:"created"`
	// ID is the ID of the response.
	ID string `json:"id"`
	// Model is the ID of the model used for text completion.
	Model string `json:"model"`
	// Object is the type of object for the response.
	Object string `json:"object"`
	// Usage is the usage statistics for the response.
	Usage struct {
		// PromptTokens is the number of tokens in the prompt.
		PromptTokens int `json:"prompt_tokens"`
		// CompletionTokens is the number of tokens in the completion.
		CompletionTokens int `json:"completion_tokens"`
		// TotalTokens is the total number of tokens.
		TotalTokens int `json:"total_tokens"`
	} `json:"usage"`
}

EditChatResponse represents a response to edit a chat response.

func (*EditChatResponse) GetContent

func (r *EditChatResponse) GetContent() (string, error)

CheckChatResponse checks if the chat response is valid.

type EmbeddingRequest

type EmbeddingRequest struct {
	// Model is the ID of the model to use for generating the embedding.
	Model string `json:"model"`
	// Input is the input text to generate the embedding for.
	Input string `json:"input"`
}

EmbeddingRequest represents a request to generate an embedding.

type EmbeddingResponse

type EmbeddingResponse struct {
	// Model is the ID of the model used for generating the embedding.
	Model string `json:"model"`
	// Object is the type of object for the response.
	Object string `json:"object"`
	// Data is an array of embedding information.
	Data []struct {
		// Object is the type of object for the response.
		Object string `json:"object"`
		// Embedding is the embedding generated for the input text.
		Embedding []float64 `json:"embedding"`
		// Index is the index of the input text.
		Index int `json:"index"`
	} `json:"data"`
	// Usage is the usage statistics for the response.
	Usage struct {
		// PromptTokens is the number of tokens in the prompt.
		PromptTokens int `json:"prompt_tokens"`
		// TotalTokens is the total number of tokens.
		TotalTokens int `json:"total_tokens"`
	} `json:"usage"`
}

EmbeddingResponse represents a response to generate an embedding.

type FileInfo

type FileInfo struct {
	// ID 是文件的唯一标识符。
	ID string `json:"id"`
	// Object 是响应的对象类型。
	Object string `json:"object"`
	// Bytes 是文件的大小(以字节为单位)。
	Bytes int `json:"bytes"`
	// CreatedAt 是文件创建的时间戳。
	CreatedAt int `json:"created_at"`
	// Filename 是文件的名称。
	Filename string `json:"filename"`
	// Purpose 是文件的用途。
	Purpose string `json:"purpose"`
}

FileInfo 文件信息

type FileList

type FileList struct {
	// Data is an array of file information.
	Data []FileInfo `json:"data"`
	// Object is the type of object for the response.
	Object string `json:"object"`
}

FileList represents a list of files.

type FineTune

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

func (*FineTune) Cancel

func (o *FineTune) Cancel(fine_tune_id string) (*FineTuneJob, error)

New code starts here

func (*FineTune) Create

func (o *FineTune) Create(fileID string) (*FineTuneJob, error)

func (*FineTune) Delete

func (o *FineTune) Delete(fine_tune_id string) (*JobDeleteInfo, error)

func (*FineTune) Events

func (o *FineTune) Events(fine_tune_id string) (*FineTuneJobEventList, error)

func (*FineTune) Get

func (o *FineTune) Get(fine_tune_id string) (*FineTuneJob, error)

func (*FineTune) List

func (o *FineTune) List() (*FineTuneJobList, error)

type FineTuneEvent

type FineTuneEvent struct {
	// Object is the type of object for the response.
	Object string `json:"object"`
	// CreatedAt is the timestamp for when the event was created.
	CreatedAt int `json:"created_at"`
	// Level is the level of the event.
	Level string `json:"level"`
	// Message is the message for the event.
	Message string `json:"message"`
}

FineTuneEvent represents an event for a fine-tune job.

type FineTuneJob

type FineTuneJob struct {
	// ID is the ID of the fine-tune job.
	ID string `json:"id"`
	// Object is the type of object for the response.
	Object string `json:"object"`
	// Model is the ID of the model being fine-tuned.
	Model string `json:"model"`
	// CreatedAt is the timestamp for when the fine-tune job was created.
	CreatedAt int `json:"created_at"`
	// Events is an array of events for the fine-tune job.
	Events []FineTuneEvent `json:"events"`
	// FineTunedModel is the ID of the fine-tuned model.
	FineTunedModel string `json:"fine_tuned_model"`
	// Hyperparams is the hyperparameters for the fine-tune job.
	Hyperparams FineTuneJobHyperparams `json:"hyperparams"`
	// OrganizationID is the ID of the organization that owns the fine-tune job.
	OrganizationID string `json:"organization_id"`
	// ResultFiles is an array of files generated by the fine-tune job.
	ResultFiles []FileInfo `json:"result_files"`
	// Status is the status of the fine-tune job.
	Status string `json:"status"`
	// ValidationFiles is an array of validation files for the fine-tune job.
	ValidationFiles []FileInfo `json:"validation_files"`
	// TrainingFiles is an array of training files for the fine-tune job.
	TrainingFiles []FileInfo `json:"training_files"`
	// UpdatedAt is the timestamp for when the fine-tune job was last updated.
	UpdatedAt int `json:"updated_at"`
}

FineTuneJob represents a job for fine-tuning a model.

type FineTuneJobEventList

type FineTuneJobEventList struct {
	// Data is an array of fine-tune job event information.
	Data []FineTuneEvent `json:"data"`
	// Object is the type of object for the response.
	Object string `json:"object"`
}

FineTuneJobEventList represents a list of events for a fine-tune job.

type FineTuneJobHyperparams

type FineTuneJobHyperparams struct {
	// BatchSize is the batch size for the fine-tune job.
	BatchSize int `json:"batch_size"`
	// LearningRateMult is the learning rate multiplier for the fine-tune job.
	LearningRateMult float64 `json:"learning_rate_multiplier"`
	// NEpochs is the number of epochs for the fine-tune job.
	NEpochs int `json:"n_epochs"`
	// PromptLossWeight is the prompt loss weight for the fine-tune job.
	PromptLossWeight float64 `json:"prompt_loss_weight"`
}

FineTuneJobHyperparams represents the hyperparameters for a fine-tune job.

type FineTuneJobList

type FineTuneJobList struct {
	// Data is an array of fine-tune job information.
	Data []FineTuneJob `json:"data"`
	// Object is the type of object for the response.
	Object string `json:"object"`
}

FineTuneJobList represents a list of fine-tune jobs.

type IChat

type IChat interface {
	Complete(string) (string, error)
}

type Image

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

func (*Image) Edit

func (o *Image) Edit(imagePath string, maskPath string, prompt string, n int, size ImageSizeSupported) (*ImageResponse, error)

func (*Image) EditDirect

func (o *Image) EditDirect(fileName string, input io.Reader, maskName string, mask io.Reader,
	prompt string, n int, size ImageSizeSupported) (*ImageResponse, error)

func (*Image) Generate

func (o *Image) Generate(prompt string, n int) (*ImageResponse, error)

func (*Image) Variate

func (o *Image) Variate(imagePath string, n int, size ImageSizeSupported) (*ImageResponse, error)

func (*Image) VariateDirect

func (o *Image) VariateDirect(fileName string, input io.Reader, n int, size ImageSizeSupported) (*ImageResponse, error)

type ImageRequest

type ImageRequest struct {
	// Model is the ID of the model to use for generating the image.
	Model string `json:"model"`
	// Prompt is the prompt to use for generating the image.
	Prompt string `json:"prompt"`
	// Size is the size of the image to generate.
	Size ImageSizeSupported `json:"size"`
	// N is the number of images to generate.
	N int `json:"n"`
	// ResponseFormat is the format of the response.
	ResponseFormat string `json:"response_format"`
}

ImageRequest represents a request to generate an image.

type ImageResponse

type ImageResponse struct {
	// Created is the timestamp for when the response was created.
	Created int `json:"created"`
	// Data is an array of image URLs.
	Data []struct {
		// URL is the URL of the generated image.
		URL string `json:"url"`
	} `json:"data"`
}

ImageResponse represents a response to generate an image.

type ImageSizeSupported

type ImageSizeSupported string
const (
	Size256  ImageSizeSupported = "256x256"
	Size512  ImageSizeSupported = "512x512"
	Size1024 ImageSizeSupported = "1024x1024"
)

type JobDeleteInfo

type JobDeleteInfo struct {
	// ID is the ID of the deleted model.
	ID string `json:"id"`
	// Object is the type of object for the response.
	Object string `json:"object"`
	// Deleted is a boolean indicating whether the model was successfully deleted.
	Deleted bool `json:"deleted"`
}

JobDeleteInfo represents a response to delete a model.

type Model

type Model struct {
	ModelList
	// contains filtered or unexported fields
}

func (*Model) Get

func (o *Model) Get(model string) (*ModelInfo, error)

func (*Model) List

func (o *Model) List() (*ModelList, error)

type ModelInfo

type ModelInfo struct {
	// 模型 ID
	ID string `json:"id"`
	// 模型对象
	Object string `json:"object"`
	// 模型所属者
	OwnedBy string `json:"owned_by"`
	// 模型权限
	Permission []ModelPermission `json:"permission"`
}

ModelInfo 是模型信息

type ModelList

type ModelList struct {
	// Data is an array of model information.
	Data []ModelInfo `json:"data"`
	// Object is the type of object for the response.
	Object string `json:"object"`
}

ModelList represents a list of models.

type ModelPermission

type ModelPermission struct {
	// 模型 ID
	ID string `json:"id"`
	// 是否允许创建引擎
	AllowCreateEngine bool `json:"allow_create_engine"`
	// 是否允许采样
	AllowSampling bool `json:"allow_sampling"`
	// 是否允许记录概率
	AllowLogprobs bool `json:"allow_logprobs"`
	// 是否允许搜索索引
	AllowSearchIndices bool `json:"allow_search_indices"`
	// 是否允许查看
	AllowView bool `json:"allow_view"`
	// 是否允许微调
	AllowFineTuning bool `json:"allow_fine_tuning"`
	// 组织
	Organization string `json:"organization"`
	// 组
	Group interface{} `json:"group"`
	// 是否阻塞
	IsBlocking bool `json:"is_blocking"`
}

ModelPermission 是模型权限

type OpenAI

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

func NewOpenAI

func NewOpenAI(apiKey string, opts ...OpenAIOption) *OpenAI

func (*OpenAI) Audio

func (o *OpenAI) Audio() *Audio

func (*OpenAI) Chat

func (o *OpenAI) Chat(opts ...ChatOption) *Chat

func (*OpenAI) Completions

func (o *OpenAI) Completions(message string) (*CompletionResponse, error)

func (*OpenAI) FineTune

func (o *OpenAI) FineTune() *FineTune

func (*OpenAI) GetEmbeddings

func (o *OpenAI) GetEmbeddings(input string) (*EmbeddingResponse, error)

func (*OpenAI) Image

func (o *OpenAI) Image() *Image

func (*OpenAI) Model

func (o *OpenAI) Model() *Model

func (*OpenAI) Moderation

func (o *OpenAI) Moderation(input string) (*TextModerationResponse, error)

func (*OpenAI) TuneFile

func (o *OpenAI) TuneFile() *TuneFile

type OpenAIOption

type OpenAIOption func(*OpenAI)

func WithModel

func WithModel(model string) OpenAIOption

type OpenAIRole

type OpenAIRole string

OpenAIRole 是 OpenAI 的角色类型

const (
	User      OpenAIRole = "user"
	System    OpenAIRole = "sysmtem"
	Assistant OpenAIRole = "assistant"
)

type TextModerationRequest

type TextModerationRequest struct {
	// Model is the ID of the model used for text moderation.
	Model string `json:"model"`
	// Input is the text to be moderated.
	Input string `json:"input"`
}

TextModerationRequest represents a request for text moderation.

type TextModerationResponse

type TextModerationResponse struct {
	// ID is the ID of the text moderation request.
	ID string `json:"id"`
	// Model is the ID of the model used for text moderation.
	Model string `json:"model"`
	// Results is an array of text moderation results.
	Results []struct {
		// Categories is a struct containing boolean values for different categories of text moderation.
		Categories struct {
			// Hate is a boolean indicating whether the text contains hate speech.
			Hate bool `json:"hate"`
			// HateThreatening is a boolean indicating whether the text contains threatening hate speech.
			HateThreatening bool `json:"hate/threatening"`
			// SelfHarm is a boolean indicating whether the text contains self-harm content.
			SelfHarm bool `json:"self-harm"`
			// Sexual is a boolean indicating whether the text contains sexual content.
			Sexual bool `json:"sexual"`
			// SexualMinors is a boolean indicating whether the text contains sexual content involving minors.
			SexualMinors bool `json:"sexual/minors"`
			// Violence is a boolean indicating whether the text contains violent content.
			Violence bool `json:"violence"`
			// ViolenceGraphic is a boolean indicating whether the text contains graphic violent content.
			ViolenceGraphic bool `json:"violence/graphic"`
		} `json:"categories"`
		// CategoryScores is a struct containing float values for the scores of different categories of text moderation.
		CategoryScores struct {
			// Hate is the score for hate speech.
			Hate float64 `json:"hate"`
			// HateThreatening is the score for threatening hate speech.
			HateThreatening float64 `json:"hate/threatening"`
			// SelfHarm is the score for self-harm content.
			SelfHarm float64 `json:"self-harm"`
			// Sexual is the score for sexual content.
			Sexual float64 `json:"sexual"`
			// SexualMinors is the score for sexual content involving minors.
			SexualMinors float64 `json:"sexual/minors"`
			// Violence is the score for violent content.
			Violence float64 `json:"violence"`
			// ViolenceGraphic is the score for graphic violent content.
			ViolenceGraphic float64 `json:"violence/graphic"`
		} `json:"category_scores"`
		// Flagged is a boolean indicating whether the text was flagged for moderation.
		Flagged bool `json:"flagged"`
	} `json:"results"`
}

TextModerationResponse represents a response to a text moderation request.

type TuneFile

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

func (*TuneFile) Content

func (o *TuneFile) Content(fileID string, filePath string) error

func (*TuneFile) Delete

func (o *TuneFile) Delete(fileID string) (*DeleteFileResponse, error)

New code starts here

func (*TuneFile) Get

func (o *TuneFile) Get(fileID string) (*FileInfo, error)

func (*TuneFile) List

func (o *TuneFile) List() (*FileList, error)

func (*TuneFile) Upload

func (o *TuneFile) Upload(filePath string) (*FileInfo, error)

New code starts here

func (*TuneFile) UploadDirect

func (o *TuneFile) UploadDirect(fileName string, input io.Reader) (*FileInfo, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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