openai

package
v0.0.0-...-6bb3034 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2024 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AssistantMessage

type AssistantMessage struct {
	Content   string     `json:"content,omitempty"`
	Name      string     `json:"name,omitempty"`
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
}

AssistantMessage represents an assistant message in the chat.

func (AssistantMessage) MarshalJSON

func (m AssistantMessage) MarshalJSON() ([]byte, error)

MarshalJSON marshals the assistant message to JSON.

func (AssistantMessage) Role

func (m AssistantMessage) Role() Role

Role returns the assistant role for the assistant message.

type ChatChunk

type ChatChunk struct {
	ID      string   `json:"id"`
	Object  string   `json:"object"`
	Created int64    `json:"created"`
	Model   string   `json:"model"`
	Choices []Choice `json:"choices"`
}

ChatChunk represents a chat chunk in the stream chat completion.

type ChatRequest

type ChatRequest struct {
	Messages         []Message     `json:"messages"`
	Model            LanguageModel `json:"model"`
	FrequencyPenalty float32       `json:"frequency_penalty,omitempty"`
	LogitBias        float32       `json:"logit_bias,omitempty"`
	LogProbs         bool          `json:"logprobs,omitempty"`
	TopLogProbs      int           `json:"top_logprobs,omitempty"`
	MaxTokens        int           `json:"max_tokens,omitempty"`
	N                int           `json:"n,omitempty"`
	PresencePenalty  float32       `json:"presence_penalty,omitempty"`
	ResponseFormat   string        `json:"response_format,omitempty"` // TODO
	Seed             int           `json:"seed,omitempty"`
	Stop             []string      `json:"stop,omitempty"`
	Stream           bool          `json:"stream,omitempty"`
	Temperature      float32       `json:"temperature,omitempty"`
	TopP             float32       `json:"top_p,omitempty"`
	Tools            []Tool        `json:"tools,omitempty"`
	ToolChoices      []ToolChoice  `json:"tool_choices,omitempty"`
	User             string        `json:"user,omitempty"`
}

ChatRequest describes a chat completion request.

type ChatResponse

type ChatResponse struct {
	ID      string `json:"id"`
	Choices []struct {
		FinishReason string `json:"finish_reason"`
		Index        int    `json:"index"`
		Message      struct {
			Content   string     `json:"content"`
			ToolCalls []ToolCall `json:"tool_calls"`
			Role      string     `json:"role"`
		} `json:"message"`
		LogProbs []LogProb `json:"logprobs"`
	} `json:"choices"`
	Created           int    `json:"created"`
	Model             string `json:"model"`
	SystemFingerprint string `json:"system_fingerprint"`
	Object            string `json:"object"`
	Usage             struct {
		CompletionTokens int `json:"completion_tokens"`
		PromptTokens     int `json:"prompt_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

ChatResponse describes a chat completion response.

type Choice

type Choice struct {
	Delta        Delta  `json:"delta"`
	FinishReason string `json:"finish_reason"`
	Index        int    `json:"index"`
}

Choice represents a chat completion chunk choice in the stream chat completion.

type Client

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

Client is a client for the OpenAI API.

func New

func New(token string) *Client

New creates a new Client using the given token.

func (*Client) Chat

func (c *Client) Chat(ctx context.Context, req *ChatRequest) (*ChatResponse, error)

Chat performs a chat completion request and returns the completion.

func (*Client) ChatStream

func (c *Client) ChatStream(ctx context.Context, req *ChatRequest, callback StreamCallback) error

ChatStream performs a chat completion request and streams the completion to the callback.

func (*Client) CreateImage

func (c *Client) CreateImage(ctx context.Context, req *CreateImageRequest) (*ImageResponse, error)

CreateImage performs an image request and returns the images.

func (*Client) CreateSpeech

func (c *Client) CreateSpeech(ctx context.Context, req *CreateSpeachRequest) (*SpeechResponse, error)

CreateSpeech performs a speech request and returns the file type and content.

func (*Client) CreateTranscription

func (c *Client) CreateTranscription(ctx context.Context, req *CreateTranscriptionRequest) (*TranscriptionResponse, error)

CreateTranscription performs a transcription request and returns the transcript.

func (*Client) CreateTranslation

func (c *Client) CreateTranslation(ctx context.Context, req *CreateTranslationRequest) (*TranslationResponse, error)

CreateTranslation performs a translation request and returns the translated text.

func (*Client) EditImage

func (c *Client) EditImage(ctx context.Context, req *EditImageRequest) (*ImageResponse, error)

EditImage performs an image editing request and returns the edited images.

func (*Client) Embed

func (c *Client) Embed(ctx context.Context, req *EmbedRequest) (*EmbedResponse, error)

Embed performs an embedding request and returns the embeddings.

func (*Client) ListModels

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

ListModels performs a model list request and returns the models.

func (*Client) RetrieveModel

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

RetrieveModel performs a model retrieve request and returns the model.

type Content

type Content interface {
	Type() string
}

Content represents the content of a message.

type CreateImageRequest

type CreateImageRequest struct {
	Prompt         string      `json:"prompt"`
	Model          ImageModel  `json:"model,omitempty"`
	N              int         `json:"n,omitempty"`
	Quality        string      `json:"quality,omitempty"`
	ResponseFormat ImageFormat `json:"response_format,omitempty"`
	Size           ImageSize   `json:"size,omitempty"`
	Style          string      `json:"style,omitempty"`
	User           string      `json:"user,omitempty"`
}

CreateImageRequest describes an image request.

type CreateSpeachRequest

type CreateSpeachRequest struct {
	Model          SpeechModel  `json:"model"`
	Input          string       `json:"input"`
	Voice          SpeechVoice  `json:"voice"`
	ResponseFormat SpeechFormat `json:"response_format,omitempty"`
	Speed          float32      `json:"speed,omitempty"`
}

CreateSpeachRequest describes a speech request.

type CreateTranscriptionRequest

type CreateTranscriptionRequest struct {
	File                   string             `json:"file"`
	Model                  TranscriptionModel `json:"model"`
	Language               string             `json:"language,omitempty"`
	Prompt                 string             `json:"prompt,omitempty"`
	ResponseFormat         TranscriptFormat   `json:"response_format,omitempty"`
	Temperature            float32            `json:"temperature,omitempty"`
	TimestampGranularities []string           `json:"timestamp_granularities,omitempty"`
}

CreateTranscribeRequest describes a transcription request.

func (*CreateTranscriptionRequest) AddFields

func (req *CreateTranscriptionRequest) AddFields(writer *multipart.Writer) error

AddFields adds fields to the multipart form data.

type CreateTranslationRequest

type CreateTranslationRequest struct {
	File           string             `json:"file"`
	Model          TranscriptionModel `json:"model"`
	Prompt         string             `json:"prompt,omitempty"`
	ResponseFormat TranscriptFormat   `json:"response_format,omitempty"`
	Temperature    float32            `json:"temperature,omitempty"`
}

CreateTranslationRequest describes a translation request.

func (*CreateTranslationRequest) AddFields

func (req *CreateTranslationRequest) AddFields(writer *multipart.Writer) error

AddFields adds fields to the multipart form data.

type Delta

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

Delta represents a streaming delta in the stream chat completion.

type EditImageRequest

type EditImageRequest struct {
	Image          string      `json:"image"`
	Prompt         string      `json:"prompt"`
	Mask           string      `json:"mask,omitempty"`
	Model          ImageModel  `json:"model,omitempty"`
	N              int         `json:"n,omitempty"`
	Size           ImageSize   `json:"size,omitempty"`
	ResponseFormat ImageFormat `json:"response_format,omitempty"`
	User           string      `json:"user,omitempty"`
}

EditImageRequest describes an image editing request.

func (*EditImageRequest) AddFields

func (req *EditImageRequest) AddFields(writer *multipart.Writer) error

AddFields adds fields to the multipart form data.

type EmbedRequest

type EmbedRequest struct {
	Input          []string       `json:"input"`
	Model          EmbeddingModel `json:"model"`
	EncodingFormat EncodingFormat `json:"encoding_format,omitempty"`
	Dimensions     int            `json:"dimensions,omitempty"`
	User           string         `json:"user,omitempty"`
}

EmbedRequest describes an embedding request.

type EmbedResponse

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

EmbedResponse describes an embedding response.

type Embedding

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

Embedding describes an embedding.

type EmbeddingModel

type EmbeddingModel string

EmbeddingModel represents the Embedding model to use for the request.

const (
	ModelTextEmbeddingADA_002 EmbeddingModel = "text-embedding-ada-002"
	ModelTextEmbedding3_Small EmbeddingModel = "text-embedding-3-small"
	ModelTextEmbedding3_Large EmbeddingModel = "text-embedding-3-large"
)

type EncodingFormat

type EncodingFormat string

EncodingFormat represents the encoding format to use for the request.

const (
	FormatFloat  EncodingFormat = "float"
	FormatBase64 EncodingFormat = "base64"
)

type ErrorResponse

type ErrorResponse struct {
	Error struct {
		Type    string `json:"type"`
		Code    string `json:"code"`
		Message string `json:"message"`
		Param   string `json:"param"`
	} `json:"error"`
}

ErrorResponse describes an error response.

type ImageContent

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

ImageContent represents an image content in the chat.

func (ImageContent) MarshalJSON

func (c ImageContent) MarshalJSON() ([]byte, error)

MarshalJSON marshals the image content to JSON.

func (ImageContent) Type

func (c ImageContent) Type() string

Type returns the type of the image content.

type ImageFormat

type ImageFormat string

ImageFormat represents the Image format to use for the request.

const (
	FormatURL        ImageFormat = "url"
	FormatBase64JSON ImageFormat = "b64_json"
)

type ImageModel

type ImageModel string

ImageModel represents the Image model to use for the request.

const (
	ModelDallE2 ImageModel = "dall-e-2"
	ModelDallE3 ImageModel = "dall-e-3"
)

type ImageResponse

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

ImageResponse describes an image response.

type ImageSize

type ImageSize string

ImageSize represents the Image size to use for the request.

const (
	Size256x256   ImageSize = "256x256"
	Size512x512   ImageSize = "512x512"
	Size1024x1024 ImageSize = "1024x1024"
	Size1792x1024 ImageSize = "1792x1024"
	Size1024x1792 ImageSize = "1024x1792"
)

type LanguageModel

type LanguageModel string

LanguageModel represents the Language model to use for the request.

const (
	ModelGPT3Dot5_Turbo           LanguageModel = "gpt-3.5-turbo"
	ModelGPT3Dot5_Turbo_16k       LanguageModel = "gpt-3.5-turbo-16k"
	ModelGPT3Dot5_Turbo_16k_0613  LanguageModel = "gpt-3.5-turbo-16k-0613"
	ModelGPT3Dot5_Turbo_0125      LanguageModel = "gpt-3.5-turbo-0125"
	ModelGPT3Dot5_Turbo_0613      LanguageModel = "gpt-3.5-turbo-0613"
	ModelGPT3Dot5_Turbo_1106      LanguageModel = "gpt-3.5-turbo-1106"
	ModelGPT3Dot5_Turbo_Instruct  LanguageModel = "gpt-3.5-turbo-instruct"
	ModelGPT4                     LanguageModel = "gpt-4"
	ModelGPT4_0613                LanguageModel = "gpt-4-0613"
	ModelGPT4_32k                 LanguageModel = "gpt-4-32k"
	ModelGPT4_32k_0613            LanguageModel = "gpt-4-32k-0613"
	ModelGPT4_0125_Preview        LanguageModel = "gpt-4-0125-preview"
	ModelGPT4_1106_Preview        LanguageModel = "gpt-4-1106-preview"
	ModelGPT4_Turbo               LanguageModel = "gpt-4-turbo"
	ModelGPT4_Turbo_Preview       LanguageModel = "gpt-4-turbo-preview"
	ModelGPT4_Vision_Preview      LanguageModel = "gpt-4-vision-preview"
	ModelGPT4_1106_Vision_Preview LanguageModel = "gpt-4-vision-preview-0613"
)

type ListModelsResponse

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

ListModelsResponse describes a model list response.

type LogProb

type LogProb struct {
	Token       string  `json:"token"`
	LogProb     float32 `json:"logprob"`
	Bytes       []byte  `json:"bytes"`
	TopLogProbs []struct {
		Token   string  `json:"token"`
		LogProb float32 `json:"logprob"`
		Bytes   []byte  `json:"bytes"`
	} `json:"top_logprobs"`
}

LogProb describes a log probability.

type Message

type Message interface {
	Role() Role
}

Message represents a message in the chat.

type Model

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

Model represents a model.

type MultipartFormDataRequest

type MultipartFormDataRequest interface {
	AddFields(writer *multipart.Writer) error
}

MultipartFormDataRequest is an interface for requests that require multipart form data.

type Role

type Role string

Role represents the role of the user in the chat.

const (
	RoleUser      Role = "user"
	RoleSystem    Role = "system"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

type SpeechFormat

type SpeechFormat string

SpeechFormat represents the Speech format to use for the request.

const (
	FormatAAC  SpeechFormat = "aac"
	FormatFLAC SpeechFormat = "flac"
	FormatMP3  SpeechFormat = "mp3"
	FormatOpus SpeechFormat = "opus"
	FormatPCM  SpeechFormat = "pcm"
	FormatWAV  SpeechFormat = "wav"
)

type SpeechModel

type SpeechModel string

SpeechModel represents the Speech model to use for the request.

const (
	ModelTTS1    SpeechModel = "tts-1"
	ModelTTS1_HD SpeechModel = "tts-1-hd"
)

type SpeechResponse

type SpeechResponse struct {
	Format  SpeechFormat `json:"format"`
	Content []byte       `json:"content"`
}

SpeechResponse describes a speech response.

type SpeechVoice

type SpeechVoice string

SpeechVoice represents the Speech voice to use for the request.

const (
	VoiceAlloy   SpeechVoice = "alloy"
	VoiceEcho    SpeechVoice = "echo"
	VoiceFable   SpeechVoice = "fable"
	VoiceNova    SpeechVoice = "nova"
	VoiceOnyx    SpeechVoice = "onyx"
	VoiceShimmer SpeechVoice = "shimmer"
)

type StreamCallback

type StreamCallback func(ctx context.Context, chunk *ChatChunk)

StreamCallback is a callback function for streaming chat completion.

type SystemMessage

type SystemMessage struct {
	Content string `json:"content"`
	Name    string `json:"name,omitempty"`
}

SystemMessage represents a system message in the chat.

func (SystemMessage) MarshalJSON

func (m SystemMessage) MarshalJSON() ([]byte, error)

MarshalJSON marshals the system message to JSON.

func (SystemMessage) Role

func (m SystemMessage) Role() Role

Role returns the system role for the system message.

type TextContent

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

TextContent represents a text content in the chat.

func (TextContent) MarshalJSON

func (c TextContent) MarshalJSON() ([]byte, error)

MarshalJSON marshals the text content to JSON.

func (TextContent) Type

func (c TextContent) Type() string

Type returns the type of the text content.

type Tool

type Tool struct {
	Name        string         `json:"name"`
	Description string         `json:"description"`
	Parameters  map[string]any `json:"parameters"`
}

Tool represents a tool in the chat.

type ToolCall

type ToolCall struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	Function struct {
		Name      string `json:"name"`
		Arguments string `json:"arguments"`
	} `json:"function"`
}

ToolCall represents a tool call in the chat.

type ToolChoice

type ToolChoice struct {
	Type     string `json:"type"`
	Function struct {
		Name string `json:"name"`
	} `json:"function"`
}

ToolChoice represents a tool choice in the chat.

type ToolMessage

type ToolMessage struct {
	Content    string `json:"content"`
	ToolCallID string `json:"tool_call_id"`
}

ToolMessage represents a tool message in the chat.

func (ToolMessage) MarshalJSON

func (m ToolMessage) MarshalJSON() ([]byte, error)

MarshalJSON marshals the tool message to JSON.

func (ToolMessage) Role

func (m ToolMessage) Role() Role

Role returns the tool role for the tool message.

type TranscriptFormat

type TranscriptFormat string

TranscriptFormat represents the Transcript format to use for the request.

const (
	FormatJSON TranscriptFormat = "json"
	FormatText TranscriptFormat = "text"
)

type TranscriptionModel

type TranscriptionModel string

TranscriptionModel represents the Transcript model to use for the request.

const (
	ModelWhisper1 TranscriptionModel = "whisper-1"
)

type TranscriptionResponse

type TranscriptionResponse struct {
	Task     string  `json:"task"`
	Language string  `json:"language"`
	Duration float32 `json:"duration"`
	Text     string  `json:"text"`
	Words    []struct {
		Word  string  `json:"word"`
		Start float32 `json:"start"`
		End   float32 `json:"end"`
	} `json:"words"`
	Segments []struct {
		ID               int     `json:"id"`
		Seek             int     `json:"seek"`
		Start            float32 `json:"start"`
		End              float32 `json:"end"`
		Text             string  `json:"text"`
		Tokens           []int   `json:"tokens"`
		Temperature      float32 `json:"temperature"`
		AvgLogProb       float32 `json:"avg_log_prob"`
		CompressionRatio float32 `json:"compression_ratio"`
		NoSpeechProb     float32 `json:"no_speech_prob"`
	} `json:"segments"`
}

TranscriptionResponse describes a transcription response.

type TranslationResponse

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

TranslationResponse describes a translation response.

type UserMessage

type UserMessage struct {
	Content []Content `json:"content"`
	Name    string    `json:"name,omitempty"`
}

UserMessage represents a user message in the chat.

func (UserMessage) MarshalJSON

func (m UserMessage) MarshalJSON() ([]byte, error)

MarshalJSON marshals the user message to JSON.

func (UserMessage) Role

func (m UserMessage) Role() Role

Role returns the user role for the user message.

Jump to

Keyboard shortcuts

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