Thanks to visit codestin.com
Credit goes to pkg.go.dev

openai

package
v0.23.2 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: Apache-2.0 Imports: 25 Imported by: 12

Documentation

Overview

Package openai provides an implementation of the fantasy AI SDK for OpenAI's language models.

Package openai provides an implementation of the fantasy AI SDK for OpenAI's language models.

Package openai provides an implementation of the fantasy AI SDK for OpenAI's language models.

Index

Constants

View Source
const (
	// Name is the name of the OpenAI provider.
	Name = "openai"
	// DefaultURL is the default URL for the OpenAI API.
	DefaultURL = "https://api.openai.com/v1"
)
View Source
const (
	TypeProviderOptions     = Name + ".options"
	TypeProviderFileOptions = Name + ".file_options"
	TypeProviderMetadata    = Name + ".metadata"
)

Global type identifiers for OpenAI-specific provider data.

View Source
const (
	TypeResponsesProviderMetadata  = Name + ".responses.metadata"
	TypeResponsesProviderOptions   = Name + ".responses.options"
	TypeResponsesReasoningMetadata = Name + ".responses.reasoning_metadata"
	TypeWebSearchCallMetadata      = Name + ".responses.web_search_call_metadata"
)

Global type identifiers for OpenAI Responses API-specific data.

Variables

This section is empty.

Functions

func DefaultMapFinishReasonFunc

func DefaultMapFinishReasonFunc(finishReason string) fantasy.FinishReason

DefaultMapFinishReasonFunc is the default implementation for mapping finish reasons.

func DefaultPrepareCallFunc

func DefaultPrepareCallFunc(model fantasy.LanguageModel, params *openai.ChatCompletionNewParams, call fantasy.Call) ([]fantasy.CallWarning, error)

DefaultPrepareCallFunc is the default implementation for preparing a call to the language model.

func DefaultStreamProviderMetadataFunc

func DefaultStreamProviderMetadataFunc(choice openai.ChatCompletionChoice, metadata fantasy.ProviderMetadata) fantasy.ProviderMetadata

DefaultStreamProviderMetadataFunc is the default implementation for handling stream provider metadata.

func DefaultStreamUsageFunc

func DefaultStreamUsageFunc(chunk openai.ChatCompletionChunk, _ map[string]any, metadata fantasy.ProviderMetadata) (fantasy.Usage, fantasy.ProviderMetadata)

DefaultStreamUsageFunc is the default implementation for calculating stream usage.

func DefaultToPrompt

func DefaultToPrompt(prompt fantasy.Prompt, _, _ string) ([]openai.ChatCompletionMessageParamUnion, []fantasy.CallWarning)

DefaultToPrompt converts a fantasy prompt to OpenAI format with default handling.

func DefaultUsageFunc

func DefaultUsageFunc(response openai.ChatCompletion) (fantasy.Usage, fantasy.ProviderOptionsData)

DefaultUsageFunc is the default implementation for calculating usage.

func IsResponsesModel

func IsResponsesModel(modelID string) bool

IsResponsesModel checks if a model ID is a Responses API model for OpenAI.

func IsResponsesReasoningModel

func IsResponsesReasoningModel(modelID string) bool

IsResponsesReasoningModel checks if a model ID is a Responses API reasoning model for OpenAI.

func New

func New(opts ...Option) (fantasy.Provider, error)

New creates a new OpenAI provider with the given options.

func NewProviderFileOptions

func NewProviderFileOptions(opts *ProviderFileOptions) fantasy.ProviderOptions

NewProviderFileOptions creates new file options for OpenAI.

func NewProviderOptions

func NewProviderOptions(opts *ProviderOptions) fantasy.ProviderOptions

NewProviderOptions creates new provider options for OpenAI.

func NewResponsesProviderOptions

func NewResponsesProviderOptions(opts *ResponsesProviderOptions) fantasy.ProviderOptions

NewResponsesProviderOptions creates new provider options for OpenAI Responses API.

func WebSearchTool added in v0.13.0

WebSearchTool creates a provider-defined web search tool for OpenAI models. Pass nil for default options.

Types

type IncludeType

type IncludeType string

IncludeType represents the type of content to include for OpenAI Responses API.

const (
	// IncludeReasoningEncryptedContent includes encrypted reasoning content.
	IncludeReasoningEncryptedContent IncludeType = "reasoning.encrypted_content"
	// IncludeFileSearchCallResults includes file search call results.
	IncludeFileSearchCallResults IncludeType = "file_search_call.results"
	// IncludeMessageOutputTextLogprobs includes message output text log probabilities.
	IncludeMessageOutputTextLogprobs IncludeType = "message.output_text.logprobs"
)

type LanguageModelExtraContentFunc

type LanguageModelExtraContentFunc = func(choice openai.ChatCompletionChoice) []fantasy.Content

LanguageModelExtraContentFunc is a function that adds extra content for the language model.

type LanguageModelMapFinishReasonFunc

type LanguageModelMapFinishReasonFunc = func(finishReason string) fantasy.FinishReason

LanguageModelMapFinishReasonFunc is a function that maps the finish reason for the language model.

type LanguageModelOption

type LanguageModelOption = func(*languageModel)

LanguageModelOption is a function that configures a languageModel.

func WithLanguageModelExtraContentFunc

func WithLanguageModelExtraContentFunc(fn LanguageModelExtraContentFunc) LanguageModelOption

WithLanguageModelExtraContentFunc sets the extra content function for the language model.

func WithLanguageModelMapFinishReasonFunc

func WithLanguageModelMapFinishReasonFunc(fn LanguageModelMapFinishReasonFunc) LanguageModelOption

WithLanguageModelMapFinishReasonFunc sets the map finish reason function for the language model.

func WithLanguageModelObjectMode added in v0.3.0

func WithLanguageModelObjectMode(om fantasy.ObjectMode) LanguageModelOption

WithLanguageModelObjectMode sets the object generation mode.

func WithLanguageModelPrepareCallFunc

func WithLanguageModelPrepareCallFunc(fn LanguageModelPrepareCallFunc) LanguageModelOption

WithLanguageModelPrepareCallFunc sets the prepare call function for the language model.

func WithLanguageModelStreamExtraFunc

func WithLanguageModelStreamExtraFunc(fn LanguageModelStreamExtraFunc) LanguageModelOption

WithLanguageModelStreamExtraFunc sets the stream extra function for the language model.

func WithLanguageModelStreamUsageFunc

func WithLanguageModelStreamUsageFunc(fn LanguageModelStreamUsageFunc) LanguageModelOption

WithLanguageModelStreamUsageFunc sets the stream usage function for the language model.

func WithLanguageModelToPromptFunc

func WithLanguageModelToPromptFunc(fn LanguageModelToPromptFunc) LanguageModelOption

WithLanguageModelToPromptFunc sets the to prompt function for the language model.

func WithLanguageModelUsageFunc

func WithLanguageModelUsageFunc(fn LanguageModelUsageFunc) LanguageModelOption

WithLanguageModelUsageFunc sets the usage function for the language model.

type LanguageModelPrepareCallFunc

type LanguageModelPrepareCallFunc = func(model fantasy.LanguageModel, params *openai.ChatCompletionNewParams, call fantasy.Call) ([]fantasy.CallWarning, error)

LanguageModelPrepareCallFunc is a function that prepares the call for the language model.

type LanguageModelStreamExtraFunc

type LanguageModelStreamExtraFunc = func(chunk openai.ChatCompletionChunk, yield func(fantasy.StreamPart) bool, ctx map[string]any) (map[string]any, bool)

LanguageModelStreamExtraFunc is a function that handles stream extra functionality for the language model.

type LanguageModelStreamProviderMetadataFunc

type LanguageModelStreamProviderMetadataFunc = func(choice openai.ChatCompletionChoice, metadata fantasy.ProviderMetadata) fantasy.ProviderMetadata

LanguageModelStreamProviderMetadataFunc is a function that handles stream provider metadata for the language model.

type LanguageModelStreamUsageFunc

type LanguageModelStreamUsageFunc = func(chunk openai.ChatCompletionChunk, ctx map[string]any, metadata fantasy.ProviderMetadata) (fantasy.Usage, fantasy.ProviderMetadata)

LanguageModelStreamUsageFunc is a function that calculates stream usage for the language model.

type LanguageModelToPromptFunc

type LanguageModelToPromptFunc = func(prompt fantasy.Prompt, provider, model string) ([]openai.ChatCompletionMessageParamUnion, []fantasy.CallWarning)

LanguageModelToPromptFunc is a function that handles converting fantasy prompts to openai sdk messages.

type LanguageModelUsageFunc

type LanguageModelUsageFunc = func(choice openai.ChatCompletion) (fantasy.Usage, fantasy.ProviderOptionsData)

LanguageModelUsageFunc is a function that calculates usage for the language model.

type Option

type Option = func(*options)

Option defines a function that configures OpenAI provider options.

func WithAPIKey

func WithAPIKey(apiKey string) Option

WithAPIKey sets the API key for the OpenAI provider.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets the base URL for the OpenAI provider.

func WithHTTPClient

func WithHTTPClient(client option.HTTPClient) Option

WithHTTPClient sets the HTTP client for the OpenAI provider.

func WithHeaders

func WithHeaders(headers map[string]string) Option

WithHeaders sets the headers for the OpenAI provider.

func WithLanguageModelOptions

func WithLanguageModelOptions(opts ...LanguageModelOption) Option

WithLanguageModelOptions sets the language model options for the OpenAI provider.

func WithName

func WithName(name string) Option

WithName sets the name for the OpenAI provider.

func WithObjectMode added in v0.3.0

func WithObjectMode(om fantasy.ObjectMode) Option

WithObjectMode sets the object generation mode.

func WithOrganization

func WithOrganization(organization string) Option

WithOrganization sets the organization for the OpenAI provider.

func WithProject

func WithProject(project string) Option

WithProject sets the project for the OpenAI provider.

func WithSDKOptions

func WithSDKOptions(opts ...option.RequestOption) Option

WithSDKOptions sets the SDK options for the OpenAI provider.

func WithUseResponsesAPI

func WithUseResponsesAPI() Option

WithUseResponsesAPI configures the provider to use the responses API for models that support it.

func WithUserAgent added in v0.12.0

func WithUserAgent(ua string) Option

WithUserAgent sets an explicit User-Agent header, overriding the default and any value set via WithHeaders.

type ProviderFileOptions

type ProviderFileOptions struct {
	ImageDetail string `json:"image_detail"`
}

ProviderFileOptions represents file options for OpenAI provider.

func (ProviderFileOptions) MarshalJSON added in v0.3.0

func (o ProviderFileOptions) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling with type info for ProviderFileOptions.

func (*ProviderFileOptions) Options

func (*ProviderFileOptions) Options()

Options implements the ProviderOptions interface.

func (*ProviderFileOptions) UnmarshalJSON added in v0.3.0

func (o *ProviderFileOptions) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling with type info for ProviderFileOptions.

type ProviderMetadata

type ProviderMetadata struct {
	Logprobs                 []openai.ChatCompletionTokenLogprob `json:"logprobs"`
	AcceptedPredictionTokens int64                               `json:"accepted_prediction_tokens"`
	RejectedPredictionTokens int64                               `json:"rejected_prediction_tokens"`
}

ProviderMetadata represents additional metadata from OpenAI provider.

func (ProviderMetadata) MarshalJSON added in v0.3.0

func (m ProviderMetadata) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling with type info for ProviderMetadata.

func (*ProviderMetadata) Options

func (*ProviderMetadata) Options()

Options implements the ProviderOptions interface.

func (*ProviderMetadata) UnmarshalJSON added in v0.3.0

func (m *ProviderMetadata) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling with type info for ProviderMetadata.

type ProviderOptions

type ProviderOptions struct {
	LogitBias           map[string]int64 `json:"logit_bias"`
	LogProbs            *bool            `json:"log_probs"`
	TopLogProbs         *int64           `json:"top_log_probs"`
	ParallelToolCalls   *bool            `json:"parallel_tool_calls"`
	User                *string          `json:"user"`
	ReasoningEffort     *ReasoningEffort `json:"reasoning_effort"`
	MaxCompletionTokens *int64           `json:"max_completion_tokens"`
	TextVerbosity       *string          `json:"text_verbosity"`
	Prediction          map[string]any   `json:"prediction"`
	Store               *bool            `json:"store"`
	Metadata            map[string]any   `json:"metadata"`
	PromptCacheKey      *string          `json:"prompt_cache_key"`
	SafetyIdentifier    *string          `json:"safety_identifier"`
	ServiceTier         *string          `json:"service_tier"`
	StructuredOutputs   *bool            `json:"structured_outputs"`
}

ProviderOptions represents additional options for OpenAI provider.

func ParseOptions

func ParseOptions(data map[string]any) (*ProviderOptions, error)

ParseOptions parses provider options from a map.

func (ProviderOptions) MarshalJSON added in v0.3.0

func (o ProviderOptions) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling with type info for ProviderOptions.

func (*ProviderOptions) Options

func (*ProviderOptions) Options()

Options implements the ProviderOptions interface.

func (*ProviderOptions) UnmarshalJSON added in v0.3.0

func (o *ProviderOptions) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling with type info for ProviderOptions.

type ReasoningEffort

type ReasoningEffort string

ReasoningEffort represents the reasoning effort level for OpenAI models.

const (
	// ReasoningEffortNone represents ReasoningEffortNone reasoning effort.
	ReasoningEffortNone ReasoningEffort = "none"
	// ReasoningEffortMinimal represents minimal reasoning effort.
	ReasoningEffortMinimal ReasoningEffort = "minimal"
	// ReasoningEffortLow represents low reasoning effort.
	ReasoningEffortLow ReasoningEffort = "low"
	// ReasoningEffortMedium represents medium reasoning effort.
	ReasoningEffortMedium ReasoningEffort = "medium"
	// ReasoningEffortHigh represents high reasoning effort.
	ReasoningEffortHigh ReasoningEffort = "high"
	// ReasoningEffortXHigh represents extra-high reasoning effort.
	ReasoningEffortXHigh ReasoningEffort = "xhigh"
)

func ReasoningEffortOption

func ReasoningEffortOption(e ReasoningEffort) *ReasoningEffort

ReasoningEffortOption creates a pointer to a ReasoningEffort value.

type ResponsesProviderMetadata added in v0.14.0

type ResponsesProviderMetadata struct {
	ResponseID string `json:"response_id"`
}

ResponsesProviderMetadata contains response-level metadata from the OpenAI Responses API. The ResponseID can be used as PreviousResponseID in follow-up requests to chain responses.

func (ResponsesProviderMetadata) MarshalJSON added in v0.14.0

func (m ResponsesProviderMetadata) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling with type info for ResponsesProviderMetadata.

func (*ResponsesProviderMetadata) Options added in v0.14.0

func (*ResponsesProviderMetadata) Options()

Options implements the ProviderOptions interface.

func (*ResponsesProviderMetadata) UnmarshalJSON added in v0.14.0

func (m *ResponsesProviderMetadata) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling with type info for ResponsesProviderMetadata.

type ResponsesProviderOptions

type ResponsesProviderOptions struct {
	Include           []IncludeType  `json:"include"`
	Instructions      *string        `json:"instructions"`
	Logprobs          any            `json:"logprobs"`
	MaxToolCalls      *int64         `json:"max_tool_calls"`
	Metadata          map[string]any `json:"metadata"`
	ParallelToolCalls *bool          `json:"parallel_tool_calls"`
	// PreviousResponseID chains this request to a prior stored response, enabling
	// server-side conversation state. When set, the prompt should contain only the
	// new incremental turn—not replayed assistant history.
	PreviousResponseID *string          `json:"previous_response_id"`
	PromptCacheKey     *string          `json:"prompt_cache_key"`
	ReasoningEffort    *ReasoningEffort `json:"reasoning_effort"`
	ReasoningSummary   *string          `json:"reasoning_summary"`
	SafetyIdentifier   *string          `json:"safety_identifier"`
	ServiceTier        *ServiceTier     `json:"service_tier"`
	// Store indicates whether OpenAI should persist this response for future
	// retrieval and chaining via PreviousResponseID. Defaults to false to prevent
	// unintended storage of potentially sensitive conversations.
	Store            *bool          `json:"store"`
	StrictJSONSchema *bool          `json:"strict_json_schema"`
	TextVerbosity    *TextVerbosity `json:"text_verbosity"`
	User             *string        `json:"user"`
}

ResponsesProviderOptions represents additional options for OpenAI Responses API.

func ParseResponsesOptions

func ParseResponsesOptions(data map[string]any) (*ResponsesProviderOptions, error)

ParseResponsesOptions parses provider options from a map for OpenAI Responses API.

func (ResponsesProviderOptions) MarshalJSON added in v0.3.0

func (o ResponsesProviderOptions) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling with type info for ResponsesProviderOptions.

func (*ResponsesProviderOptions) Options

func (*ResponsesProviderOptions) Options()

Options implements the ProviderOptions interface.

func (*ResponsesProviderOptions) UnmarshalJSON added in v0.3.0

func (o *ResponsesProviderOptions) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling with type info for ResponsesProviderOptions.

type ResponsesReasoningMetadata

type ResponsesReasoningMetadata struct {
	ItemID           string   `json:"item_id"`
	EncryptedContent *string  `json:"encrypted_content"`
	Summary          []string `json:"summary"`
}

ResponsesReasoningMetadata represents reasoning metadata for OpenAI Responses API.

func GetReasoningMetadata

func GetReasoningMetadata(providerOptions fantasy.ProviderOptions) *ResponsesReasoningMetadata

GetReasoningMetadata extracts reasoning metadata from provider options for responses models.

func (ResponsesReasoningMetadata) MarshalJSON added in v0.3.0

func (m ResponsesReasoningMetadata) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling with type info for ResponsesReasoningMetadata.

func (*ResponsesReasoningMetadata) Options

func (*ResponsesReasoningMetadata) Options()

Options implements the ProviderOptions interface.

func (*ResponsesReasoningMetadata) UnmarshalJSON added in v0.3.0

func (m *ResponsesReasoningMetadata) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling with type info for ResponsesReasoningMetadata.

type SearchContextSize added in v0.13.0

type SearchContextSize string

SearchContextSize controls how much context window space the web search tool uses. Maps to the OpenAI API's search_context_size parameter.

const (
	// SearchContextSizeLow uses minimal context for search results.
	SearchContextSizeLow SearchContextSize = "low"
	// SearchContextSizeMedium is the default context size.
	SearchContextSizeMedium SearchContextSize = "medium"
	// SearchContextSizeHigh uses maximal context for search results.
	SearchContextSizeHigh SearchContextSize = "high"
)

type ServiceTier

type ServiceTier string

ServiceTier represents the service tier for OpenAI Responses API.

const (
	// ServiceTierAuto represents the auto service tier.
	ServiceTierAuto ServiceTier = "auto"
	// ServiceTierFlex represents the flex service tier.
	ServiceTierFlex ServiceTier = "flex"
	// ServiceTierPriority represents the priority service tier.
	ServiceTierPriority ServiceTier = "priority"
)

type TextVerbosity

type TextVerbosity string

TextVerbosity represents the text verbosity level for OpenAI Responses API.

const (
	// TextVerbosityLow represents low text verbosity.
	TextVerbosityLow TextVerbosity = "low"
	// TextVerbosityMedium represents medium text verbosity.
	TextVerbosityMedium TextVerbosity = "medium"
	// TextVerbosityHigh represents high text verbosity.
	TextVerbosityHigh TextVerbosity = "high"
)

type WebSearchAction added in v0.13.0

type WebSearchAction struct {
	// Type is the kind of action: "search", "open_page", or "find".
	Type string `json:"type"`
	// Query is the search query (present when Type is "search").
	Query string `json:"query,omitempty"`
	// Sources are the results returned by the search.
	Sources []WebSearchSource `json:"sources,omitempty"`
}

WebSearchAction represents the action taken during a web search call.

type WebSearchCallMetadata added in v0.13.0

type WebSearchCallMetadata struct {
	// ItemID is the server-side ID of the web_search_call output item.
	ItemID string `json:"item_id"`
	// Action contains the structured action data from the search.
	Action *WebSearchAction `json:"action,omitempty"`
}

WebSearchCallMetadata stores structured data from a web_search_call output item for round-tripping through multi-turn conversations. The ItemID is used with item_reference for efficient round-tripping when response storage is enabled.

func (WebSearchCallMetadata) MarshalJSON added in v0.13.0

func (m WebSearchCallMetadata) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling with type info.

func (*WebSearchCallMetadata) Options added in v0.13.0

func (*WebSearchCallMetadata) Options()

Options implements the ProviderOptionsData interface.

func (*WebSearchCallMetadata) UnmarshalJSON added in v0.13.0

func (m *WebSearchCallMetadata) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling with type info.

type WebSearchSource added in v0.13.0

type WebSearchSource struct {
	Type string `json:"type"`
	URL  string `json:"url"`
}

WebSearchSource represents a single source from a web search action.

type WebSearchToolOptions added in v0.13.0

type WebSearchToolOptions struct {
	// SearchContextSize controls the amount of context window
	// space used for search results. Defaults to medium.
	SearchContextSize SearchContextSize
	// AllowedDomains restricts search results to these domains.
	// Subdomains are included automatically.
	AllowedDomains []string
	// UserLocation provides geographic context for more
	// relevant search results.
	UserLocation *WebSearchUserLocation
}

WebSearchToolOptions configures the OpenAI web search tool.

type WebSearchUserLocation added in v0.13.0

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

WebSearchUserLocation provides geographic context for more relevant web search results.

Jump to

Keyboard shortcuts

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