openai

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: May 6, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Package openai provides an OpenAI provider implementation.

This package follows the same pattern as @ai-sdk/openai, providing both:

  • Chat Completions API via Chat() method
  • Responses API via Responses() method

The default Model() method returns a Responses API model, matching @ai-sdk behavior.

Index

Constants

View Source
const (
	ToolIDWebSearch  = "openai.web_search"
	ToolIDCustom     = "openai.custom"
	ToolIDToolSearch = "openai.tool_search"
)

Provider-defined tool IDs for OpenAI hosted tools. Mirror ai-sdk's factory IDs at packages/openai/src/tool/*.ts.

Variables

View Source
var OpenAIFailedResponseHandler = response.CreateJSONErrorResponseHandler(response.JSONErrorConfig[OpenAIErrorData]{
	ErrorSchema:    parseOpenAIErrorForHandler,
	ErrorToMessage: func(data OpenAIErrorData) string { return data.GetMessage() },
	IsRetryable: func(resp *http.Response, _ *OpenAIErrorData) bool {
		return resp.StatusCode == 429 || resp.StatusCode >= 500
	},
})

OpenAIFailedResponseHandler is the error response handler for OpenAI API errors. It parses the JSON error response and extracts the error message. This matches ai-sdk's openaiFailedResponseHandler.

Source: ai-sdk/packages/openai/src/openai-error.ts

Functions

func Custom

func Custom(opts CustomOptions) tool.Tool

Custom returns a provider-defined OpenAI custom tool. The surface Name used by goai may differ from opts.Name (the wire-format name OpenAI knows) to support alias mapping.

func HandleErrorResponse

func HandleErrorResponse(resp *http.Response, url string, requestBodyValues any) *errors.APICallError

HandleErrorResponse processes an error response using the OpenAI error handler. Returns an APICallError with parsed error data.

func ToolSearch

func ToolSearch(opts ToolSearchOptions) tool.Tool

ToolSearch returns a provider-defined OpenAI tool_search tool.

func WebSearch

func WebSearch() tool.Tool

WebSearch returns a provider-defined OpenAI web_search tool. Use WebSearchWith for options.

func WebSearchWith

func WebSearchWith(opts WebSearchOptions) tool.Tool

Types

type ChatModel

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

ChatModel represents an OpenAI model using the Chat Completions API.

func (*ChatModel) ID

func (m *ChatModel) ID() string

ID returns the model ID.

func (*ChatModel) Provider

func (m *ChatModel) Provider() string

Provider returns "openai.chat".

func (*ChatModel) Stream

func (m *ChatModel) Stream(ctx context.Context, options *stream.CallOptions) (<-chan stream.Event, error)

Stream sends a streaming request to OpenAI using the Chat Completions API.

type ChatOptions

type ChatOptions struct {
	// Logprobs returns the log probabilities of the tokens.
	// Can be true (return logprobs) or a number 1-20 (return top N logprobs).
	Logprobs any `json:"logprobs,omitempty"`

	// LogitBias modifies the likelihood of specified tokens appearing in the completion.
	// Maps token IDs to bias values from -100 to 100.
	LogitBias map[string]int `json:"logitBias,omitempty"`

	// ParallelToolCalls controls whether to use parallel tool calls.
	// Defaults to true.
	ParallelToolCalls *bool `json:"parallelToolCalls,omitempty"`

	// PresencePenalty penalizes new tokens based on whether they appear in the text so far.
	// Range: -2.0 to 2.0. Positive values increase likelihood to talk about new topics.
	PresencePenalty *float64 `json:"presencePenalty,omitempty"`

	// FrequencyPenalty penalizes new tokens based on their frequency in the text so far.
	// Range: -2.0 to 2.0. Positive values decrease likelihood to repeat the same line.
	FrequencyPenalty *float64 `json:"frequencyPenalty,omitempty"`

	// ReasoningEffort controls reasoning effort for reasoning models.
	// Values: "low", "medium", "high"
	ReasoningEffort string `json:"reasoningEffort,omitempty"`

	// Store controls whether to store the generation.
	Store *bool `json:"store,omitempty"`

	// StrictJsonSchema controls whether to use strict JSON schema validation.
	StrictJsonSchema *bool `json:"strictJsonSchema,omitempty"`

	// StructuredOutputs controls whether to use structured outputs.
	StructuredOutputs *bool `json:"structuredOutputs,omitempty"`

	// User is a unique identifier representing your end-user for abuse monitoring.
	User string `json:"user,omitempty"`
}

ChatOptions contains provider-specific options for the OpenAI Chat Completions API. These options match ai-sdk's OpenAIChatProviderOptions schema. See: ai-sdk/packages/openai/src/chat/openai-chat-options.ts

type ConversionResult

type ConversionResult struct {
	Input    []responsesInputItem
	Warnings []ConversionWarning
}

ConversionResult contains the converted input and any warnings.

type ConversionWarning

type ConversionWarning struct {
	Type    string `json:"type"`    // "other"
	Message string `json:"message"` // Warning message
}

ConversionWarning represents a warning generated during message conversion. Matches ai-sdk's SharedV3Warning type.

type CustomFormat

type CustomFormat struct {
	Type       string `json:"type"`
	Syntax     string `json:"syntax,omitempty"`
	Definition string `json:"definition,omitempty"`
}

CustomFormat specifies the output format for a custom tool. Either a grammar format (regex/lark) or a plain text format.

type CustomOptions

type CustomOptions struct {
	Name        string        `json:"name"`
	Description string        `json:"description,omitempty"`
	Format      *CustomFormat `json:"format,omitempty"`
}

CustomOptions configures the openai.custom hosted tool. Mirrors the ai-sdk argsSchema at packages/openai/src/tool/custom.ts.

type LanguageModelCapabilities

type LanguageModelCapabilities struct {
	// IsReasoningModel indicates if the model is a reasoning model (o1, o3, o4-mini, gpt-5, etc.)
	IsReasoningModel bool

	// SystemMessageMode determines how system messages should be handled.
	// "system" - use standard system role
	// "developer" - convert to developer role (for reasoning models)
	// "remove" - remove system messages entirely
	SystemMessageMode string

	// SupportsFlexProcessing indicates if the model supports flex processing tier.
	SupportsFlexProcessing bool

	// SupportsPriorityProcessing indicates if the model supports priority processing tier.
	SupportsPriorityProcessing bool

	// SupportsNonReasoningParameters indicates if the model allows temperature, topP, logProbs
	// when reasoningEffort is none. Only true for gpt-5.1+ models.
	SupportsNonReasoningParameters bool
}

LanguageModelCapabilities describes the capabilities of an OpenAI language model. Source: ai-sdk/packages/openai/src/openai-language-model-capabilities.ts

func GetLanguageModelCapabilities

func GetLanguageModelCapabilities(modelID string) LanguageModelCapabilities

GetLanguageModelCapabilities returns the capabilities for a given OpenAI model ID.

type OpenAIEmbeddingModel

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

OpenAIEmbeddingModel implements the EmbeddingModel interface for OpenAI.

func (*OpenAIEmbeddingModel) Dimensions

func (m *OpenAIEmbeddingModel) Dimensions() int

Dimensions returns the default embedding dimensions (0 means variable).

func (*OpenAIEmbeddingModel) Embed

Embed generates embeddings for the provided texts.

func (*OpenAIEmbeddingModel) ID

func (m *OpenAIEmbeddingModel) ID() string

ID returns the model identifier.

func (*OpenAIEmbeddingModel) MaxEmbeddingsPerCall

func (m *OpenAIEmbeddingModel) MaxEmbeddingsPerCall() int

MaxEmbeddingsPerCall returns the maximum number of texts that can be embedded in a single call.

func (*OpenAIEmbeddingModel) Provider

func (m *OpenAIEmbeddingModel) Provider() string

Provider returns "openai".

type OpenAIErrorData

type OpenAIErrorData struct {
	Error OpenAIErrorInfo `json:"error"`
}

OpenAIErrorData represents the structure of an OpenAI API error response. This schema is designed to handle both standard OpenAI errors and wrapped errors from OpenAI-compatible providers (e.g., OpenRouter).

Source: ai-sdk/packages/openai/src/openai-error.ts

func ParseOpenAIError

func ParseOpenAIError(body []byte) (*OpenAIErrorData, error)

ParseOpenAIError parses an OpenAI API error response. Returns the parsed error data or an error if parsing fails.

func (*OpenAIErrorData) GetCodeNumber

func (e *OpenAIErrorData) GetCodeNumber() int

GetCodeNumber returns the error code as a number. If the code is not numeric, it returns 0.

func (*OpenAIErrorData) GetCodeString

func (e *OpenAIErrorData) GetCodeString() string

GetCodeString returns the error code as a string. If the code is numeric, it returns an empty string.

func (*OpenAIErrorData) GetMessage

func (e *OpenAIErrorData) GetMessage() string

GetMessage returns the error message.

func (*OpenAIErrorData) GetType

func (e *OpenAIErrorData) GetType() string

GetType returns the error type, or empty string if not set.

type OpenAIErrorInfo

type OpenAIErrorInfo struct {
	// Message is the error message. For nested errors from providers like
	// OpenRouter, this may contain JSON-encoded error details.
	Message string `json:"message"`

	// Type is the error type (e.g., "invalid_request_error").
	// Optional - may be nil for some providers.
	Type *string `json:"type,omitempty"`

	// Param is the parameter that caused the error.
	// Optional - type is any to handle different provider formats.
	Param any `json:"param,omitempty"`

	// Code is the error code. Can be either a string or number depending
	// on the provider. For example, OpenAI uses strings like "invalid_api_key",
	// while OpenRouter may use numeric codes like 429.
	Code any `json:"code,omitempty"`
}

OpenAIErrorInfo contains the details of an OpenAI error.

type OpenAIImageModel

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

OpenAIImageModel implements the ImageModel interface for OpenAI.

func (*OpenAIImageModel) Generate

Generate generates images based on the provided options.

func (*OpenAIImageModel) ID

func (m *OpenAIImageModel) ID() string

ID returns the model identifier.

func (*OpenAIImageModel) MaxImagesPerCall

func (m *OpenAIImageModel) MaxImagesPerCall() int

MaxImagesPerCall returns the maximum number of images that can be generated in a single call.

func (*OpenAIImageModel) Provider

func (m *OpenAIImageModel) Provider() string

Provider returns "openai".

type OpenAISpeechModel

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

OpenAISpeechModel implements the SpeechModel interface for OpenAI.

func (*OpenAISpeechModel) Generate

Generate generates speech from text.

func (*OpenAISpeechModel) ID

func (m *OpenAISpeechModel) ID() string

ID returns the model identifier.

func (*OpenAISpeechModel) Provider

func (m *OpenAISpeechModel) Provider() string

Provider returns "openai".

type OpenAITranscriptionModel

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

OpenAITranscriptionModel implements the TranscriptionModel interface for OpenAI.

func (*OpenAITranscriptionModel) ID

ID returns the model identifier.

func (*OpenAITranscriptionModel) Provider

func (m *OpenAITranscriptionModel) Provider() string

Provider returns "openai".

func (*OpenAITranscriptionModel) Transcribe

Transcribe transcribes audio to text.

type Provider

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

Provider implements the OpenAI provider.

func New

func New(opts provider.Options) *Provider

New creates a new OpenAI provider.

func (*Provider) Chat

func (p *Provider) Chat(modelID string) stream.Model

Chat returns a model instance using the Chat Completions API (/chat/completions).

func (*Provider) EmbeddingModel

func (p *Provider) EmbeddingModel(modelID string) model.EmbeddingModel

EmbeddingModel returns an embedding model instance.

func (*Provider) EmbeddingModels

func (p *Provider) EmbeddingModels() []string

EmbeddingModels returns available embedding model IDs.

func (*Provider) ID

func (p *Provider) ID() string

ID returns "openai".

func (*Provider) ImageModel

func (p *Provider) ImageModel(modelID string) model.ImageModel

ImageModel returns an image generation model instance.

func (*Provider) ImageModels

func (p *Provider) ImageModels() []string

ImageModels returns available image model IDs.

func (*Provider) LanguageModel

func (p *Provider) LanguageModel(modelID string) model.LanguageModel

LanguageModel returns a language model instance.

func (*Provider) Model

func (p *Provider) Model(modelID string) stream.Model

Model returns a model instance using the Responses API (default). This matches @ai-sdk/openai behavior where the default is the Responses API.

func (*Provider) Models

func (p *Provider) Models() []string

Models returns available model IDs. Mirrors ai-sdk's OpenAIChatModelId union in packages/openai/src/chat/openai-chat-options.ts.

func (*Provider) RerankingModel

func (p *Provider) RerankingModel(modelID string) model.RerankingModel

RerankingModel returns nil as OpenAI doesn't support reranking.

func (*Provider) Responses

func (p *Provider) Responses(modelID string) stream.Model

Responses returns a model instance using the Responses API (/responses).

func (*Provider) SpeechModel

func (p *Provider) SpeechModel(modelID string) model.SpeechModel

SpeechModel returns a text-to-speech model instance.

func (*Provider) SpeechModels

func (p *Provider) SpeechModels() []string

SpeechModels returns available speech model IDs.

func (*Provider) TranscriptionModel

func (p *Provider) TranscriptionModel(modelID string) model.TranscriptionModel

TranscriptionModel returns a speech-to-text model instance.

func (*Provider) TranscriptionModels

func (p *Provider) TranscriptionModels() []string

TranscriptionModels returns available transcription model IDs.

type ResponsesModel

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

ResponsesModel represents an OpenAI model using the Responses API. This is the newer API that supports features like reasoning, web search, and code interpreter natively.

Note: goai defaults to the Responses API. The standard @ai-sdk/openai uses Chat Completions by default See provider.go for the default behavior.

func (*ResponsesModel) ID

func (m *ResponsesModel) ID() string

ID returns the model ID.

func (*ResponsesModel) Provider

func (m *ResponsesModel) Provider() string

Provider returns "openai.responses".

func (*ResponsesModel) Stream

func (m *ResponsesModel) Stream(ctx context.Context, options *stream.CallOptions) (<-chan stream.Event, error)

Stream sends a streaming request to OpenAI using the Responses API.

type ResponsesOptions

type ResponsesOptions struct {
	// Conversation is the ID of the OpenAI Conversation to continue.
	// You must create a conversation first via the OpenAI API.
	// Cannot be used in conjunction with PreviousResponseID.
	Conversation string `json:"conversation,omitempty"`

	// Include specifies extra fields to include in the response.
	// Example values: "reasoning.encrypted_content", "file_search_call.results", "message.output_text.logprobs"
	Include []string `json:"include,omitempty"`

	// Instructions for the model.
	// They can be used to change the system or developer message when continuing
	// a conversation using the PreviousResponseID option.
	Instructions string `json:"instructions,omitempty"`

	// Logprobs returns the log probabilities of the tokens.
	// Can be true (return logprobs) or a number 1-20 (return top N logprobs).
	// Including logprobs increases response size and can slow down response times.
	Logprobs any `json:"logprobs,omitempty"`

	// MaxToolCalls is the maximum number of total calls to built-in tools
	// that can be processed in a response. This applies across all built-in
	// tool calls, not per individual tool.
	MaxToolCalls *int `json:"maxToolCalls,omitempty"`

	// Metadata is additional metadata to store with the generation.
	Metadata any `json:"metadata,omitempty"`

	// ParallelToolCalls controls whether to use parallel tool calls.
	// Defaults to true.
	ParallelToolCalls *bool `json:"parallelToolCalls,omitempty"`

	// PreviousResponseID is the ID of the previous response for conversation continuation.
	PreviousResponseID string `json:"previousResponseId,omitempty"`

	// PromptCacheKey sets a cache key to tie this prompt to cached prefixes
	// for better caching performance.
	PromptCacheKey string `json:"promptCacheKey,omitempty"`

	// PromptCacheRetention is the retention policy for the prompt cache.
	// Values: "in_memory" (default), "24h" (extended, only for 5.1 series models)
	PromptCacheRetention string `json:"promptCacheRetention,omitempty"`

	// ReasoningEffort controls reasoning effort for reasoning models.
	// Values: "none", "minimal", "low", "medium", "high", "xhigh"
	// Note: "none" is only for GPT-5.1 models, "xhigh" only for GPT-5.1-Codex-Max.
	ReasoningEffort string `json:"reasoningEffort,omitempty"`

	// ReasoningSummary controls reasoning summary output from the model.
	// Values: "auto" (automatically receive richest level), "detailed" (comprehensive summaries)
	ReasoningSummary string `json:"reasoningSummary,omitempty"`

	// SafetyIdentifier is the identifier for safety monitoring and tracking.
	SafetyIdentifier string `json:"safetyIdentifier,omitempty"`

	// ServiceTier is the service tier for the request.
	// Values: "auto" (default), "flex" (50% cheaper, higher latency), "priority" (faster, Enterprise), "default"
	ServiceTier string `json:"serviceTier,omitempty"`

	// Store controls whether to store the generation. Defaults to true.
	Store *bool `json:"store,omitempty"`

	// StrictJsonSchema controls whether to use strict JSON schema validation.
	// Defaults to true.
	StrictJsonSchema *bool `json:"strictJsonSchema,omitempty"`

	// TextVerbosity controls the verbosity of the model's responses.
	// Values: "low" (concise), "medium", "high" (verbose)
	TextVerbosity string `json:"textVerbosity,omitempty"`

	// Truncation controls output truncation.
	// Values: "auto" (default, truncates automatically), "disabled" (no truncation)
	Truncation string `json:"truncation,omitempty"`

	// User is a unique identifier representing your end-user for abuse monitoring.
	User string `json:"user,omitempty"`

	// SystemMessageMode overrides how system messages are handled.
	// Values: "system" (default for most models), "developer" (for reasoning models), "remove"
	SystemMessageMode string `json:"systemMessageMode,omitempty"`

	// ForceReasoning forces treating this model as a reasoning model.
	// Useful for "stealth" reasoning models via custom baseURL where the model ID
	// is not recognized by the SDK's allowlist.
	ForceReasoning bool `json:"forceReasoning,omitempty"`
}

ResponsesOptions contains provider-specific options for the OpenAI Responses API. These options match ai-sdk's OpenAIResponsesProviderOptions schema. See: ai-sdk/packages/openai/src/responses/openai-responses-options.ts

type SystemMessageMode

type SystemMessageMode string

SystemMessageMode controls how system messages are mapped in the Responses API. Options: "system", "developer", "remove" - "system": Use the 'system' role (default for most models) - "developer": Use the 'developer' role (used by reasoning models like o1, o3) - "remove": Remove system messages (for models that don't support them)

const (
	SystemMessageModeSystem    SystemMessageMode = "system"
	SystemMessageModeDeveloper SystemMessageMode = "developer"
	SystemMessageModeRemove    SystemMessageMode = "remove"
)

type ToolSearchOptions

type ToolSearchOptions struct {
	Execution   string         `json:"execution,omitempty"`
	Description string         `json:"description,omitempty"`
	Parameters  map[string]any `json:"parameters,omitempty"`
}

ToolSearchOptions configures the openai.tool_search hosted tool. Mirrors the ai-sdk argsSchema at packages/openai/src/tool/tool-search.ts.

type WebSearchFilters

type WebSearchFilters struct {
	AllowedDomains []string `json:"allowedDomains,omitempty"`
}

WebSearchFilters narrows search results to specific domains.

type WebSearchOptions

type WebSearchOptions struct {
	ExternalWebAccess *bool                  `json:"externalWebAccess,omitempty"`
	Filters           *WebSearchFilters      `json:"filters,omitempty"`
	SearchContextSize string                 `json:"searchContextSize,omitempty"`
	UserLocation      *WebSearchUserLocation `json:"userLocation,omitempty"`
}

WebSearchOptions configures the openai.web_search hosted tool. Mirrors the ai-sdk argsSchema at packages/openai/src/tool/web-search.ts.

type WebSearchUserLocation

type WebSearchUserLocation struct {
	Type     string `json:"type"`
	Country  string `json:"country,omitempty"`
	City     string `json:"city,omitempty"`
	Region   string `json:"region,omitempty"`
	Timezone string `json:"timezone,omitempty"`
}

WebSearchUserLocation provides geographically relevant search results. Type is always "approximate".

Jump to

Keyboard shortcuts

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