openai

package
v0.0.80 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2026 License: GPL-3.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultCodexClientVersion = "0.144.1"
	DefaultOAuthClientID      = "app_EMoamEEZ73f0CkXaXp7hrann"
	DefaultOAuthIssuer        = "https://auth.openai.com"
	DefaultOAuthTokenEndpoint = "https://auth.openai.com/oauth/token"
)
View Source
const (
	// DefaultChatModel/DefaultChatMiniModel are the default OpenAI-compatible
	// runtime models used when callers omit an explicit model selection.
	// These defaults should be Responses-compatible.
	DefaultChatModel     = "gpt-5.6-sol"
	DefaultChatMiniModel = "gpt-5.3-codex-spark"
)

Variables

This section is empty.

Functions

func CalculateCost

func CalculateCost(model string, usage anthropic.Usage) float64

CalculateCost returns the estimated USD cost for an OpenAI-compatible request.

func CodexClientVersion

func CodexClientVersion() string

func EstimateCost

func EstimateCost(model string, usage anthropic.Usage) (float64, bool)

EstimateCost returns the estimated USD cost for an OpenAI-compatible request together with whether pricing for the model is known.

func FetchModelMetadataByID

func FetchModelMetadataByID(ctx context.Context, baseURL string, session *OpenAIAuthSession) (map[string]ModelMetadata, error)

FetchModelMetadataByID fetches model metadata keyed by lower-case model ID. Prefixed aliases such as "openai/gpt-5.5" are intentionally not synthesized; callers can strip provider prefixes for lookup.

func IsChatGPTBackendBaseURL

func IsChatGPTBackendBaseURL(raw string) bool

IsChatGPTBackendBaseURL reports whether a base URL targets the ChatGPT backend.

func SupportsChatCompletions

func SupportsChatCompletions(model string) bool

SupportsChatCompletions reports whether the configured model is compatible with the Chat Completions endpoint.

func ValidateChatCompletionsModel

func ValidateChatCompletionsModel(model string) error

ValidateChatCompletionsModel returns an actionable error for incompatible models when a caller needs Chat-Completions-only behavior.

Types

type AuthMode

type AuthMode string
const (
	AuthModeAPIKey AuthMode = "api-key"
	AuthModeOAuth  AuthMode = "oauth"
)

func NormalizeAuthMode

func NormalizeAuthMode(mode string) AuthMode

NormalizeAuthMode resolves configured mode and defaults to API key mode.

type Client

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

Client implements OpenAI-compatible Responses APIs.

func NewClient

func NewClient(apiKey string, opts ...Option) *Client

NewClient creates a new OpenAI-compatible client.

func NewClientWithAuthSession

func NewClientWithAuthSession(session *OpenAIAuthSession, opts ...Option) *Client

NewClientWithAuthSession creates a new OpenAI-compatible client from an auth session.

func (*Client) AnalyzeImage

func (c *Client) AnalyzeImage(ctx context.Context, model, imageURL, prompt, detail string) (*anthropic.CreateMessageResponse, error)

AnalyzeImage sends a single image plus prompt through the OpenAI Responses image-input path and returns the assembled assistant message.

func (*Client) CompactConversation

func (*Client) CreateMessageStream

func (c *Client) CreateMessageStream(ctx context.Context, req anthropic.CreateMessageRequest) (messageStream, error)

func (*Client) SupportsResponseCompaction

func (c *Client) SupportsResponseCompaction() bool

type CompactConversationResponse

type CompactConversationResponse struct {
	ID       string
	Messages []anthropic.Message
	Usage    anthropic.Usage
	Raw      *responses.CompactedResponse
}

CompactConversationResponse is the compacted context window returned by OpenAI Responses compaction, expressed as Anthropic-shaped messages so the agent layer can keep using provider-neutral RunItems.

type CustomAuthSessionConfig added in v0.0.12

type CustomAuthSessionConfig struct {
	RequestHeaders  func(context.Context) (map[string]string, error)
	Refresh         func(context.Context) error
	SupportsRefresh func() bool
	SDKAPIKey       string
}

type ModelMetadata

type ModelMetadata struct {
	ID                            string
	ContextWindow                 int
	MaxContextWindow              int
	MaxOutputTokens               int
	AutoCompactTokenLimit         int
	EffectiveContextWindowPercent int
}

ModelMetadata is the subset of provider model metadata the SDK uses. The ChatGPT Codex backend returns these fields from /models.

func FetchModelMetadata

func FetchModelMetadata(ctx context.Context, baseURL string, session *OpenAIAuthSession) ([]ModelMetadata, error)

FetchModelMetadata fetches OpenAI-compatible model metadata.

It supports both the standard OpenAI /v1/models shape:

{"data":[{"id":"gpt-..."}]}

and the ChatGPT Codex backend shape:

{"models":[{"slug":"gpt-...","context_window":272000,...}]}

func (ModelMetadata) ResolvedContextWindow

func (m ModelMetadata) ResolvedContextWindow() int

ResolvedContextWindow mirrors Codex's ModelInfo::resolved_context_window.

type ModelPricing

type ModelPricing struct {
	InputPerMillion           float64
	CachedInputPerMillion     float64
	CacheWriteInputPerMillion float64
	OutputPerMillion          float64
}

ModelPricing holds per-million-token prices in USD.

type OAuthSessionConfig

type OAuthSessionConfig struct {
	AuthJSON      []byte
	AuthJSONPath  string
	AccountID     string
	AccountIDPath string
	ClientID      string
	TokenEndpoint string
	ClientVersion string
	RefreshClient *http.Client
}

type OpenAIAuthSession

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

func NewAPIKeyAuthSession

func NewAPIKeyAuthSession(apiKey string) *OpenAIAuthSession

func NewCustomAuthSession added in v0.0.12

func NewCustomAuthSession(cfg CustomAuthSessionConfig) *OpenAIAuthSession

func NewOAuthAuthSessionFromConfig

func NewOAuthAuthSessionFromConfig(cfg OAuthSessionConfig) (*OpenAIAuthSession, error)

func NewOAuthAuthSessionFromFile

func NewOAuthAuthSessionFromFile(authJSONPath, accountIDPath string) (*OpenAIAuthSession, error)

func NewOAuthAuthSessionFromSecretData

func NewOAuthAuthSessionFromSecretData(authJSON []byte, accountIDOverride string) (*OpenAIAuthSession, error)

func (*OpenAIAuthSession) DisableRefresh

func (s *OpenAIAuthSession) DisableRefresh()

func (*OpenAIAuthSession) IsOAuth

func (s *OpenAIAuthSession) IsOAuth() bool

func (*OpenAIAuthSession) NeedsRefresh

func (s *OpenAIAuthSession) NeedsRefresh() bool

func (*OpenAIAuthSession) Refresh

func (s *OpenAIAuthSession) Refresh(ctx context.Context) error

func (*OpenAIAuthSession) RefreshAndSerialize

func (s *OpenAIAuthSession) RefreshAndSerialize(ctx context.Context, accountIDOverride string) ([]byte, error)

func (*OpenAIAuthSession) RequestHeaders

func (s *OpenAIAuthSession) RequestHeaders(ctx context.Context) (map[string]string, error)

func (*OpenAIAuthSession) SupportsRefresh

func (s *OpenAIAuthSession) SupportsRefresh() bool

type Option

type Option func(*clientConfig)

Option configures the OpenAI-compatible client.

func WithAPIMode

func WithAPIMode(mode string) Option

WithAPIMode forces which OpenAI endpoint family to use: - "responses" => /v1/responses - "chat-completions" => /v1/chat/completions - "" or unknown => "responses"

func WithAuthSession

func WithAuthSession(session *OpenAIAuthSession) Option

WithAuthSession sets the auth session used for request headers and refresh.

func WithBaseURL

func WithBaseURL(url string) Option

WithBaseURL overrides the OpenAI-compatible API base URL.

Supported forms: - https://api.openai.com/v1 - https://api.openai.com/v1/chat/completions (legacy; normalized to /v1) - https://api.openai.com/v1/responses (legacy; normalized to /v1)

func WithMaxConcurrent

func WithMaxConcurrent(n int) Option

WithMaxConcurrent sets maximum in-flight API requests.

func WithModelFallbacks added in v0.0.5

func WithModelFallbacks(models []string) Option

WithModelFallbacks sets an ordered list of fallback model identifiers. For OpenRouter (and other OpenAI-compatible backends that honor it) these are sent as the request body's "models" array so the provider automatically retries the next model when one is unavailable or errors. The primary request model is always tried first; fallbacks follow in order. It is a no-op for the Responses API path. An empty list leaves the request unchanged.

type RequestError

type RequestError struct {
	StatusCode int
	Body       string
	API        string
	Endpoint   string
	// contains filtered or unexported fields
}

RequestError is an OpenAI-compatible HTTP request error.

func (*RequestError) Error

func (e *RequestError) Error() string

func (*RequestError) RetryAfterMS

func (e *RequestError) RetryAfterMS() int

RetryAfterMS returns Retry-After in milliseconds.

func (*RequestError) Retryable

func (e *RequestError) Retryable() bool

Retryable reports whether this error should be retried.

type ResponseFailedError

type ResponseFailedError struct {
	ID               string
	Status           string
	Code             string
	Message          string
	IncompleteReason string
	// EmptyOutput marks a response that returned no usable output content under
	// an otherwise non-terminal status (e.g. "completed" with empty content) —
	// a transient provider glitch worth retrying.
	EmptyOutput bool
}

ResponseFailedError preserves terminal Responses status details instead of collapsing them into a generic empty-output error.

func (*ResponseFailedError) Error

func (e *ResponseFailedError) Error() string

func (*ResponseFailedError) NonRetryableReason

func (e *ResponseFailedError) NonRetryableReason() string

func (*ResponseFailedError) Reason added in v0.0.14

func (e *ResponseFailedError) Reason() string

func (*ResponseFailedError) Retryable

func (e *ResponseFailedError) Retryable() bool

type ResponsesStreamReader

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

ResponsesStreamReader wraps the SDK's real SSE stream and translates OpenAI Responses streaming events into Anthropic-style StreamEvents.

func (*ResponsesStreamReader) Close

func (r *ResponsesStreamReader) Close() error

Close closes the underlying SSE stream.

func (*ResponsesStreamReader) Next

Next returns the next translated Anthropic-style stream event.

type StreamReader

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

StreamReader replays synthetic Anthropic-style events derived from Responses output.

func (*StreamReader) Close

func (r *StreamReader) Close() error

Close is a no-op for buffered stream readers.

func (*StreamReader) Next

func (r *StreamReader) Next() (anthropic.StreamEvent, error)

Next returns the next synthetic stream event.

Jump to

Keyboard shortcuts

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