openai

package
v0.13.0-test.2 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2024 License: Apache-2.0 Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

The openai package provides objects that conform to the OpenAI API specification. It can be used with OpenAI, as well as other services that conform to the OpenAI API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AssistantMessage

type AssistantMessage struct {

	// The tool calls generated by the model, such as function calls.
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	// contains filtered or unexported fields
}

An assistant message object.

func NewAssistantMessage

func NewAssistantMessage(content string, toolCalls ...ToolCall) *AssistantMessage

Creates a new assistant message object.

type ChatModel

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

Provides input and output types that conform to the OpenAI Chat API, as described in the API Reference docs.

func (*ChatModel) CreateInput

func (m *ChatModel) CreateInput(messages ...Message) (*ChatModelInput, error)

Creates an input object for the OpenAI Chat API.

type ChatModelInput

type ChatModelInput struct {

	// The name of the model to use for the chat.
	//
	// Must be the exact string expected by the model provider.
	// For example, "gpt-3.5-turbo".
	Model string `json:"model"`

	// The list of messages to send to the chat model.
	Messages []Message `json:"messages"`

	// 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.
	FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`

	// Modifies the likelihood of specified tokens appearing in the completion.
	//
	// Accepts an object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100.
	// Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model,
	// but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban
	// or exclusive selection of the relevant token.
	LogitBias map[string]float64 `json:"logit_bias,omitempty"`

	// Whether to return log probabilities of the output tokens or not,
	//
	// If true, returns the log probabilities of each output token returned in the content of message.
	Logprobs bool `json:"logprobs,omitempty"`

	// An integer between 0 and 20 specifying the number of most likely tokens to return at each token position,
	// each with an associated log probability. [Logprobs] must be set to true if this parameter is used.
	TopLogprobs int `json:"top_logprobs,omitempty"`

	// The maximum number of tokens to generate in the chat completion.
	//
	// The default (0) is equivalent to 4096.
	MaxTokens int `json:"max_tokens,omitempty"`

	// The number of completions to generate for each prompt.
	//
	// The default (0) is equivalent to 1.
	N int `json:"n,omitempty"`

	// 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.
	PresencePenalty float64 `json:"presence_penalty,omitempty"`

	// Specifies the requested format for the response.
	//  - ResponseFormatText requests a plain text string.
	//  - ResponseFormatJson requests a JSON object.
	//  - ResponseFormatJsonSchema requests a JSON object that conforms to the provided JSON schema.
	//
	// The default is ResponseFormatText.
	ResponseFormat ResponseFormat `json:"response_format"`

	// If specified, the model will make a best effort to sample deterministically,
	// such that repeated requests with the same seed and parameters should return
	// the same result.
	//
	// Determinism is not guaranteed, and you should use the SystemFingerprint response
	// parameter to monitor changes in the backend.
	//
	// The default (0) is equivalent to a random seed.
	Seed int `json:"seed,omitempty"`

	// Specifies the latency tier to use for processing the request.
	//  - ServiceTierAuto utilizes scale tier credits until they are exhausted.
	//  - ServiceTierDefault processes the request using the default OpenAI service
	//    tier with a lower uptime SLA and no latency guarantee.
	//
	// The default is ServiceTierAuto.
	ServiceTier ServiceTier `json:"service_tier,omitempty"`

	// Up to 4 sequences where the API will stop generating further tokens.
	Stop []string `json:"stop,omitempty"`

	// A number between 0.0 and 2.0 that controls the sampling temperature.
	//
	// Higher values like 0.8 will make the output more random, while lower values
	// like 0.2 will make it more focused and deterministic.
	//
	// We generally recommend altering this or TopP but not both.
	//
	// The default value is 1.0.
	Temperature float64 `json:"temperature"`

	// An alternative to sampling with temperature, called nucleus sampling, where the model
	// considers the results of the tokens with TopP probability mass.
	//
	// For example, 0.1 means only the tokens comprising the top 10% probability mass are considered.
	//
	// We generally recommend altering this or Temperature but not both.
	//
	// The default value is 1.0.
	TopP float64 `json:"top_p"`

	// A list of tools the model may call. Currently, only functions are supported as a tool.
	// Use this to provide a list of functions the model may generate JSON inputs for.
	// A max of 128 functions are supported.
	Tools []Tool `json:"tools,omitempty"`

	// Controls which (if any) tool is called by the model.
	//  - ToolChoiceNone means the model will not call any tool and instead generates a message.
	//  - ToolChoiceAuto means the model can pick between generating a message or calling one or more tools.
	//  - ToolChoiceRequired means the model must call one or more tools.
	//  - ToolChoiceFunction(name) forces the model to call a specific tool.
	//
	// The default is ToolChoiceAuto when tools are present, and ToolChoiceNone otherwise.
	ToolChoice ToolChoice `json:"tool_choice,omitempty"`

	// Whether to enable parallel function calling during tool use.
	//
	// The default is true.
	ParallelToolCalls bool `json:"parallel_tool_calls"`

	// The user ID to associate with the request, as described in the [documentation].
	// If not specified, the request will be anonymous.
	//
	// [documentation]: https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids
	User string `json:"user,omitempty"`
}

The input object for the OpenAI Chat API.

func (*ChatModelInput) MarshalJSON

func (mi *ChatModelInput) MarshalJSON() ([]byte, error)

type ChatModelOutput

type ChatModelOutput struct {

	// A unique identifier for the chat completion.
	Id string `json:"id"`

	// The name of the output object type returned by the API.
	// This will always be "chat.completion".
	Object string `json:"object"`

	// A list of chat completion choices. Can be more than one if n is greater than 1 in the input options.
	Choices []Choice `json:"choices"`

	// The Unix timestamp (in seconds) of when the chat completion was created.
	Created int `json:"created"`

	// The name of the model used to generate the chat.
	// In most cases, this will match the requested model field in the input.
	Model string `json:"model"`

	// The service tier used for processing the request.
	//
	// This field is only included if the ServiceTier parameter is specified in the request.
	ServiceTier ServiceTier `json:"service_tier"`

	// This fingerprint represents the OpenAI backend configuration that the model runs with.
	//
	// Can be used in conjunction with the Seed request parameter to understand when backend changes
	// have been made that might impact determinism.
	SystemFingerprint string `json:"system_fingerprint"`

	// The usage statistics for the request.
	Usage Usage `json:"usage"`
}

The output object for the OpenAI Chat API.

type Choice

type Choice struct {

	// The reason the model stopped generating tokens.
	//
	// Possible values are:
	//  - "stop" if the model hit a natural stop point or a provided stop sequence
	//  - "length" if the maximum number of tokens specified in the request was reached
	//  - "content_filter" if content was omitted due to a flag from content filters
	//  - "tool_calls" if the model called a tool
	FinishReason string `json:"finish_reason"`

	// The index of the choice in the list of choices.
	Index int `json:"index"`

	// A chat completion message generated by the model.
	Message CompletionMessage `json:"message"`

	// Log probability information for the choice.
	Logprobs Logprobs `json:"logprobs"`
}

A completion choice object returned in the response.

type CompletionMessage

type CompletionMessage struct {

	// The refusal message generated by the model.
	Refusal string `json:"refusal,omitempty"`
	// contains filtered or unexported fields
}

A chat completion message generated by the model.

type Embedding

type Embedding struct {

	// The name of the output object type returned by the API.
	// This will always be "embedding".
	Object string `json:"object"`

	// The index of the input text that corresponds to this embedding.
	// Used when requesting embeddings for multiple texts.
	Index int `json:"index"`

	// The vector embedding of the input text.
	Embedding []float32 `json:"embedding"`
}

The output vector embeddings data.

type EmbeddingsModel

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

Provides input and output types that conform to the OpenAI Embeddings API, as described in the API Reference docs.

func (*EmbeddingsModel) CreateInput

func (m *EmbeddingsModel) CreateInput(content any) (*EmbeddingsModelInput, error)

Creates an input object for the OpenAI Embeddings API.

The content parameter can be any of:

  • A string representing the text to vectorize.
  • A slice of strings representing multiple texts to vectorize.
  • A slice of integers representing pre-tokenized text to vectorize.
  • A slice of slices of integers representing multiple pre-tokenized texts to vectorize.

NOTE: The input content must not exceed the maximum token limit of the model.

type EmbeddingsModelInput

type EmbeddingsModelInput struct {

	// The name of the model to use to generate the embeddings.
	//
	// Must be the exact string expected by the model provider.
	// For example, "text-embedding-3-small".
	Model string `json:"model"`

	// The input content to vectorize.
	Input any `json:"input"`

	// The format for the output embeddings.
	// The default ("") is equivalent to [EncodingFormatFloat], which is currently the only supported format.
	EncodingFormat EncodingFormat `json:"encoding_format,omitempty"`

	// The maximum number of dimensions for the output embeddings.
	// The default (0) indicates that the model's default number of dimensions will be used.
	Dimensions int `json:"dimensions,omitempty"`

	// The user ID to associate with the request, as described in the [documentation].
	// If not specified, the request will be anonymous.
	//
	// [documentation]: https://platform.openai.com/docs/guides/safety-best-practices/end-user-ids
	User string `json:"user,omitempty"`
}

The input object for the OpenAI Embeddings API.

type EmbeddingsModelOutput

type EmbeddingsModelOutput struct {

	// The name of the output object type returned by the API.
	// This will always be "list".
	Object string `json:"object"`

	// The name of the model used to generate the embeddings.
	// In most cases, this will match the requested model field in the input.
	Model string `json:"model"`

	// The usage statistics for the request.
	Usage Usage `json:"usage"`

	// The output vector embeddings data.
	Data []Embedding `json:"data"`
}

The output object for the OpenAI Embeddings API.

type EncodingFormat

type EncodingFormat string

The encoding format for the output embeddings.

const (
	// The output embeddings are encoded as an array of floating-point numbers.
	EncodingFormatFloat EncodingFormat = "float"

	// The output embeddings are encoded as a base64-encoded string,
	// containing an binary representation of an array of floating-point numbers.
	//
	// NOTE: This format is not currently supported.
	EncodingFormatBase64 EncodingFormat = "base64"
)

type FunctionCall

type FunctionCall struct {

	// The name of the function to call.
	Name string `json:"name"`

	// The arguments to call the function with, as generated by the model in JSON format.
	//
	// NOTE:
	// The model does not always generate valid JSON, and may hallucinate parameters not
	// defined by your function schema. Validate the arguments in your code before calling your function.
	Arguments string `json:"arguments"`
}

A function call object that the model may generate.

type FunctionDefinition

type FunctionDefinition struct {

	// The name of the function to be called.
	//
	// Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.
	Name string `json:"name"`

	// An optional description of what the function does, used by the model to choose when and how to call the function.
	Description string `json:"description,omitempty"`

	// Whether to enable strict schema adherence when generating the function call.
	// If set to true, the model will follow the exact schema defined in the parameters field.
	//
	// The default is false.
	//
	// See https://platform.openai.com/docs/guides/function-calling
	//
	// NOTE:
	// In order to guarantee strict schema adherence, disable parallel function calls
	// by setting ParallelToolCalls to false.
	//
	// See https://platform.openai.com/docs/guides/function-calling/parallel-function-calling-and-structured-outputs
	Strict bool `json:"strict,omitempty"`

	// The parameters the functions accepts, described as a JSON Schema object.
	//
	// See https://platform.openai.com/docs/guides/function-calling
	Parameters utils.RawJsonString `json:"parameters,omitempty"`
}

The definition of a function that can be called by the model.

type Logprobs

type Logprobs struct {
	// A list of message content tokens with log probability information.
	Content []LogprobsContent `json:"content"`
}

Log probability information for a choice.

type LogprobsContent

type LogprobsContent struct {
	LogprobsContentObject

	// List of the most likely tokens and their log probability, at this token position.
	// In rare cases, there may be fewer than the number of requested TopLogprobs returned.
	TopLogprobs []LogprobsContentObject `json:"top_logprobs"`
}

Log probability information for a message content token.

type LogprobsContentObject

type LogprobsContentObject struct {
	// The token.
	Token string `json:"token"`

	// The log probability of this token, if it is within the top 20 most likely tokens.
	// Otherwise, the value -9999.0 is used to signify that the token is very unlikely.
	Logprob float64 `json:"logprob"`

	// A list of integers representing the UTF-8 bytes representation of the token.
	//
	// Useful in instances where characters are represented by multiple tokens and their byte
	// representations must be combined to generate the correct text representation.
	// Can be nil if there is no bytes representation for the token.
	Bytes []byte `json:"bytes"`
}

Log probability information for the most likely tokens at a given position.

type Message

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

An interface to any message object.

type ResponseFormat

type ResponseFormat struct {

	// The type of response format.
	Type string `json:"type"`

	// The JSON schema to use for the response format.
	JsonSchema utils.RawJsonString `json:"json_schema,omitempty"`
}

An object specifying the format that the model must output.

var (
	// Instructs the model to output the response as a plain text string.
	// This is the default response format.
	ResponseFormatText ResponseFormat = ResponseFormat{Type: "text"}

	// Instructs the model to output the response as a JSON object.
	//  - You must also instruct the model to produce JSON yourself via a system or user message.
	//  - Additionally, if you need an array you must ask for an object that wraps the array,
	//    because the model will not reliably produce arrays directly (ie., there is no "json_array" option).
	ResponseFormatJson ResponseFormat = ResponseFormat{Type: "json_object"}

	// Enables Structured Outputs which guarantees the model will match your supplied JSON schema.
	//
	// See https://platform.openai.com/docs/guides/structured-outputs
	ResponseFormatJsonSchema = func(jsonSchema string) ResponseFormat {
		return ResponseFormat{Type: "json_schema", JsonSchema: utils.RawJsonString(jsonSchema)}
	}
)

type ServiceTier

type ServiceTier string

The OpenAI service tier used to process the request.

const (
	// The OpenAI system will utilize scale tier credits until they are exhausted.
	ServiceTierAuto ServiceTier = "auto"

	// The request will be processed using the default OpenAI service tier with a lower
	// uptime SLA and no latency guarantee.
	ServiceTierDefault ServiceTier = "default"
)

type SystemMessage

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

A system message object.

func NewSystemMessage

func NewSystemMessage(content string) *SystemMessage

Creates a new system message object.

type Tool

type Tool struct {

	// The type of the tool. Currently, only `"function"` is supported.
	Type string `json:"type"`

	// The definition of the function.
	Function FunctionDefinition `json:"function"`
}

A tool object that the model may call.

func NewTool

func NewTool() Tool

Creates a new tool object.

type ToolCall

type ToolCall struct {

	// The ID of the tool call.
	Id string `json:"id"`

	// The type of the tool. Currently, only `"function"` is supported.
	Type string `json:"type"`

	// The function that the model called.
	Function FunctionCall `json:"function"`
}

A tool call object that the model may generate.

func NewToolCall

func NewToolCall(id, name, arguments string) ToolCall

Creates a new tool call object.

type ToolChoice

type ToolChoice struct {

	// The type of tool to call.
	Type string `json:"type"`

	// The function to call.
	Function struct {
		// The name of the function to call.
		Name string `json:"name"`
	} `json:"function,omitempty"`
}

An object specifying which tool the model should call.

var (
	// Directs the model to not call any tool and instead generates a message.
	ToolChoiceNone ToolChoice = ToolChoice{Type: "none"}

	// Directs the model to pick between generating a message or calling one or more tools.
	ToolChoiceAuto ToolChoice = ToolChoice{Type: "auto"}

	// Directs that the model must call one or more tools.
	ToolChoiceRequired ToolChoice = ToolChoice{Type: "required"}

	// Forces the model to call a specific tool.
	ToolChoiceFunction = func(name string) ToolChoice {
		c := ToolChoice{Type: "function"}
		c.Function.Name = name
		return c
	}
)

func (ToolChoice) MarshalJSON

func (tc ToolChoice) MarshalJSON() ([]byte, error)

type ToolMessage

type ToolMessage struct {

	// The tool call that this message is responding to.
	ToolCallId string `json:"tool_call_id"`
	// contains filtered or unexported fields
}

A tool message object.

func NewToolMessage

func NewToolMessage(content, toolCallId string) *ToolMessage

Creates a new tool message object.

type Usage

type Usage struct {

	// The number of completion tokens used.
	CompletionTokens int `json:"completion_tokens"`

	// The number of prompt tokens used.
	PromptTokens int `json:"prompt_tokens"`

	// The total number of tokens used.
	TotalTokens int `json:"total_tokens"`
}

The usage statistics returned by the OpenAI API.

type UserMessage

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

A user message object.

func NewUserMessage

func NewUserMessage(content string) *UserMessage

Creates a new user message object.

Jump to

Keyboard shortcuts

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