openai

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Overview

Package openai adapts OpenAI-compatible APIs to sigma.

It includes providers for Chat Completions-compatible endpoints, OpenAI Responses, Azure OpenAI Responses, OpenAI Codex Responses, OpenAI Images, and OpenAI Embeddings. Chat Completions-compatible registration is also the path for local endpoints and routers described with sigma.OpenAICompatibleModel.

Providers resolve credentials through sigma.Options.AuthResolver or explicit token-provider options instead of reading environment variables directly.

Index

Constants

View Source
const (

	// AzureCredentialSourceAPIKey documents API-key authentication.
	AzureCredentialSourceAPIKey = "api-key"
	// AzureCredentialSourceToken documents Microsoft Entra token authentication.
	AzureCredentialSourceToken = "token"
)
View Source
const DefaultBaseURL = "https://api.openai.com/v1"

Variables

View Source
var Tools = struct {
	WebSearch       func(opts ...WebSearchOption) sigma.Tool
	CodeInterpreter func(opts ...CodeInterpreterOption) sigma.Tool
	FileSearch      func(opts ...FileSearchOption) sigma.Tool
	ImageGeneration func(opts ...ImageGenerationOption) sigma.Tool
}{
	WebSearch:       webSearchTool,
	CodeInterpreter: codeInterpreterTool,
	FileSearch:      fileSearchTool,
	ImageGeneration: imageGenerationTool,
}

Tools provides factories for OpenAI Responses provider-defined tools.

Functions

func CloseCodexResponsesWebSocketSession added in v0.3.0

func CloseCodexResponsesWebSocketSession(sessionID string)

CloseCodexResponsesWebSocketSession closes and forgets a cached Codex WebSocket session and clears its SSE fallback marker.

func CloseCodexResponsesWebSocketSessions added in v0.3.0

func CloseCodexResponsesWebSocketSessions()

CloseCodexResponsesWebSocketSessions closes all cached Codex WebSocket sessions and clears SSE fallback markers.

func NewCodexOAuthTokenProvider added in v0.3.0

func NewCodexOAuthTokenProvider(credentials CodexOAuthCredentials, opts CodexOAuthTokenProviderOptions) sigma.OAuthTokenProvider

NewCodexOAuthTokenProvider adapts caller-managed OpenAI Codex OAuth credentials to Sigma's OAuthTokenProvider interface. Refreshed credentials are kept in memory and passed to OnRefresh for caller persistence.

func Register

func Register(registry *sigma.Registry, providerID sigma.ProviderID, opts ...ProviderOption) error

Register adds a Chat Completions-compatible text provider to registry.

func RegisterAzureResponses

func RegisterAzureResponses(registry *sigma.Registry, providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterAzureResponses adds an Azure OpenAI Responses text provider to registry.

func RegisterAzureResponsesDefault

func RegisterAzureResponsesDefault(providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterAzureResponsesDefault adds an Azure OpenAI Responses text provider to sigma's default registry.

func RegisterCodexResponses

func RegisterCodexResponses(registry *sigma.Registry, providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterCodexResponses adds an OpenAI Codex Responses text provider to registry.

func RegisterCodexResponsesDefault

func RegisterCodexResponsesDefault(providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterCodexResponsesDefault adds an OpenAI Codex Responses text provider to sigma's default registry.

func RegisterDefault

func RegisterDefault(providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterDefault adds a Chat Completions-compatible text provider to sigma's default registry.

func RegisterEmbeddings added in v0.3.0

func RegisterEmbeddings(registry *sigma.Registry, providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterEmbeddings adds an OpenAI Embeddings API provider to registry.

func RegisterEmbeddingsDefault added in v0.3.0

func RegisterEmbeddingsDefault(providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterEmbeddingsDefault adds an OpenAI Embeddings API provider to sigma's default registry.

func RegisterImages added in v0.2.0

func RegisterImages(registry *sigma.Registry, providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterImages adds an OpenAI Images API provider to registry.

func RegisterImagesDefault added in v0.2.0

func RegisterImagesDefault(providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterImagesDefault adds an OpenAI Images API provider to sigma's default registry.

func RegisterLocalEmbeddings added in v0.3.0

func RegisterLocalEmbeddings(registry *sigma.Registry, config LocalEmbeddingConfig) (sigma.EmbeddingModel, error)

RegisterLocalEmbeddings registers an OpenAI-compatible embeddings provider and model for local or private /v1/embeddings endpoints.

func RegisterResponses

func RegisterResponses(registry *sigma.Registry, providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterResponses adds an OpenAI Responses API text provider to registry.

func RegisterResponsesDefault

func RegisterResponsesDefault(providerID sigma.ProviderID, opts ...ProviderOption) error

RegisterResponsesDefault adds an OpenAI Responses API text provider to sigma's default registry.

func RegisterVertex added in v0.4.0

func RegisterVertex(registry *sigma.Registry, providerID sigma.ProviderID, opts ...VertexProviderOption) error

RegisterVertex adds a Vertex OpenAI-compatible text provider to registry.

func RegisterVertexDefault added in v0.4.0

func RegisterVertexDefault(providerID sigma.ProviderID, opts ...VertexProviderOption) error

RegisterVertexDefault adds a Vertex OpenAI-compatible text provider to sigma's default registry.

func WithAzureResponsesAPIVersion

func WithAzureResponsesAPIVersion(provider sigma.ProviderID, apiVersion string) sigma.Option

WithAzureResponsesAPIVersion overrides the api-version query parameter for a request. Azure currently documents v1 as the default, but sigma requires an explicit value so configuration drift is visible in tests and diagnostics.

func WithAzureResponsesCredentialSource

func WithAzureResponsesCredentialSource(provider sigma.ProviderID, source string) sigma.Option

WithAzureResponsesCredentialSource documents the expected auth path for a request. Supported values are AzureCredentialSourceAPIKey and AzureCredentialSourceToken.

func WithAzureResponsesDeployment

func WithAzureResponsesDeployment(provider sigma.ProviderID, deployment string) sigma.Option

WithAzureResponsesDeployment overrides the Azure OpenAI deployment name sent as the Responses model for a request.

func WithAzureResponsesEndpoint

func WithAzureResponsesEndpoint(provider sigma.ProviderID, endpoint string) sigma.Option

WithAzureResponsesEndpoint overrides the Azure OpenAI resource endpoint for a request. The provider appends /openai/v1/responses and api-version.

func WithAzureResponsesTokenCredential

func WithAzureResponsesTokenCredential(provider sigma.ProviderID, credential AzureTokenCredential) sigma.Option

WithAzureResponsesTokenCredential supplies a request-scoped Microsoft Entra token source. API-key auth can use sigma.WithAPIKey, AZURE_OPENAI_API_KEY, or a normal sigma.AuthResolver.

func WithCodexResponsesOAuthTokenProvider

func WithCodexResponsesOAuthTokenProvider(provider sigma.ProviderID, tokenProvider sigma.OAuthTokenProvider) sigma.Option

WithCodexResponsesOAuthTokenProvider supplies the OAuth bearer-token source used by the Codex Responses provider. Use NewCodexOAuthTokenProvider with LoginOpenAICodexDeviceCode when callers want Sigma-managed refresh without Sigma-managed token persistence.

Types

type AzureAccessToken

type AzureAccessToken struct {
	Token     string
	ExpiresOn time.Time
}

AzureAccessToken is the minimal token shape needed by Azure Responses auth.

type AzureResponsesProvider

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

AzureResponsesProvider adapts Azure OpenAI Responses to sigma.

func NewAzureResponsesProvider

func NewAzureResponsesProvider(opts ...ProviderOption) *AzureResponsesProvider

NewAzureResponsesProvider constructs an Azure OpenAI Responses provider.

func (*AzureResponsesProvider) API

func (p *AzureResponsesProvider) API() sigma.API

API reports the Azure OpenAI Responses API surface.

func (*AzureResponsesProvider) Stream

Stream sends req to the Azure Responses endpoint and emits sigma events as SSE chunks arrive.

type AzureTokenCredential

type AzureTokenCredential interface {
	GetAzureToken(context.Context, AzureTokenRequest) (AzureAccessToken, error)
}

AzureTokenCredential is a narrow adapter interface for Microsoft Entra ID token sources. Azure SDK credentials can be wrapped to this interface without importing Azure SDK packages into sigma.

type AzureTokenCredentialFunc

type AzureTokenCredentialFunc func(context.Context, AzureTokenRequest) (AzureAccessToken, error)

AzureTokenCredentialFunc adapts a function into AzureTokenCredential.

func (AzureTokenCredentialFunc) GetAzureToken

GetAzureToken calls f.

type AzureTokenRequest

type AzureTokenRequest struct {
	Scopes []string
}

AzureTokenRequest describes the token request made by AzureResponsesProvider.

type CodeInterpreterContainer

type CodeInterpreterContainer struct {
	FileIDs []string
}

CodeInterpreterContainer configures an auto-provisioned code interpreter container.

type CodeInterpreterOption

type CodeInterpreterOption func(*codeInterpreterConfig)

CodeInterpreterOption configures OpenAI code interpreter.

func WithContainerFiles

func WithContainerFiles(container *CodeInterpreterContainer) CodeInterpreterOption

func WithContainerID

func WithContainerID(id string) CodeInterpreterOption

type CodexBrowserAuthInfo added in v0.3.0

type CodexBrowserAuthInfo struct {
	URL          string
	Instructions string
}

CodexBrowserAuthInfo reports the authorization URL that callers should open in a browser to complete OpenAI Codex OAuth login.

type CodexBrowserLoginOptions added in v0.3.0

type CodexBrowserLoginOptions struct {
	HTTPClient   *http.Client
	OnAuth       func(CodexBrowserAuthInfo)
	OnManualCode func(context.Context, CodexBrowserManualPrompt) (string, error)
}

CodexBrowserLoginOptions configures OpenAI Codex browser callback login.

type CodexBrowserManualPrompt added in v0.3.0

type CodexBrowserManualPrompt struct {
	Message string
}

CodexBrowserManualPrompt describes the fallback prompt for manually pasting an authorization code or redirect URL.

type CodexDeviceCodeInfo added in v0.3.0

type CodexDeviceCodeInfo struct {
	UserCode        string
	VerificationURI string
	Interval        time.Duration
	ExpiresIn       time.Duration
}

CodexDeviceCodeInfo reports the user code and verification URL that should be shown to the caller during OpenAI Codex device-code login.

type CodexDeviceCodeLoginOptions added in v0.3.0

type CodexDeviceCodeLoginOptions struct {
	HTTPClient   *http.Client
	OnDeviceCode func(CodexDeviceCodeInfo)
}

CodexDeviceCodeLoginOptions configures OpenAI Codex device-code login.

type CodexOAuthCredentials added in v0.3.0

type CodexOAuthCredentials struct {
	AccessToken  string
	RefreshToken string
	Expiry       time.Time
	AccountID    string
}

CodexOAuthCredentials carries OpenAI Codex OAuth tokens. Callers own persistence; Sigma never stores these credentials.

func LoginOpenAICodexBrowser added in v0.3.0

func LoginOpenAICodexBrowser(ctx context.Context, opts CodexBrowserLoginOptions) (CodexOAuthCredentials, error)

LoginOpenAICodexBrowser runs the OpenAI Codex browser callback OAuth flow and returns credentials for caller-managed persistence.

func LoginOpenAICodexDeviceCode added in v0.3.0

func LoginOpenAICodexDeviceCode(ctx context.Context, opts CodexDeviceCodeLoginOptions) (CodexOAuthCredentials, error)

LoginOpenAICodexDeviceCode runs the OpenAI Codex device-code OAuth flow and returns credentials for caller-managed persistence.

func RefreshOpenAICodexToken added in v0.3.0

func RefreshOpenAICodexToken(ctx context.Context, refreshToken string, opts CodexOAuthTokenProviderOptions) (CodexOAuthCredentials, error)

RefreshOpenAICodexToken refreshes OpenAI Codex OAuth credentials from a refresh token.

type CodexOAuthTokenProviderOptions added in v0.3.0

type CodexOAuthTokenProviderOptions struct {
	HTTPClient    *http.Client
	Now           func() time.Time
	RefreshBefore time.Duration
	OnRefresh     func(context.Context, CodexOAuthCredentials) error
}

CodexOAuthTokenProviderOptions configures the OAuth token provider returned by NewCodexOAuthTokenProvider.

type CodexResponsesProvider

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

CodexResponsesProvider adapts OpenAI Codex Responses to sigma. It reuses the OpenAI Responses payload and SSE parsing path, but requires explicit OAuth credentials instead of reading credentials from environment or global state.

func NewCodexResponsesProvider

func NewCodexResponsesProvider(opts ...ProviderOption) *CodexResponsesProvider

NewCodexResponsesProvider constructs an OpenAI Codex Responses provider.

func (*CodexResponsesProvider) API

func (p *CodexResponsesProvider) API() sigma.API

API reports the OpenAI Codex Responses API surface.

func (*CodexResponsesProvider) Stream

Stream sends req to the Codex Responses endpoint and emits sigma events as SSE chunks arrive.

type EmbeddingsProvider added in v0.3.0

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

EmbeddingsProvider adapts OpenAI's embeddings API to sigma.

func NewEmbeddingsProvider added in v0.3.0

func NewEmbeddingsProvider(opts ...ProviderOption) *EmbeddingsProvider

NewEmbeddingsProvider constructs an OpenAI Embeddings API provider.

func (*EmbeddingsProvider) API added in v0.3.0

API reports the OpenAI Embeddings API surface.

func (*EmbeddingsProvider) Embed added in v0.3.0

Embed sends req to OpenAI's embeddings endpoint.

type FileSearchComparisonFilter

type FileSearchComparisonFilter struct {
	Key   string
	Type  string
	Value any
}

type FileSearchCompoundFilter

type FileSearchCompoundFilter struct {
	Type    string
	Filters []FileSearchFilter
}

type FileSearchFilter

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

type FileSearchOption

type FileSearchOption func(*fileSearchConfig)

FileSearchOption configures OpenAI file search.

func WithFileSearchFilters

func WithFileSearchFilters(filters FileSearchFilter) FileSearchOption

func WithMaxNumResults

func WithMaxNumResults(results int) FileSearchOption

func WithRanking

func WithRanking(ranking FileSearchRanking) FileSearchOption

func WithVectorStoreIDs

func WithVectorStoreIDs(ids ...string) FileSearchOption

type FileSearchRanking

type FileSearchRanking struct {
	Ranker         string
	ScoreThreshold float64
}

type ImageGenerationMask

type ImageGenerationMask struct {
	FileID   string
	ImageURL string
}

type ImageGenerationOption

type ImageGenerationOption func(*imageGenerationConfig)

ImageGenerationOption configures OpenAI image generation as a Responses tool.

func WithBackground

func WithBackground(background string) ImageGenerationOption

func WithImageModel

func WithImageModel(model string) ImageGenerationOption

func WithImageQuality

func WithImageQuality(quality string) ImageGenerationOption

func WithImageSize

func WithImageSize(size string) ImageGenerationOption

func WithInputFidelity

func WithInputFidelity(fidelity string) ImageGenerationOption

func WithInputImageMask

func WithInputImageMask(mask ImageGenerationMask) ImageGenerationOption

func WithModeration

func WithModeration(moderation string) ImageGenerationOption

func WithOutputCompression

func WithOutputCompression(compression int) ImageGenerationOption

func WithOutputFormat

func WithOutputFormat(format string) ImageGenerationOption

func WithPartialImages

func WithPartialImages(images int) ImageGenerationOption

type ImagesProvider added in v0.2.0

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

ImagesProvider adapts OpenAI's image generation API to sigma.

func NewImagesProvider added in v0.2.0

func NewImagesProvider(opts ...ProviderOption) *ImagesProvider

NewImagesProvider constructs an OpenAI Images API provider.

func (*ImagesProvider) API added in v0.2.0

func (p *ImagesProvider) API() sigma.ImageAPI

API reports the OpenAI Images API surface.

func (*ImagesProvider) Generate added in v0.2.0

Generate sends req to OpenAI's non-streaming image endpoint.

func (*ImagesProvider) StreamImages added in v0.3.0

func (p *ImagesProvider) StreamImages(ctx context.Context, model sigma.ImageModel, req sigma.ImageRequest, opts sigma.Options) *sigma.ImageStream

StreamImages sends req to OpenAI's streaming image endpoint.

type LocalEmbeddingConfig added in v0.3.0

type LocalEmbeddingConfig struct {
	Provider            sigma.ProviderID
	ID                  sigma.ModelID
	BaseURL             string
	APIKeyEnv           string
	Headers             map[string]string
	Name                string
	DefaultDimensions   int
	MinDimensions       int
	MaxDimensions       int
	MaxInputTokens      int
	MaxBatchInputs      int
	MaxBatchBytes       int
	InputCostPerMillion float64
	CostCurrency        string
	ProviderMetadata    map[string]any
}

LocalEmbeddingConfig configures RegisterLocalEmbeddings for a local or private OpenAI-compatible embeddings endpoint.

type Provider

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

Provider adapts OpenAI Chat Completions-compatible HTTP APIs to sigma.

func NewProvider

func NewProvider(opts ...ProviderOption) *Provider

NewProvider constructs an OpenAI Chat Completions-compatible provider.

func (*Provider) API

func (p *Provider) API() sigma.API

API reports the OpenAI Chat Completions API surface.

func (*Provider) Stream

func (p *Provider) Stream(ctx context.Context, model sigma.Model, req sigma.Request, opts sigma.Options) *sigma.Stream

Stream sends req to a Chat Completions-compatible endpoint and emits sigma events as SSE chunks arrive.

type ProviderOption

type ProviderOption func(*Provider)

ProviderOption configures a Provider.

func WithBaseURL

func WithBaseURL(baseURL string) ProviderOption

WithBaseURL configures the provider base URL, for example an httptest server URL ending in /v1 or a local OpenAI-compatible endpoint.

func WithHTTPClient

func WithHTTPClient(client *http.Client) ProviderOption

WithHTTPClient configures the provider fallback HTTP client.

func WithHeader

func WithHeader(key, value string) ProviderOption

WithHeader configures a provider default request header.

func WithHeaders

func WithHeaders(headers map[string]string) ProviderOption

WithHeaders configures provider default request headers.

type ResponsesProvider

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

ResponsesProvider adapts the OpenAI Responses API to sigma.

func NewResponsesProvider

func NewResponsesProvider(opts ...ProviderOption) *ResponsesProvider

NewResponsesProvider constructs an OpenAI Responses API provider.

func (*ResponsesProvider) API

func (p *ResponsesProvider) API() sigma.API

API reports the OpenAI Responses API surface.

func (*ResponsesProvider) Stream

func (p *ResponsesProvider) Stream(ctx context.Context, model sigma.Model, req sigma.Request, opts sigma.Options) *sigma.Stream

Stream sends req to the Responses endpoint and emits sigma events as SSE chunks arrive.

type VertexConfig added in v0.4.0

type VertexConfig struct {
	ProjectID      string
	Location       string
	APIVersion     string
	CredentialMode VertexCredentialMode
}

VertexConfig carries Vertex OpenAI-compatible request configuration.

type VertexCredentialMode added in v0.4.0

type VertexCredentialMode string

VertexCredentialMode selects the Google Vertex AI authentication path.

const (
	// VertexCredentialAuto resolves a sigma credential first, then falls back to
	// the configured token provider when no API key or token is available.
	VertexCredentialAuto VertexCredentialMode = VertexCredentialMode(vertexai.CredentialAuto)
	// VertexCredentialAPIKey requires an API-key credential.
	VertexCredentialAPIKey VertexCredentialMode = VertexCredentialMode(vertexai.CredentialAPIKey)
	// VertexCredentialToken requires an OAuth token credential.
	VertexCredentialToken VertexCredentialMode = VertexCredentialMode(vertexai.CredentialToken)
)

type VertexProvider added in v0.4.0

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

VertexProvider adapts Vertex OpenAI-compatible MaaS Chat Completions to sigma.

func NewVertexProvider added in v0.4.0

func NewVertexProvider(opts ...VertexProviderOption) *VertexProvider

NewVertexProvider constructs a Vertex OpenAI-compatible provider.

func (*VertexProvider) API added in v0.4.0

func (p *VertexProvider) API() sigma.API

API reports the OpenAI Chat Completions API surface.

func (*VertexProvider) Stream added in v0.4.0

func (p *VertexProvider) Stream(ctx context.Context, model sigma.Model, req sigma.Request, opts sigma.Options) *sigma.Stream

Stream sends req to Vertex OpenAI-compatible Chat Completions and emits sigma events.

type VertexProviderOption added in v0.4.0

type VertexProviderOption func(*VertexProvider)

VertexProviderOption configures a VertexProvider.

func WithVertexBaseURL added in v0.4.0

func WithVertexBaseURL(baseURL string) VertexProviderOption

WithVertexBaseURL configures the Vertex service base URL including API version.

func WithVertexConfig added in v0.4.0

func WithVertexConfig(config VertexConfig) VertexProviderOption

WithVertexConfig configures provider-level Vertex routing and auth defaults.

func WithVertexHTTPClient added in v0.4.0

func WithVertexHTTPClient(client *http.Client) VertexProviderOption

WithVertexHTTPClient configures the provider fallback HTTP client.

func WithVertexHeader added in v0.4.0

func WithVertexHeader(key, value string) VertexProviderOption

WithVertexHeader configures a provider default request header.

func WithVertexHeaders added in v0.4.0

func WithVertexHeaders(headers map[string]string) VertexProviderOption

WithVertexHeaders configures provider default request headers.

func WithVertexTokenProvider added in v0.4.0

func WithVertexTokenProvider(tokenProvider sigma.OAuthTokenProvider) VertexProviderOption

WithVertexTokenProvider configures an ADC or OAuth token provider.

type WebSearchFilters

type WebSearchFilters struct {
	AllowedDomains []string
}

WebSearchFilters configures search result filtering.

type WebSearchLocation

type WebSearchLocation struct {
	Country  string
	City     string
	Region   string
	Timezone string
}

WebSearchLocation configures approximate user location for search.

type WebSearchOption

type WebSearchOption func(*webSearchConfig)

WebSearchOption configures OpenAI web search.

func WithExternalWebAccess

func WithExternalWebAccess(enabled bool) WebSearchOption

func WithSearchContextSize

func WithSearchContextSize(size string) WebSearchOption

func WithSearchFilters

func WithSearchFilters(filters WebSearchFilters) WebSearchOption

func WithUserLocation

func WithUserLocation(location WebSearchLocation) WebSearchOption

Jump to

Keyboard shortcuts

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