openai

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: May 14, 2024 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

openai implements an API client for OpenAI https://platform.openai.com/docs/api-reference

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func OptOrganization

func OptOrganization(value string) client.ClientOpt

Set an organization where the user has access to multiple organizations

Types

type Chat

type Chat struct {
	Id                string           `json:"id"`
	Object            string           `json:"object"`
	Created           int64            `json:"created"`
	Model             string           `json:"model"`
	SystemFingerprint string           `json:"system_fingerprint,omitempty"`
	Choices           []*MessageChoice `json:"choices"`
	Usage             struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

A chat completion object

type Client

type Client struct {
	*client.Client
}

func New

func New(ApiKey string, opts ...client.ClientOpt) (*Client, error)

func (*Client) Chat

func (c *Client) Chat(messages []*Message, opts ...Opt) (Chat, error)

Chat creates a model response for the given chat conversation.

func (*Client) CreateEmbedding

func (c *Client) CreateEmbedding(content any, opts ...Opt) (schema.Embeddings, error)

CreateEmbedding creates an embedding from a string or array of strings

func (*Client) CreateImages

func (c *Client) CreateImages(prompt string, opts ...Opt) ([]*Image, error)

CreateImage generates one or more images from a prompt

func (*Client) DeleteModel

func (c *Client) DeleteModel(model string) error

Delete a fine-tuned model. You must have the Owner role in your organization to delete a model.

func (*Client) GetModel

func (c *Client) GetModel(model string) (schema.Model, error)

GetModel returns one model

func (*Client) ListModels

func (c *Client) ListModels() ([]schema.Model, error)

ListModels returns all the models

func (*Client) Speech added in v0.0.3

func (c *Client) Speech(w io.Writer, voice, text string, opts ...Opt) (int64, error)

Creates audio for the given text, outputs to the writer and returns the number of bytes written

func (*Client) Transcribe added in v0.0.3

func (c *Client) Transcribe(r io.Reader, opts ...Opt) (*Transcription, error)

Transcribes audio from audio data

func (*Client) Translate added in v0.0.3

func (c *Client) Translate(r io.Reader, opts ...Opt) (*Transcription, error)

Translate audio into English

func (*Client) WriteImage

func (c *Client) WriteImage(w io.Writer, image *Image) (int, error)

WriteImage writes an image and returns the number of bytes written

type Image

type Image struct {
	Url           string `json:"url,omitempty"`
	Data          string `json:"b64_json,omitempty"`
	RevisedPrompt string `json:"revised_prompt,omitempty"`
}

An image

type Message

type Message struct {
	Role      string              `json:"role"`
	Content   MessageContentArray `json:"content,omitempty"`
	Name      string              `json:"name,omitempty"`
	ToolCalls []struct {
		Id       string `json:"id"`
		Type     string `json:"type"`
		Function struct {
			Name      string `json:"name"`
			Arguments string `json:"arguments"`
		} `json:"function"`
	} `json:"tool_calls,omitempty"`
	ToolCallId string `json:"tool_call_id,omitempty"`
}

A message choice object

func NewMessage

func NewMessage(role string, text ...string) *Message

func (*Message) AppendImageFile

func (msg *Message) AppendImageFile(file ...string) *Message

func (*Message) AppendImageUrl

func (msg *Message) AppendImageUrl(url ...string) *Message

func (*Message) AppendText

func (msg *Message) AppendText(text ...string) *Message

type MessageChoice

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

A message choice object

type MessageContent

type MessageContent struct {
	Type      string                   `json:"type"`
	Text      *string                  `json:"text,omitempty"`
	ImageFile *MessageContentImageFile `json:"image_file,omitempty"`
	ImageUrl  *MessageContentImageUrl  `json:"image_url,omitempty"`
}

Message content

type MessageContentArray

type MessageContentArray []MessageContent

A message content array

func (MessageContentArray) Flatten

func (arr MessageContentArray) Flatten() string

Return the text of the message

func (*MessageContentArray) UnmarshalJSON

func (c *MessageContentArray) UnmarshalJSON(data []byte) error

type MessageContentImageFile

type MessageContentImageFile struct {
	File string `json:"file_id"`
}

Message content image file

type MessageContentImageUrl

type MessageContentImageUrl struct {
	Url string `json:"url"`
}

Message content image url

type Opt

type Opt func(Request) error

type ChatCompletionOpt func(*chatRequest) error type ImageOpt func(*imageRequest) error

func OptCount

func OptCount(value int) Opt

How many chat choices or images to return

func OptFrequencyPenalty

func OptFrequencyPenalty(value float64) Opt

Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.

func OptFunction

func OptFunction(name, description string, parameters ...ToolParameter) Opt

When set, system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result.

func OptLanguage added in v0.0.3

func OptLanguage(language string) Opt

The language for transcription. Supplying the input language in ISO-639-1 format will improve accuracy and latency.

func OptMaxTokens

func OptMaxTokens(value int) Opt

How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep n as 1 to minimize costs.

func OptModel

func OptModel(value string) Opt

ID of the model to use

func OptPresencePenalty

func OptPresencePenalty(value float64) Opt

Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.

func OptPrompt added in v0.0.3

func OptPrompt(prompt string) Opt

An optional text to guide the model's style or continue a previous audio segment. The prompt should match the audio language.

func OptQuality

func OptQuality(value string) Opt

The quality of the image that will be generated. hd creates images with finer details and greater consistency across the image. This param is only supported for dall-e-3.

func OptResponseFormat

func OptResponseFormat(value string) Opt

Format of the returned response, use "json_format" to enable JSON mode, which guarantees the message the model generates is valid JSON. Important: when using JSON mode, you must also instruct the model to produce JSON yourself via a system or user message.

func OptSeed

func OptSeed(value int) Opt

When set, system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result.

func OptSize

func OptSize(w, h uint) Opt

The size of the generated images. Must be one of 256x256, 512x512, or 1024x1024 for dall-e-2. Must be one of 1024x1024, 1792x1024, or 1024x1792 for dall-e-3 models.

func OptSpeed added in v0.0.3

func OptSpeed(speed float32) Opt

The speed of the generated audio. Select a value from 0.25 to 4.0. 1.0 is the default.

func OptStream

func OptStream(value bool) Opt

Partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE]

func OptStyle

func OptStyle(style string) Opt

The style of the generated images. Must be one of vivid or natural. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images. This param is only supported for dall-e-3.

func OptTemperature

func OptTemperature(value float64) Opt

When set, system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result.

type Request

type Request interface {
	// contains filtered or unexported methods
}

An abstract request object

type Tool

type Tool struct {
	Type     string        `json:"type"`
	Function *ToolFunction `json:"function,omitempty"`
}

A tool

type ToolFunction

type ToolFunction struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Parameters  *ToolParameters `json:"parameters"`
}

A tool function

type ToolParameter

type ToolParameter struct {
	Name        string   `json:"-"`
	Type        string   `json:"type"`
	Enum        []string `json:"enum,omitempty"`
	Description string   `json:"description"`
	Required    bool     `json:"-"`
}

Tool function call parameter

type ToolParameters

type ToolParameters struct {
	Type       string                   `json:"type"`
	Properties map[string]ToolParameter `json:"properties"`
	Required   []string                 `json:"required"`
}

Tool function parameters

type Transcription added in v0.0.3

type Transcription struct {
	Task     string  `json:"task,omitempty"`
	Language string  `json:"language,omitempty"` // The language of the input audio.
	Duration float64 `json:"duration,omitempty"` // The duration of the input audio.
	Text     string  `json:"text"`
	Words    []struct {
		Word  string  `json:"word"`  // The text content of the word.
		Start float64 `json:"start"` // Start time of the word in seconds.
		End   float64 `json:"end"`   // End time of the word in seconds.
	} `json:"words,omitempty"` // Extracted words and their corresponding timestamps.
	Segments []struct {
		Id                  uint    `json:"id"`
		Seek                uint    `json:"seek"`
		Start               float64 `json:"start"`
		End                 float64 `json:"end"`
		Text                string  `json:"text"`
		Tokens              []uint  `json:"tokens"`                      // Array of token IDs for the text content.
		Temperature         float64 `json:"temperature,omitempty"`       // Temperature parameter used for generating the segment.
		AvgLogProbability   float64 `json:"avg_logprob,omitempty"`       // Average logprob of the segment. If the value is lower than -1, consider the logprobs failed.
		CompressionRatio    float64 `json:"compression_ratio,omitempty"` // Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed.
		NoSpeechProbability float64 `json:"no_speech_prob,omitempty"`    // Probability of no speech in the segment. If the value is higher than 1.0 and the avg_logprob is below -1, consider this segment silent.
	} `json:"segments,omitempty"`
}

Represents a transcription response returned by model, based on the provided input.

func (*Transcription) Unmarshal added in v0.0.3

func (resp *Transcription) Unmarshal(mimetype string, r io.Reader) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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