openai

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2023 License: Apache-2.0 Imports: 16 Imported by: 1

README

OpenAI

Overview

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

TODO:

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"
)

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 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 ChatRequest

type ChatRequest struct {
	Content string `json:"content" form:"content"`
	Tokens  int    `json:"tokens,omitempty" form:"tokens,omitempty"`
}

The ChatRequest struct defines the structure for requests to be sent to the chat service. It contains two fields: - Content: the content of the message - Tokens: the number of tokens to generate in the response.

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 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) 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)

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) 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)

func (*Client) ListFiles added in v0.0.2

func (c *Client) ListFiles(ctx context.Context) (response Files, 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)

func (*Client) RetrieveFileContent added in v0.0.2

func (c *Client) RetrieveFileContent(ctx context.Context, request *File) (response File, 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 FormFactory added in v0.0.2

type FormFactory interface {
	CreateFormFile(fieldname string, file *os.File) error
	WriteField(fieldname string, value string) error
	FormDataContentType() string
	Close() error
}

type ImagesEditReuqest

type ImagesEditReuqest struct {
	Image          *os.File `json:"image"`
	Mask           *os.File `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          *os.File `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 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 TranscriptionsRequest

type TranscriptionsRequest struct {
	File           *os.File `json:"file"`
	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"`
}

type WeChatCache

type WeChatCache struct {
	OpenID  string `json:"open_id"`
	Content string `json:"content"`
}

The WeChatCache struct defines the structure to cache WeChat messages. It contains two fields: - OpenID: The unique identifier of the recipient's account. - Content: The content of WeChat message.

func (*WeChatCache) Key

func (cache *WeChatCache) Key() string

The Key method generates a unique key for caching a WeChat message by combining the OpenID and content properties of the cache object and then applying SHA-512/384 algorithm to create a hexadecimal-encoded key.

type WeChatInfo

type WeChatInfo struct {
	Token     string
	AppID     string
	Appsecret string
}

The WeChatInfo struct contains three fields: - Token: The token provided by WeChat to identify the server. - AppID: The ID of the application registered with WeChat - Appsecret: The app secret provided by WeChat.

type WeChatMsg

type WeChatMsg struct {
	XMLName      xml.Name `xml:"xml"`
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Content      string
}

The WeChatMsg struct defines the structure for a WeChat message. It contains six fields: - XMLName: This is the name of the XML element. - ToUserName: The account ID of the recipient - FromUserName: The account ID of the sender - CreateTime: Time value in Unix format when message sent by sender. - MsgType: The type of message. (text, image, voice etc.) - Content: The message content

type WeChatVerify

type WeChatVerify struct {
	Signature string `json:"signature" form:"signature"`
	Timestamp string `json:"timestamp" form:"timestamp"`
	Nonce     string `json:"nonce" form:"nonce"`
	Echostr   string `json:"echostr" form:"echostr"`
}

The WeChatVerify struct is used to verify requests received from WeChat. It contains four fields: - Signature: The signature to verify. It is created by hashing a string consisting of the timestamp, nonce and token parameters together with SHA-1 algorithm. - Timestamp: A timestamp used to ensure that this request is not replayed. - Nonce: A random value used to create a unique hash. - Echostr: A parameter used to respond to the verification request.

func (*WeChatVerify) Verify

func (p *WeChatVerify) Verify(token string) bool

The Verify method verifies a WeChat request signature. It calculates the hash of the token, timestamp and nonce, combines them into a single string and then applies SHA-1 algorithm to generate a hexadecimal-encoded signature. If this generated signature matches with the provided signature then the method returns true.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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