openai

package
v1.0.178 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2026 License: Apache-2.0 Imports: 21 Imported by: 1 module, 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

Package openai provides an llms.Model implementation for OpenAI-compatible APIs, including OpenAI and Azure OpenAI endpoints. Use options to select the provider style, model, base URL, token, and API version where applicable.

Example

mdl, err := openai.New(
    openai.WithProvider(openai.ProviderOpenAI),
    openai.WithToken(os.Getenv("OPENAI_API_KEY")),
    openai.WithModel("gpt-4o-mini"),
)
_ = mdl; _ = err

The models an OpenAI or OpenRouter account can call are listed with NewModelLister, which needs no model name, or with LLM.ListModels.

Index

Constants

View Source
const (
	RoleSystem    = "system"
	RoleAssistant = "assistant"
	RoleUser      = "user"
	RoleFunction  = "function"
	RoleTool      = "tool"
)
View Source
const (
	DefaultTokenEnvVarName        = "OPENAI_API_KEY"      //nolint:gosec
	DefaultModelEnvVarName        = "OPENAI_MODEL"        //nolint:gosec
	DefaultBaseURLEnvVarName      = "OPENAI_BASE_URL"     //nolint:gosec
	DefaultOrganizationEnvVarName = "OPENAI_ORGANIZATION" //nolint:gosec
	DefaultProjectEnvVarName      = "OPENAI_PROJECT"      //nolint:gosec
)
View Source
const (
	DefaultAPIVersion = "2023-05-15"
)
View Source
const DefaultOpenRouterTokenEnvVarName = "OPENROUTER_API_KEY" //nolint:gosec

Variables

View Source
var (
	ErrEmptyResponse              = errors.New("no response")
	ErrMissingToken               = errors.New("missing the OpenAI API key")
	ErrMissingOpenRouterToken     = errors.New("missing the OpenRouter API key")
	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")
)

Functions

func ExtractToolParts

func ExtractToolParts(msg *ChatMessage) ([]llms.ContentPart, []llms.ToolCall)

ExtractToolParts extracts the tool parts from a message.

func NewModelLister added in v1.0.173

func NewModelLister(opts ...Option) (llms.ModelLister, error)

NewModelLister returns a client that lists the models of an OPENAI or OPENROUTER account. It takes the options of New; no model name is needed. For any other provider type it returns llms.ErrModelListNotSupported.

Types

type ChatMessage

type ChatMessage = openaiclient.ChatMessage

type InferenceAPI added in v0.21.160

type InferenceAPI string

InferenceAPI selects which upstream OpenAI API the portable Infer method uses.

const (
	// InferenceAPIDefault selects Responses for ProviderOpenAI and Chat
	// Completions for every other OpenAI-compatible provider type.
	InferenceAPIDefault InferenceAPI = ""
	// InferenceAPIResponses uses POST /responses upstream.
	InferenceAPIResponses InferenceAPI = "responses"
	// InferenceAPIChat uses POST /chat/completions upstream.
	InferenceAPIChat InferenceAPI = "chat"
)

type LLM

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

func New

func New(opts ...Option) (*LLM, error)

New returns a new OpenAI LLM.

func (*LLM) CancelBatch added in v0.17.130

func (o *LLM) CancelBatch(ctx context.Context, batchID string) (*llms.BatchHandle, error)

CancelBatch implements llms.Batcher.

func (*LLM) CreateEmbedding

func (o *LLM) CreateEmbedding(ctx context.Context, inputTexts []string) ([][]float32, error)

CreateEmbedding creates embeddings for the given input texts.

func (*LLM) FetchBatchResults added in v0.17.130

func (o *LLM) FetchBatchResults(ctx context.Context, batchID string) ([]llms.BatchResult, error)

FetchBatchResults implements llms.Batcher. It refuses to read partial output: callers must wait until BatchHandle.Status.IsTerminal() returns true (typically by polling GetBatch).

func (*LLM) GenerateContent

func (o *LLM) GenerateContent(ctx context.Context, messages []llms.Message, options ...llms.CallOption) (*llms.ContentResponse, error)

GenerateContent implements the Model interface.

func (*LLM) GetBatch added in v0.17.130

func (o *LLM) GetBatch(ctx context.Context, batchID string) (*llms.BatchHandle, error)

GetBatch implements llms.Batcher.

func (*LLM) GetName added in v0.10.61

func (o *LLM) GetName() string

GetName implements the Model interface.

func (*LLM) GetProviderType added in v0.10.54

func (o *LLM) GetProviderType() llms.ProviderType

GetProviderType implements the Model interface.

func (*LLM) Infer added in v0.21.160

Infer performs one presence-preserving, non-streaming generation through the Responses API or Chat Completions depending on configuration.

func (*LLM) ListModels added in v1.0.173

func (o *LLM) ListModels(ctx context.Context) ([]llms.ModelInfo, error)

ListModels implements llms.ModelLister. It returns the models the account can call on OPENAI and OPENROUTER, in the provider's order.

OpenAI reports the announced shutdown date of a model; OpenRouter reports an expiration date, a display name and the reasoning effort levels. A model with such a date is llms.ModelLifecycleDeprecated and carries it in RetiresAt.

The other provider types served by this package do not advertise llms.CapabilityModels and return llms.ErrModelListNotSupported. On Azure the names a request can use are deployments, which only the management API lists.

func (*LLM) SubmitBatch added in v0.17.130

func (o *LLM) SubmitBatch(ctx context.Context, requests []llms.BatchRequest, options ...llms.BatchSubmitOption) (*llms.BatchHandle, error)

SubmitBatch implements llms.Batcher. It marshals each BatchRequest into a JSONL line, uploads the document as a file with purpose=batch, and creates a batch targeting either /v1/chat/completions or /v1/responses depending on whether the underlying provider configuration uses the Responses API.

func (*LLM) ValidateInference added in v0.21.160

func (o *LLM) ValidateInference(r llms.InferenceRequest) error

ValidateInference rejects controls the selected upstream API cannot express. Every OpenAI-compatible provider type is accepted; only the upstream dialect restricts controls.

type Option

type Option func(*options)

Option is a functional option for the OpenAI client.

func WithAPIVersion

func WithAPIVersion(apiVersion string) Option

WithAPIVersion passes the api version to the client. If not set, the default value is DefaultAPIVersion.

func WithAWSConfig added in v0.19.148

func WithAWSConfig(cfg *aws.Config) Option

WithAWSConfig passes the AWS config to the client.

func WithBaseURL

func WithBaseURL(baseURL string) Option

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 WithEffortPolicy added in v1.0.173

func WithEffortPolicy(policy llms.EffortPolicy) Option

WithEffortPolicy sets the reasoning effort used when a call requests none, and the highest effort any call may use. Each call still sends the nearest level its model accepts. Legacy GenerateContent only; the portable Infer path is unaffected.

func WithEmbeddingModel

func WithEmbeddingModel(embeddingModel string) Option

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 WithHeaders added in v0.19.156

func WithHeaders(headers map[string]string) Option

WithHeaders adds custom headers to each provider request. Authentication and content type remain controlled by the client and cannot be overridden here.

func WithInferenceAPI added in v0.21.160

func WithInferenceAPI(api InferenceAPI) Option

WithInferenceAPI selects the upstream API for the portable Infer path. Legacy GenerateContent is unaffected.

func WithModel

func WithModel(model string) Option

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 WithOrganization

func WithOrganization(organization string) Option

WithOrganization passes the OpenAI organization to the client. If not set, the organization is read from the OPENAI_ORGANIZATION.

func WithProject added in v0.19.153

func WithProject(project string) Option

WithProject passes the OpenAI project to the client. If not set, the project is read from the OPENAI_PROJECT environment variable.

func WithProvider added in v0.14.88

func WithProvider(apiType llms.ProviderType) Option

WithProvider passes the api type to the client. If not set, the default value is ProviderOpenAI.

func WithResponseFormat

func WithResponseFormat(responseFormat *schema.ResponseFormat) Option

WithResponseFormat allows setting a custom response format.

func WithToken

func WithToken(token string) Option

WithToken passes the OpenAI API token to the client. If not set, the token is read from the OPENAI_API_KEY environment variable.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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