Documentation
¶
Overview ¶
Package openai provides an interface to OpenAI's language models.
Token Limits ¶
For setting token limits with OpenAI models, use openai.WithMaxCompletionTokens() for clarity. The OpenAI API now uses max_completion_tokens as the field for limiting output tokens.
// Recommended for clarity:
llm.GenerateContent(ctx, messages,
openai.WithMaxCompletionTokens(100),
)
// Also works (backward compatible):
llm.GenerateContent(ctx, messages,
llms.WithMaxTokens(100),
)
Both options set the same underlying field. By default, the implementation sends max_completion_tokens (modern field). For older OpenAI-compatible servers that only support max_tokens, use WithLegacyMaxTokensField():
llm.GenerateContent(ctx, messages,
llms.WithMaxTokens(100),
openai.WithLegacyMaxTokensField(), // Forces use of max_tokens field
)
Index ¶
- Constants
- Variables
- func ExtractToolParts(msg *ChatMessage) ([]llms.ContentPart, []llms.ToolCall, []llms.ToolCallResponse)
- func MapError(err error) error
- func WithExtraBody(extraBody map[string]any) llms.CallOption
- func WithLegacyMaxTokensField() llms.CallOption
- func WithMaxCompletionTokens(maxTokens int) llms.CallOption
- type APIType
- type ChatMessage
- type ErrStructuredOutputRefusal
- type LLM
- func (o *LLM) Call(ctx context.Context, prompt string, options ...llms.CallOption) (string, error)
- func (o *LLM) CreateEmbedding(ctx context.Context, inputTexts []string) ([][]float32, error)
- func (o *LLM) GenerateContent(ctx context.Context, messages []llms.MessageContent, ...) (resp *llms.ContentResponse, err error)
- func (o *LLM) GenerateTTS(ctx context.Context, input string, options ...llms.CallOption) ([]byte, error)
- type Option
- func WithAPIType(apiType APIType) Option
- func WithAPIVersion(apiVersion string) Option
- func WithBaseURL(baseURL string) Option
- func WithCallback(callbackHandler callbacks.Handler) Option
- func WithEmbeddingDimensions(dimensions int) Option
- func WithEmbeddingModel(embeddingModel string) Option
- func WithHTTPClient(client openaiclient.Doer) Option
- func WithModel(model string) Option
- func WithModernReasoningFormat() Option
- func WithOrganization(organization string) Option
- func WithPreserveReasoningContent() Option
- func WithResponseFormat(responseFormat *ResponseFormat) Option
- func WithToken(token string) Option
- func WithUsingReasoningMaxTokens() Option
- type ResponseFormat
- type ResponseFormatJSONSchema
- type ResponseFormatJSONSchemaProperty
Constants ¶
const ( RoleSystem = "system" RoleAssistant = "assistant" RoleUser = "user" RoleFunction = "function" RoleTool = "tool" )
const ( APITypeOpenAI APIType = APIType(openaiclient.APITypeOpenAI) APITypeAzure = APIType(openaiclient.APITypeAzure) APITypeAzureAD = APIType(openaiclient.APITypeAzureAD) )
const (
DefaultAPIVersion = "2023-05-15"
)
Variables ¶
var ( ErrEmptyResponse = errors.New("no response") ErrMissingToken = errors.New("missing the OpenAI API key, set it in the OPENAI_API_KEY environment variable") //nolint:lll ErrMissingAzureModel = errors.New("model needs to be provided when using Azure API") ErrMissingAzureEmbeddingModel = errors.New("embeddings model needs to be provided when using Azure API") ErrUnexpectedResponseLength = errors.New("unexpected length of response") )
var ResponseFormatJSON = &ResponseFormat{Type: "json_object"} //nolint:gochecknoglobals
ResponseFormatJSON is the JSON response format.
Functions ¶
func ExtractToolParts ¶
func ExtractToolParts(msg *ChatMessage) ([]llms.ContentPart, []llms.ToolCall, []llms.ToolCallResponse)
ExtractToolParts extracts the tool parts from a message.
func WithExtraBody ¶
func WithExtraBody(extraBody map[string]any) llms.CallOption
WithExtraBody allows passing additional fields in the request body that will be sent to the OpenAI-compatible API. These fields will override any existing fields with the same name, allowing you to use provider-specific parameters not directly supported by the library.
Example usage:
llm.GenerateContent(ctx, messages,
openai.WithExtraBody(map[string]any{
"enable_thinking": false,
"chat_template_kwargs": map[string]any{
"enable_thinking": false,
},
}),
)
func WithLegacyMaxTokensField ¶
func WithLegacyMaxTokensField() llms.CallOption
WithLegacyMaxTokensField forces the use of the max_tokens field instead of max_completion_tokens. This is useful when connecting to older OpenAI-compatible inference servers that only support the max_tokens field and don't recognize max_completion_tokens.
Usage:
llm.GenerateContent(ctx, messages,
llms.WithMaxTokens(100),
openai.WithLegacyMaxTokensField(), // Forces use of max_tokens field
)
func WithMaxCompletionTokens ¶
func WithMaxCompletionTokens(maxTokens int) llms.CallOption
WithMaxCompletionTokens sets the max_completion_tokens field for token generation. This is the recommended way to limit tokens with OpenAI models.
Usage:
llm.GenerateContent(ctx, messages,
openai.WithMaxCompletionTokens(100),
)
Note: While llms.WithMaxTokens() still works for backward compatibility, WithMaxCompletionTokens is preferred for clarity when using OpenAI.
Types ¶
type APIType ¶
type APIType openaiclient.APIType
type ChatMessage ¶
type ChatMessage = openaiclient.ChatMessage
type ErrStructuredOutputRefusal ¶
ErrStructuredOutputRefusal reports that the model declined a structured-output request (OpenAI Structured Outputs). A refusal may legitimately not match the schema, so it is a distinct typed outcome rather than a validation failure. The usage-carrying ContentResponse is returned alongside this error.
func (*ErrStructuredOutputRefusal) Error ¶
func (e *ErrStructuredOutputRefusal) Error() string
type LLM ¶
func (*LLM) CreateEmbedding ¶
CreateEmbedding creates embeddings for the given input texts.
func (*LLM) GenerateContent ¶
func (o *LLM) GenerateContent(ctx context.Context, messages []llms.MessageContent, options ...llms.CallOption) (resp *llms.ContentResponse, err error)
GenerateContent implements the Model interface.
func (*LLM) GenerateTTS ¶
func (o *LLM) GenerateTTS(ctx context.Context, input string, options ...llms.CallOption) ([]byte, error)
Create Text to Speech.
type Option ¶
type Option func(*options)
Option is a functional option for the OpenAI client.
func WithAPIType ¶
WithAPIType passes the api type to the client. If not set, the default value is APITypeOpenAI.
func WithAPIVersion ¶
WithAPIVersion passes the api version to the client. If not set, the default value is DefaultAPIVersion.
func WithBaseURL ¶
WithBaseURL passes the OpenAI base url to the client. If not set, the base url is read from the OPENAI_BASE_URL environment variable. If still not set in ENV VAR OPENAI_BASE_URL, then the default value is https://api.openai.com/v1 is used.
func WithCallback ¶
WithCallback allows setting a custom Callback Handler.
func WithEmbeddingDimensions ¶
WithEmbeddingDimensions passes the OpenAI embeddings dimensions to the client. Requires a compatible model, test-embedding-3 or later. For more info, please check openai doc https://platform.openai.com/docs/api-reference/embeddings/create#embeddings-create-dimensions
func WithEmbeddingModel ¶
WithEmbeddingModel passes the OpenAI model to the client. Required when ApiType is Azure.
func WithHTTPClient ¶
func WithHTTPClient(client openaiclient.Doer) Option
WithHTTPClient allows setting a custom HTTP client. If not set, the default value is http.DefaultClient.
func WithModel ¶
WithModel passes the OpenAI model to the client. If not set, the model is read from the OPENAI_MODEL environment variable. Required when ApiType is Azure.
func WithModernReasoningFormat ¶
func WithModernReasoningFormat() Option
WithModernReasoningFormat includes "reasoning" key and object value in the request payload. Otherways, it will be sent as a "reasoning_effort" string value.
func WithOrganization ¶
WithOrganization passes the OpenAI organization to the client. If not set, the organization is read from the OPENAI_ORGANIZATION.
func WithPreserveReasoningContent ¶
func WithPreserveReasoningContent() Option
WithPreserveReasoningContent enables preservation of reasoning content in multi-turn conversations with tool calls. This is required for some LLM providers like Moonshot that expect reasoning_content field in assistant messages with tool calls.
func WithResponseFormat ¶
func WithResponseFormat(responseFormat *ResponseFormat) Option
WithResponseFormat allows setting a custom response format.
func WithToken ¶
WithToken passes the OpenAI API token to the client. If not set, the token is read from the OPENAI_API_KEY environment variable.
func WithUsingReasoningMaxTokens ¶
func WithUsingReasoningMaxTokens() Option
WithUsingReasoningMaxTokens allows to use reasoning max_tokens instead of effort. If reasoning max_tokens is set, it will be sent to the server instead of effort. Note: you must use this option within WithModernReasoningFormat(), otherwise it will be ignored.
type ResponseFormat ¶
type ResponseFormat = openaiclient.ResponseFormat
ResponseFormat is the response format for the OpenAI client.
type ResponseFormatJSONSchema ¶
type ResponseFormatJSONSchema = openaiclient.ResponseFormatJSONSchema
ResponseFormatJSONSchema is the JSON Schema response format in structured output.
type ResponseFormatJSONSchemaProperty ¶
type ResponseFormatJSONSchemaProperty = openaiclient.ResponseFormatJSONSchemaProperty
ResponseFormatJSONSchemaProperty is the JSON Schema property in structured output.