openai

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2023 License: Apache-2.0 Imports: 10 Imported by: 0

README

OpenAI

Overview

This is a library implemented in Go for OpenAI API. It supports:

Install

go get github.com/mengbin92/openai

ChatGPT example code

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/mengbin92/openai"
)

func main() {
	client := openai.NewClient("your token", "your org", "proxy")

	resp, err := client.CreateChatCompletion(
		context.Background(),
		&openai.ChatCompletionRequset{
			Model: openai.GPT3Dot5Turbo,
			Messages: []openai.Message{
				{Role: openai.ChatMessageRoleUser, Content: "hi!"},
			},
		},
	)
	if err != nil {
		fmt.Printf("CreateChatCompletion error: %s\n", err.Error())
		os.Exit(-1)
	}
	fmt.Println(resp.Choices[0].Message.Content)
}

Documentation

Overview

This is an openAI library implemented in Go.

Index

Constants

View Source
const (
	GPT4        = "gpt-4"
	GPT40314    = "gpt-4-0314"
	GPT432K     = "gpt-4-32k"
	GPT432K0314 = "gpt-4-32k-0314"

	GPT3Dot5Turbo          = "gpt-3.5-turbo"
	GPT3Dot5Turbo0301      = "gpt-3.5-turbo-0301"
	GPT3Dot5TextDavinci003 = "text-davinci-003"
	GPT3Dot5TextDavinci002 = "text-davinci-002"
	GPT3Dot5CodeDavinci002 = "code-davinci-002"

	GPT3TextCurie001       = "text-curie-001"
	GPT3TextBabbage001     = "text-babbage-001"
	GPT3TextAda001         = "text-ada-001"
	GPT3TextDavincEdit001  = "text-davinci-edit-001"
	GPT3CodeDavinciEdit001 = "code-davinci-edit-001"
	GPT3Whisper1           = "whisper-1"
	GPT3Davinci            = "davinci"
	GPT3Curie              = "curie"
	GPT3Babbage            = "babbage"
	GPT3Ada                = "ada"
	TextEmbeddingAda002    = "text-embedding-ada-002"
	TextSearchAdaDoc001    = "text-search-ada-doc-001"
	TextModerationStable   = "text-moderation-stable"
	TextModerationLatest   = "text-moderation-latest"

	// update 2023/06/14
	GPT40613             = "gpt-4-0613"
	GPT3Dot5Turbo16k     = "gpt-3.5-turbo-16k"
	GPT3Dot5Turbo0613    = "gpt-3.5-turbo-0613"
	GPT3Dot5Turbo16k0613 = "gpt-3.5-turbo-16k-0613"
)

model list from https://platform.openai.com/docs/models/model-endpoint-compatibility

View Source
const (
	ChatMessageRoleUser      = "user"
	ChatMessageRoleSystem    = "system"
	ChatMessageRoleAssistant = "assistant"
)

chat role defined by OpenAI

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	Code       string `json:"code,omitempty"`
	Message    string `json:"message"`
	Param      string `json:"param,omitempty"`
	Type       string `json:"type"`
	StatusCode int    `json:"-"`
}

APIError provides error information returned by the OpenAI API.

func (*APIError) Error

func (e *APIError) Error() string

type Categories added in v0.2.0

type 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"`
}

type CategoryScores added in v0.2.0

type 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"`
}

type ChatCompletionRequset

type ChatCompletionRequset struct {
	Model            string                 `json:"model,omitempty"`
	Messages         []Message              `json:"messages,omitempty"`
	Temperature      float64                `json:"temperature,omitempty"`
	TopP             float64                `json:"top_p,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]interface{} `json:"logit_bias,omitempty"`
	User             string                 `json:"user,omitempty"`
}

ChatCompletionRequest struct defines the openAI ChatCompletionRequest type. The purpose of this struct is to define the parameters required to make a request to an OpenAI API endpoint to perform chat completion.

type ChatCompletionResponse

type ChatCompletionResponse struct {
	Id      string   `json:"id"`
	Object  string   `json:"object"`
	Created int64    `json:"created"`
	Model   string   `json:"model"`
	Choices []Choice `json:"choices"`
	Usage   Usage    `json:"usage"`
}

type Choice

type Choice struct {
	Index        int `json:"index,omitempty"`
	Message      `json:"message,omitempty"`
	FinishReason string `json:"finish_reason,omitempty"`
}

type Client

type Client struct {
	HttpClient *http.Client
	// contains filtered or unexported fields
}

Clinet is the openAI API client

func NewClient

func NewClient(apikey, org, proxyUrl, accessToken string) *Client

NewClient creates and returns a new instance of the Client struct. It takes in an API key, organization name and proxy URL as strings

func NewClientWithConfig added in v0.0.2

func NewClientWithConfig(config *ClientConfig) *Client

func (*Client) CancelFineTune added in v0.2.0

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

func (*Client) CreateChatCompletion

func (c *Client) CreateChatCompletion(ctx context.Context, request *ChatCompletionRequset) (response ChatCompletionResponse, err error)

The function CreateChatCompletion creates a new completed chat. It takes in parameters: - ctx, of type context.Context which is the execution context of the function. - request, of type *ChatCompletionRequset which contains the necessary information to create a new chat completion. It returns: - response, of type ChatCompletionResponse which contains the response from the server. - err, of type error which contains any errors that occurred. If there were no errors, it will be nil.

func (*Client) CreateCompletion

func (c *Client) CreateCompletion(ctx context.Context, request *CompletionRequest) (response CompletionResponse, err error)

The CreateCompletion method creates a new completion request with the specified parameters and sends it to the server. It takes in parameters: - ctx, of type context.Context which is the execution context of the function. - request, of type *CompletionRequest which contains the data to be sent in the completion request body. It returns: - response, an object of type CompletionResponse, which contains the response from the server. - err, an error object which will contain any errors that occurred during the creation or sending of the request.

func (*Client) CreateEdits

func (c *Client) CreateEdits(ctx context.Context, request *EditsRequest) (response EditsResponse, err error)

The CreateEdits method creates a new edits request with the specified parameters and sends it to the server. It takes in parameters: - ctx, of type context.Context which is the execution context of the function. - request, of type *EditsRequest which contains the data to be sent in the edits request body. It returns: - response, an object of type EditsResponse, which contains the response from the server. - err, an error object which will contain any errors that occurred during the creation or sending of the request.

func (*Client) CreateEmbeddings

func (c *Client) CreateEmbeddings(ctx context.Context, request *EmbeddingsRequest) (response EmbeddingsResponse, err error)

The following code declares a function CreateEmbeddings for the client, which accepts a context, an EmbeddingsRequest struct and returns an EmbeddingsResponse and error. The function sends a POST request to the embeddings API of the server using Build method from c.requestFactory. It builds a request using the provided arguments; a context, http.MethodPost and full URL for the embeddings API. It also checks for any errors that may occur in the process of building the request. If there is no error in creating the request, then this function sends the created request using sendRequest method of client c with both the request and response structs as its parameters. If there is no error encountered during the execution of the above statements, the function returns the result in the form of EmbdedingsResponse object.

func (*Client) CreateFile added in v0.0.2

func (c *Client) CreateFile(ctx context.Context, request *FileRequest) (response File, err error)

CreateFile takes a context and a file request, creates a new file, and returns the created file as response

func (*Client) CreateFineTune added in v0.2.0

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

func (*Client) CreateImage

func (c *Client) CreateImage(ctx context.Context, request *ImagesReuqest) (response ImagesResponse, err error)

func (*Client) CreateImageEdits

func (c *Client) CreateImageEdits(ctx context.Context, request *ImagesEditReuqest) (response ImagesResponse, err error)

func (*Client) CreateImageVariation

func (c *Client) CreateImageVariation(ctx context.Context, request *ImagesVariationReuqest) (response ImagesResponse, err error)

func (*Client) CreateModeration added in v0.2.0

func (c *Client) CreateModeration(ctx context.Context, request ModerationRequest) (response ModerationResponse, err error)

func (*Client) CreateTranscriptions

func (c *Client) CreateTranscriptions(ctx context.Context, request *TranscriptionsRequest) (response TranscriptionsResponse, err error)

func (*Client) CreateTranslations

func (c *Client) CreateTranslations(ctx context.Context, request *TranscriptionsRequest) (response TranscriptionsResponse, err error)

func (*Client) DeleteFile added in v0.0.2

func (c *Client) DeleteFile(ctx context.Context, request *File) (response File, err error)

DeleteFile takes a context and a file, creates a new DELETE request for deleting the file with provided ID, and returns the response after sending the request

func (*Client) DeleteFineTuneModel added in v0.2.0

func (c *Client) DeleteFineTuneModel(ctx context.Context, model string) (response FineTuneDeleteResponse, err error)

func (*Client) ListFiles added in v0.0.2

func (c *Client) ListFiles(ctx context.Context) (response Files, err error)

ListFiles takes a context, send a request to OpenAI and return a list of files as response

func (*Client) ListFineTuneEvents added in v0.2.0

func (c *Client) ListFineTuneEvents(ctx context.Context, id string) (response FineTuneEventList, err error)

func (*Client) ListFineTunes added in v0.2.0

func (c *Client) ListFineTunes(ctx context.Context) (response FineTuneList, err error)

func (*Client) ModelInfo

func (c *Client) ModelInfo(ctx context.Context, name string) (model Model, err error)

func (*Client) ModelList

func (c *Client) ModelList(ctx context.Context) (list ModelList, err error)

func (*Client) RetrieveFile added in v0.0.2

func (c *Client) RetrieveFile(ctx context.Context, request *File) (response File, err error)

RetrieveFile takes a context and a file, creates a new GET request for retrieving the file with provided ID, and returns the response after sending the request

func (*Client) RetrieveFileContent added in v0.0.2

func (c *Client) RetrieveFileContent(ctx context.Context, request *File) (response File, err error)

RetrieveFileContent takes a context and a file, creates a new GET request for retrieving the content of the file with provided ID, and returns the response after sending the request

func (*Client) RetrieveFineTune added in v0.2.0

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

type ClientConfig added in v0.0.2

type ClientConfig struct {
	APIKey string
	Org    string
	Proxy  string

	HttpRequestFactory  RequestFactory
	HttpFielFormFactory func(body io.Writer) FormFactory
}

type CompletionChoice

type CompletionChoice struct {
	Text         string        `json:"text"`
	Index        int           `json:"index"`
	FinishReason string        `json:"finish_reason"`
	LogProbs     LogprobResult `json:"logprobs"`
}

type CompletionRequest

type CompletionRequest struct {
	Model            string         `json:"model"`
	Prompt           interface{}    `json:"prompt,omitempty"`
	Suffix           string         `json:"suffix,omitempty"`
	MaxTokens        int            `json:"max_tokens,omitempty"`
	Temperature      float32        `json:"temperature,omitempty"`
	TopP             float32        `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  float32        `json:"presence_penalty,omitempty"`
	FrequencyPenalty float32        `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 int64              `json:"created"`
	Model   string             `json:"model"`
	Choices []CompletionChoice `json:"choices"`
	Usage   Usage              `json:"usage"`
}

type EditsChoice

type EditsChoice struct {
	Text  string `json:"text"`
	Index int    `json:"index"`
}

type EditsRequest

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

type EditsResponse

type EditsResponse struct {
	Object  string        `json:"object"`
	Created int64         `json:"created"`
	Usage   Usage         `json:"usage"`
	Choices []EditsChoice `json:"choices"`
}

type Embedding

type Embedding struct {
	Object    string    `json:"object"`
	Embedding []float32 `json:"embedding"`
	Index     int       `json:"index"`
}

type EmbeddingsRequest

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

type EmbeddingsResponse

type EmbeddingsResponse struct {
	Model  string      `json:"model"`
	Object string      `json:"object"`
	Data   []Embedding `json:"data"`
	Usage  Usage       `json:"usage"`
}

type ErrResponse

type ErrResponse struct {
	Err *APIError `json:"error,omitempty"`
}

func (ErrResponse) Error

func (e ErrResponse) Error() string

type File added in v0.0.2

type File struct {
	Id        string `json:"id" form:"id"`
	Object    string `json:"object"`
	Bytes     int    `json:"bytes"`
	CreatedAt int64  `json:"created_at"`
	Filename  string `json:"filename"`
	Purpose   string `json:"purpose"`
	Deleted   bool   `json:"deleted"`
}

type FileRequest added in v0.0.2

type FileRequest struct {
	File    string `json:"file" form:"file"`
	Purpose string `json:"purpose" form:"purpose"`
}

type Files added in v0.0.2

type Files struct {
	Data []File `json:"data"`
}

type FineTune added in v0.2.0

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

type FineTuneDeleteResponse added in v0.2.0

type FineTuneDeleteResponse struct {
	Id      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
}

type FineTuneEvent added in v0.2.0

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

type FineTuneEventList added in v0.2.0

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

type FineTuneHyperparams added in v0.2.0

type FineTuneHyperparams struct {
	BatchSize              int64   `json:"batch_size"`
	LearningRateMultiplier float64 `json:"learning_rate_multiplier"`
	NEpochs                int64   `json:"n_epochs"`
	PromptLossWeight       float64 `json:"prompt_loss_weight"`
}

type FineTuneList added in v0.2.0

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

type FineTuneRequest added in v0.2.0

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       float32   `json:"learning_rate_multiplier,omitempty"`
	PromptLossWeight             float32   `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          []float32 `json:"classification_betas,omitempty"`
	Suffix                       string    `json:"suffix,omitempty"`
}

type FormFactory added in v0.0.2

type FormFactory interface {
	CreateFormFile(fieldname string, filepath string) error
	WriteField(fieldname string, value string) error
	FormDataContentType() string
	Close() error
}

type ImagesEditReuqest

type ImagesEditReuqest struct {
	Image          string `json:"image"`
	Mask           string `json:"mask,omitempty"`
	Prompt         string `json:"prompt"`
	N              int    `json:"n,omitempty"`
	Size           string `json:"size,omitempty"`
	ResponseFormat string `json:"response_format,omitempty"` // url or b64_json
	User           string `json:"user,omitempty"`
}

type ImagesResponse

type ImagesResponse struct {
	Created int64                `json:"created,omitempty"`
	Data    []ImagesResponseData `json:"data,omitempty"`
}

type ImagesResponseData

type ImagesResponseData struct {
	URL     string `json:"url,omitempty"`
	B64JSON string `json:"b64_json,omitempty"`
}

type ImagesReuqest

type ImagesReuqest struct {
	Prompt         string `json:"prompt" form:"prompt"`
	N              int    `json:"n,omitempty" form:"n,omitempty"`
	Size           string `json:"size,omitempty" form:"size,omitempty"`
	ResponseFormat string `json:"response_format,omitempty" form:"response_format,omitempty"` // url or b64_json
	User           string `json:"user,omitempty" form:"user,omitempty"`
}

type ImagesVariationReuqest

type ImagesVariationReuqest struct {
	Image          string `json:"image"`
	N              int    `json:"n,omitempty"`
	Size           string `json:"size,omitempty"`
	ResponseFormat string `json:"response_format,omitempty"` // url or b64_json
	User           string `json:"user,omitempty"`
}

type LogprobResult

type LogprobResult struct {
	Tokens        []string             `json:"tokens"`
	TokenLogprobs []float32            `json:"token_logprobs"`
	TopLogprobs   []map[string]float32 `json:"top_logprobs"`
	TextOffset    []int                `json:"text_offset"`
}

type Message

type Message struct {
	Role    string `json:"role,omitempty"`
	Content string `json:"content,omitempty"`
}

type Model

type Model struct {
	ID         string       `json:"id"`
	Object     string       `json:"object"`
	Created    int64        `json:"created"`
	OwnedBy    string       `json:"owned_by"`
	Permission []Permission `json:"permission"`
	Root       string       `json:"root"`
	Parent     interface{}  `json:"parent"`
}

type ModelList

type ModelList struct {
	Models []Model `json:"data"`
}

type ModerationRequest added in v0.2.0

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

type ModerationResponse added in v0.2.0

type ModerationResponse struct {
	ID      string   `json:"id"`
	Model   string   `json:"model"`
	Results []Result `json:"results"`
}

type Permission

type Permission struct {
	ID                 string      `json:"id"`
	Object             string      `json:"object"`
	Created            int64       `json:"created"`
	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"`
}

type RequestError

type RequestError struct {
	Code int
	Err  error
}

func (*RequestError) Error

func (e *RequestError) Error() string

type RequestFactory

type RequestFactory interface {
	Build(ctx context.Context, method, url string, request any) (*http.Request, error)
}

The RequestFactory interface defines the behavior for creating an http.Request object given certain parameters.

type Result added in v0.2.0

type Result struct {
	Categories     Categories     `json:"categories"`
	CategoryScores CategoryScores `json:"category_scores"`
	Flagged        bool           `json:"flagged"`
}

type TranscriptionsRequest

type TranscriptionsRequest struct {
	FilePath       string  `json:"file_path"`
	Model          string  `json:"model"` // only whisper-1
	Prompt         string  `json:"prompt,omitempty"`
	ResponseFormat string  `json:"response_format,omitempty"` // json, text, srt, verbose_json, or vtt
	Temperature    float64 `json:"temperature,omitempty"`
	Language       string  `json:"language,omitempty"`
}

type TranscriptionsResponse

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

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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