codex

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 28 Imported by: 0

Documentation

Overview

Package codex adapts OpenAI's ChatGPT subscription Codex Responses protocol to llm's provider-neutral generation interfaces. Callers own the ChatGPT authentication lifecycle and supply either current credentials or a resolver; this package does not perform or persist OAuth logins. Models explicitly configured with CapabilityAudio accept user-message WAV, MP3/MPEG, M4A/MP4, WebM, and Ogg input through the subscription Responses backend.

TransportSSE is the compatibility-preserving default. TransportWebSocket reuses an idle session connection but always sends full context. TransportWebSocketCached and TransportAuto may send a verified continuation delta only when the canonical request exactly extends the preceding request and response. Requests with per-attempt headers use transient sockets. Auto falls back to SSE only when the WebSocket handshake fails before response.create is sent; strict WebSocket modes never fall back, and ambiguous response.create write failures are not retried internally. Call Client.Close to release cached and active WebSocket resources early.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccountIDFromToken

func AccountIDFromToken(token string) (string, error)

AccountIDFromToken extracts the ChatGPT account identifier from an OpenAI ID or access JWT without verifying its signature. The server verifies the token when it is used; this helper only reads the routing claim.

Types

type APIError

type APIError = internalresponses.APIError

APIError is a provider error reported by the Codex Responses endpoint.

type Client

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

Client is a concurrency-safe ChatGPT subscription Codex client. Its configuration is immutable; WebSocket modes maintain an internal session connection cache. The credential resolver and HTTP client must also be safe for concurrent use.

func New

func New(config Config) (*Client, error)

New constructs a Client from config using subscription protocol defaults.

func NewWithCompatibility

func NewWithCompatibility(config Config, compatibility *llm.OpenAIResponsesCompatibility) (*Client, error)

NewWithCompatibility constructs a Client with model compatibility metadata. compatibility is copied during construction.

func (*Client) Close

func (c *Client) Close() error

Close closes all cached Codex WebSocket sessions. It is idempotent and safe to call concurrently. A closed Client cannot start new WebSocket requests; its SSE transport remains unaffected.

func (*Client) Generate

func (c *Client) Generate(ctx context.Context, request llm.Request) (_ *llm.Response, err error)

Generate performs one Codex Responses request. The subscription endpoint is streaming-only, so Generate assembles its result from the same event stream used by Stream.

func (*Client) Info

func (c *Client) Info() llm.ModelInfo

Info describes the configured model and its explicitly declared optional capabilities.

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, request llm.Request) (_ llm.Stream, err error)

Stream starts one streaming Codex Responses request. Provider, credential, and transport failures after validation are delivered by the returned stream.

type Config

type Config struct {
	Provider           string
	Model              string
	Capabilities       []llm.Capability
	AccessToken        string
	AccountID          string
	ResolveCredentials CredentialResolver
	BaseURL            string
	HTTPClient         *http.Client
	// WebSocketDialer overrides WebSocket dialing. Client copies the dialer,
	// its TLS configuration, and ordinary option slices during construction.
	// Callback, pool, certificate, key, root, cache, and jar objects referenced
	// by the dialer must be concurrency-safe and must not be mutated during use.
	WebSocketDialer *websocket.Dialer
	Headers         http.Header
	Originator      string
	// Transport defaults to TransportSSE.
	Transport TransportMode
	// WebSocketIdleTime bounds how long an unused session socket is retained.
	// Zero selects five minutes.
	WebSocketIdleTime time.Duration
	// WebSocketMaxAge bounds total session socket lifetime. Zero selects 55 minutes.
	WebSocketMaxAge time.Duration
	// WebSocketConnectTimeout bounds the handshake. Zero selects 15 seconds.
	WebSocketConnectTimeout time.Duration
	// WebSocketMaxSessions bounds retained session sockets. Zero selects 64;
	// negative values are invalid. Busy sockets are never evicted.
	WebSocketMaxSessions int
}

Config configures a ChatGPT subscription Codex client. Model is required. Provider identifies the service in ModelInfo and errors and defaults to "openai-codex". Set either AccessToken (with optional AccountID) or ResolveCredentials, but not both. ResolveCredentials is called before every request and once more after an HTTP 401.

BaseURL defaults to https://chatgpt.com/backend-api. Capabilities opts the configured model into optional protocol features; generation is always enabled, while streaming, tools, vision, and audio must be listed explicitly. Audio capability is model-gated and enables user-message WAV, MP3/MPEG, M4A/MP4, WebM, and Ogg inputs up to 50 MiB each. HTTPClient owns the SSE transport. WebSocketDialer, when non-nil, explicitly owns WebSocket dialing; otherwise Client best-effort copies settings from a concrete *http.Transport and cannot adapt arbitrary RoundTripper wrappers. Custom Headers are copied. Authorization, ChatGPT-Account-ID, OpenAI-Beta, Originator, Content-Type, Accept, and User-Agent are owned by Client and overwrite custom values. SSE uses http.DefaultClient when HTTPClient is nil, so callers should use context deadlines when an unbounded request is not acceptable. Transport defaults to SSE, preserving the original behavior. Strict WebSocket modes never fall back to SSE; Auto falls back only for a pre-send connection failure.

type CredentialResolver

type CredentialResolver func(ctx context.Context, rejectedAccessToken string) (Credentials, error)

CredentialResolver returns current ChatGPT subscription credentials. rejectedAccessToken is nonempty after the server rejects a token with HTTP 401. Implementations that refresh credentials should rotate only when their current token still matches rejectedAccessToken. A resolver must be safe for concurrent use.

type Credentials

type Credentials struct {
	AccessToken string
	AccountID   string
}

Credentials authorize one request against a ChatGPT subscription. AccountID may be empty when AccessToken is a JWT containing chatgpt_account_id.

type TransportMode

type TransportMode string

TransportMode selects the Codex Responses transport.

const (
	// TransportSSE preserves the original HTTP event-stream transport and is the default.
	TransportSSE TransportMode = "sse"
	// TransportWebSocket uses WebSocket but always sends full canonical context.
	TransportWebSocket TransportMode = "websocket"
	// TransportWebSocketCached enables verified connection-scoped continuation deltas.
	TransportWebSocketCached TransportMode = "websocket-cached"
	// TransportAuto uses cached WebSocket and falls back to SSE only when the
	// WebSocket connection cannot be established before response.create is sent.
	TransportAuto TransportMode = "auto"
)

Jump to

Keyboard shortcuts

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