openai

package module
v1.0.0 Latest Latest
Warning

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

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

README

OpenAI API for Go

This library provider Go clients for OpenAI API.

Installation

go get github.com/im15/go-openai

Example:

package main

import (
	"context"
	openai "github.com/im15/openai-api-go"
	"log"
	"os"
)

func main() {
	c := openai.NewClient(os.Getenv("OPENAI_API_KEY"))
	body, err := c.CreateChatCompletion(
		context.Background(),
		openai.ChatRequestBody{
			Model: openai.GPT35Turbo,
			Message: []openai.ChatMessage{
				{
					Role: openai.RoleUser, 
					Content: "Hello!" 
				},
            },
        },
	)
	if err != nil {
        log.Printf("error: %v", err)
		return
	}

	log.Printf("%s", body.Choices[0].Message.Content)
}

Documentation

Index

Constants

View Source
const (
	RoleUser      = "user"
	RoleSystem    = "system"
	RoleAssistant = "assistant"
)
View Source
const (
	Size256  = "256x256"
	Size512  = "512x512"
	Size1024 = "1024x1024"
)
View Source
const (
	ImageResponseFormat  = "url"
	ImageResponseB64Json = "b64_json"
)
View Source
const (
	GPT4                 = "gpt-4"
	GPT40314             = "gpt-4-0314"
	GPT432k              = "gpt-4-32k"
	GPT432k0314          = "gpt-4-32k-0314"
	GPT35Turbo           = "gpt-3.5-turbo"
	GPT35Turbo0310       = "gpt-3.5-turbo-0310"
	TextDavinci003       = "text-davinci-003"
	TextDavinci002       = "text-davinci-002"
	TextCurie001         = "text-curie-001"
	TextBabBage001       = "text-babbage-001"
	TextAda001           = "text-ada-001"
	Davinci              = "davinci"
	Curie                = "curie"
	Babbage              = "babbage"
	Ada                  = "ada"
	TextDavinciEdit001   = "text-davinci-edit-001"
	CodeDavinciEdit001   = "code-davinci-edit-001"
	Whisper1             = "whisper-1"
	TextEmbeddingAda002  = "text-embedding-ada-002"
	TextSearchAdaDoc001  = "text-search-ada-doc-001"
	TextModerationStable = "text-moderation-stable"
	TextModerationLatest = "text-moderation-latest"
)

Variables

View Source
var (
	ErrInvalidModel = errors.New("invalid model")
)

Functions

This section is empty.

Types

type AudioRequestBody

type AudioRequestBody struct {
	File           string  `json:"file"`
	Model          string  `json:"model"`
	Prompt         string  `json:"prompt,omitempty"`
	ResponseFormat string  `json:"response_format,omitempty"`
	Temperature    float32 `json:"temperature,omitempty"`
	Language       string  `json:"language,omitempty"` // just create transcription
}

type AudioResponseBody

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

type ChatChoice

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

type ChatMessage

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

type ChatRequestBody

type ChatRequestBody struct {
	Model            string         `json:"model"`
	Messages         []ChatMessage  `json:"messages"`
	Temperature      float32        `json:"temperature,omitempty"`
	TopP             float32        `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  float32        `json:"presence_penalty,omitempty"`
	FrequencyPenalty float32        `json:"frequency_penalty,omitempty"`
	LogitBias        map[string]int `json:"logit_bias,omitempty"`
	User             string         `json:"user,omitempty"`
}

type ChatResponseBody

type ChatResponseBody struct {
	Usage   TokensUsage  `json:"usage"`
	ID      string       `json:"id"`
	Object  string       `json:"object"`
	Created int          `json:"created"`
	Choices []ChatChoice `json:"choices"`
}

type Client

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

func NewClient

func NewClient(token string) *Client

func NewClientWithOrg

func NewClientWithOrg(token, orgID string) *Client

func (*Client) CreateChatCompletion

func (c *Client) CreateChatCompletion(
	ctx context.Context,
	reqBody ChatRequestBody) (resBody ChatResponseBody, err error)

CreateChatCompletion Create a completion for the chat message POST https://api.openai.com/v1/chat/completions

func (*Client) CreateCompletions

func (c *Client) CreateCompletions(
	ctx context.Context,
	reqBody CompletionRequestBody) (resBody CompletionResponseBody, err error)

CreateCompletions POST https://api.openai.com/v1/completions

func (*Client) CreateEdit

func (c *Client) CreateEdit(
	ctx context.Context,
	reqBody EditRequestBody) (resBody EditResponseBody, err error)

CreateEdit Creates a new edit for the provided inout, and parameters. POST https://api.openai.com/v1/edits

func (*Client) CreateEmbeddings

func (c *Client) CreateEmbeddings(
	ctx context.Context,
	reqBody EmbeddingsRequestBody) (resBody EmbeddingsResponseBody, err error)

CreateEmbeddings POST https://api.openai.com/v1/embeddings

func (*Client) CreateImage

func (c *Client) CreateImage(
	ctx context.Context,
	reqBody ImageRequestBody) (resBody ImageResponseBody, err error)

CreateImage Creates an image given a prompt. POST https://api.openai.com/v1/images/generations

func (*Client) CreateImageEdit

func (c *Client) CreateImageEdit(
	ctx context.Context,
	reqBody ImageEditRequestBody) (resBody ImageResponseBody, err error)

CreateImageEdit Create an edited or extended image given an original image and a prompt. POST https://api.openai.com/v1/images/edits

func (*Client) CreateImageVariation

func (c *Client) CreateImageVariation(
	ctx context.Context,
	reqBody ImageVariationRequestBody) (resBody ImageResponseBody, err error)

CreateImageVariation Create a variation of a given image. POST https://api.openai.com/v1/images/variations

func (*Client) CreateModeration

func (c *Client) CreateModeration(
	ctx context.Context,
	reqBody ModerationRequestBody) (resBody ModerationResponseBody, err error)

CreateModeration Classifies if text violates OpenAI's Content Policy POST https://api.openai.com/v1/moderations

func (*Client) CreateTranscription

func (c *Client) CreateTranscription(
	ctx context.Context,
	reqBody AudioRequestBody) (resBody AudioResponseBody, err error)

CreateTranscription Transcribes audio into the input language. POST https://api.openai.com/v1/audio/transcriptions

func (*Client) CreateTranslation

func (c *Client) CreateTranslation(
	ctx context.Context,
	reqBody AudioRequestBody) (resBody AudioResponseBody, err error)

CreateTranslation Translates audio into English. POST https://api.openai.com/v1/audio/translations

func (*Client) DeleteFile

func (c *Client) DeleteFile(
	ctx context.Context,
	fileID string) (resBody DeleteFileResponseBody, err error)

DeleteFile Delete a file DELETE https://api.openai.com/v1/files/{file_id}

func (*Client) ListFiles

func (c *Client) ListFiles(ctx context.Context) (resBody ListFilesResponseBody, err error)

ListFiles Return a list of files that belong to the user's organization. GET https://api.openai.com/v1/files

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) (*ModelsResponseBody, error)

ListModels Lists the currently available models, and provides basic information about each one such as the owner and availability. GET https://api.openai.com/v1/models

func (*Client) RetrieveFile

func (c *Client) RetrieveFile(
	ctx context.Context,
	fileID string) (resBody FileObject, err error)

RetrieveFile Return information about a specific file. GET https://api.openai.com/v1/files/{file_id}

func (*Client) RetrieveFileContent

func (c *Client) RetrieveFileContent(
	ctx context.Context,
	fileID string) (resBody RetrieveFileContentResponseBody, err error)

RetrieveFileContent Returns the contents of the specified file. GET https://api.openai.com/v1/files/{file_id}/content

func (*Client) RetrieveModel

func (c *Client) RetrieveModel(
	ctx context.Context,
	model string,
) (modelObject ModelObject, err error)

RetrieveModel Retrieves a model instance, providing basic information about the model such as the owner and permissioning. `model`: The ID of the model to use for this request GET https://api.openai.com/v1/models/{model}

func (*Client) UploadFile

func (c *Client) UploadFile(
	ctx context.Context,
	reqBody UploadFileRequestBody) (resBody FileObject, err 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 1GB. Please contact us if you need to increase the storage limit. POST https://api.openai.com/v1/files

type CompletionChoice

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

type CompletionRequestBody

type CompletionRequestBody struct {
	Model           string         `json:"model"`
	Prompt          string         `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"`
	BestOf          int            `json:"best_of,omitempty"`
	LogitBias       map[string]int `json:"logit_bias,omitempty"`
	User            string         `json:"user,omitempty"`
}

type CompletionResponseBody

type CompletionResponseBody struct {
	ID      string             `json:"id"`
	Object  string             `json:"object"`
	Created int                `json:"created"`
	Model   string             `json:"model"`
	Choices []CompletionChoice `json:"choices"`
	Usage   TokensUsage        `json:"usage"`
}

type DeleteFileResponseBody

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

type EditChoice

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

type EditRequestBody

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

type EditResponseBody

type EditResponseBody struct {
	Usage   TokensUsage  `json:"usage"`
	Object  string       `json:"object"`
	Created int          `json:"created"`
	Choices []EditChoice `json:"choices"`
}

type EmbeddingsRequestBody

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

type EmbeddingsResponseBody

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

type Error

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

func (*Error) Error

func (e *Error) Error() string

type ErrorResponseBody

type ErrorResponseBody struct {
	Error *Error `json:"error,omitempty"`
}

type FileObject

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

type ImageData

type ImageData struct {
	URL string `json:"url"`
}

type ImageEditRequestBody

type ImageEditRequestBody struct {
	// [Required]
	// The image to edit. Must be a valid PNG file, less than 4MB, and square.
	// If mask is not provided, image must have transparency, which will be used as the mask.
	Image string `json:"image" multipart:"image,file"`
	// [Optional]
	// An additional image whose fully transparent areas (e.g. where alpha is zero) indicate
	// where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the
	// same dimensions as `image`.
	Mask string `json:"mask,omitempty" multipart:"mask,file"`
	// [Required]
	// A text description of the desired image(s).
	// The maximum length is 1000 characters.
	Prompt string `json:"prompt" multipart:"prompt"`
	// [Optional Defaults to 1]
	// The number of images to generate.
	// Must be between 1 and 10.
	N int `json:"n,omitempty" multipart:"n"`
	// [Optional Defaults to 1024x1024]
	// The size of the generated images.
	// Must be one of `256x256`, `512x512`, or `1024x1024`.
	Size string `json:"size,omitempty" multipart:"size"`
	// [Optional Defaults to url]
	// The format in which the generated images are returned.
	// Must be one of `url` or `b64_json`.
	ResponseFormat string `json:"response_format,omitempty" multipart:"response-format"`
	// [Optional]
	// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.
	User string `json:"user,omitempty" multipart:"user"`
}

func (ImageEditRequestBody) WriteForm

func (b ImageEditRequestBody) WriteForm(w *multipart.Writer) (err error)

type ImageRequestBody

type ImageRequestBody struct {
	// [Required]
	// A text description of the desired image(s).
	// The maximum length is 1000 characters.
	Prompt string `json:"prompt"`
	// [Optional Defaults to 1]
	// The number of images to generate.
	// Must be between 1 and 10.
	N int `json:"n,omitempty"`
	// [Optional Defaults to 1024x1024] The size of the generated images.
	//Must be one of `256x256`, `512x512`, or `1024x1024`.
	Size string `json:"size,omitempty"`
	// [Optional Defaults to url]
	// The format in which the generated images are returned.
	// Must be one of `url` or `b64_json`.
	ResponseFormat string `json:"response_format,omitempty"`
	// [Optional]
	// A unique identifier representing your end-user,
	// which can help OpenAI to monitor and detect abuse.
	User string `json:"user,omitempty"`
}

type ImageResponseBody

type ImageResponseBody struct {
	Created int         `json:"created"`
	Data    []ImageData `json:"data"`
}

type ImageVariationRequestBody

type ImageVariationRequestBody struct {
	// [Required]
	// The image to use as the basic for the variation(s).
	// Must be a valid PNG file, less than 4MB, and square.
	Image          string `json:"image"`
	N              int    `json:"n"`
	Size           string `json:"size"`
	ResponseFormat string `json:"response_format"`
	User           string `json:"user"`
}

func (ImageVariationRequestBody) WriteForm

func (b ImageVariationRequestBody) WriteForm(w *multipart.Writer) (err error)

type ListFilesResponseBody

type ListFilesResponseBody struct {
	Object string       `json:"object"`
	Data   []FileObject `json:"data"`
}

type ModelObject

type ModelObject struct {
	ID         string            `json:"id"`
	Object     string            `json:"object"`
	Created    int               `json:"created"`
	OwnerBy    string            `json:"owner_by"`
	Permission []ModelPermission `json:"permission"`
	Root       string            `json:"root"`
	Parent     interface{}       `json:"parent"`
}

type ModelPermission

type ModelPermission struct {
	ID                 string      `json:"id"`
	Object             string      `json:"object"`
	Created            int         `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 ModelsResponseBody

type ModelsResponseBody struct {
	Object string        `json:"object"`
	Data   []ModelObject `json:"data"`
}

type ModerationObject

type ModerationObject 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 ModerationRequestBody

type ModerationRequestBody struct {
	Input string
	Model string `json:"model,omitempty"`
}

type ModerationResponseBody

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

type ModerationResult

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

type RequestError

type RequestError struct {
	StatusCode int
}

func (*RequestError) Error

func (r *RequestError) Error() string

func (*RequestError) Unwrap

func (r *RequestError) Unwrap() error

type RetrieveFileContentResponseBody

type RetrieveFileContentResponseBody struct {
	Data []byte
}

type TokensUsage

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

type UploadFileRequestBody

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

Jump to

Keyboard shortcuts

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