codex

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package codex provides a chat model backed by an existing OpenAI Codex CLI subscription. It reads ~/.codex/auth.json for ChatGPT OAuth tokens (refreshing them when needed) and talks to ChatGPT's Codex backend using the Responses API.

Index

Constants

View Source
const DefaultBaseURL = "https://chatgpt.com/backend-api/codex"

DefaultBaseURL is the Codex backend exposed to ChatGPT subscribers.

View Source
const DefaultModel = "gpt-5-codex"

DefaultModel is the model used by the Codex CLI when nothing is configured. The server may transparently route this to newer revisions (gpt-5.1-codex-*).

Variables

This section is empty.

Functions

This section is empty.

Types

type AuthFile

type AuthFile struct {
	OpenAIAPIKey string     `json:"OPENAI_API_KEY,omitempty"`
	Tokens       *AuthToken `json:"tokens,omitempty"`
	LastRefresh  string     `json:"last_refresh,omitempty"`
}

AuthFile mirrors the on-disk shape of ~/.codex/auth.json.

type AuthManager

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

AuthManager loads, caches, and refreshes Codex CLI credentials.

func NewAuthManager

func NewAuthManager(path string) (*AuthManager, error)

NewAuthManager constructs a manager backed by the file at path. An empty path resolves to $CODEX_HOME/auth.json (defaulting to ~/.codex/auth.json).

func (*AuthManager) AccessToken

func (m *AuthManager) AccessToken(ctx context.Context) (token, accountID string, err error)

AccessToken returns a valid bearer token, refreshing if it is close to expiry. It also returns the account_id used for the ChatGPT-Account-ID header.

func (*AuthManager) Path

func (m *AuthManager) Path() string

Path returns the auth file path the manager is bound to.

type AuthToken

type AuthToken struct {
	IDToken      string `json:"id_token"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	AccountID    string `json:"account_id,omitempty"`
}

AuthToken holds the OAuth tokens issued by ChatGPT login.

type ChatModel

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

ChatModel talks to ChatGPT's Codex backend using the user's CLI subscription.

func New

func New(optFns ...OptionFunc) (*ChatModel, error)

New builds a ChatModel. It loads the auth file eagerly so misconfiguration surfaces during construction, but defers token refresh until the first request.

func (*ChatModel) Batch

func (m *ChatModel) Batch(ctx context.Context, inputs [][]core.Message, opts ...core.Option) ([]*core.AIMessage, error)

Batch performs multiple chat completions sequentially.

func (*ChatModel) BindSkills

func (m *ChatModel) BindSkills(skills ...llms.SkillDefinition) llms.ChatModel

BindSkills returns a copy of the model with skills bound. Codex's Responses API has no native skill concept, so bound skills are forwarded as appended instructions instead.

func (*ChatModel) BindTools

func (m *ChatModel) BindTools(tools ...llms.ToolDefinition) llms.ChatModel

BindTools returns a copy of the model with tool definitions attached.

func (*ChatModel) Generate

func (m *ChatModel) Generate(ctx context.Context, messages []core.Message, opts ...core.Option) (*llms.ChatResult, error)

Generate performs a chat completion and returns the full result. It uses the streaming endpoint under the hood because Codex's Responses API is streaming-first.

func (*ChatModel) GetName

func (m *ChatModel) GetName() string

GetName returns the chat model name.

func (*ChatModel) Invoke

func (m *ChatModel) Invoke(ctx context.Context, input []core.Message, opts ...core.Option) (*core.AIMessage, error)

Invoke sends messages and returns the assistant's reply.

func (*ChatModel) ListModels

func (m *ChatModel) ListModels(ctx context.Context) ([]Model, error)

ListModels fetches the models available to the authenticated ChatGPT account.

func (*ChatModel) ListModelsRaw

func (m *ChatModel) ListModelsRaw(ctx context.Context) ([]byte, error)

ListModelsRaw returns the raw JSON body from the /models endpoint. Useful for debugging when ListModels returns nothing because the schema shifted.

func (*ChatModel) Stream

func (m *ChatModel) Stream(ctx context.Context, input []core.Message, opts ...core.Option) (*core.StreamIterator[*core.AIMessage], error)

Stream opens an SSE stream against the Codex Responses API and decodes events into AIMessage chunks.

func (*ChatModel) WithStructuredOutput

func (m *ChatModel) WithStructuredOutput(schema map[string]any) llms.ChatModel

WithStructuredOutput requests JSON output that conforms to the given schema. The Codex backend does not advertise json_schema response_format on the ChatGPT path, so the schema is injected into the instructions.

type Model

type Model struct {
	ID                        string   `json:"id"`
	Model                     string   `json:"model"`
	DisplayName               string   `json:"displayName"`
	Description               string   `json:"description"`
	Hidden                    bool     `json:"hidden"`
	IsDefault                 bool     `json:"isDefault"`
	SupportedReasoningEfforts []string `json:"supportedReasoningEfforts"`
	DefaultReasoningEffort    string   `json:"defaultReasoningEffort"`
}

Model describes a model exposed by the Codex backend.

type OptionFunc

type OptionFunc func(*Options)

OptionFunc configures the Codex chat model.

func WithAuthFile

func WithAuthFile(path string) OptionFunc

WithAuthFile overrides the path to auth.json.

func WithBaseURL

func WithBaseURL(url string) OptionFunc

WithBaseURL overrides the Codex backend base URL.

func WithInstructions

func WithInstructions(instructions string) OptionFunc

WithInstructions sets a baseline instructions string for the Responses API.

func WithMaxOutputTokens

func WithMaxOutputTokens(n int) OptionFunc

WithMaxOutputTokens caps the output length.

func WithModelName

func WithModelName(model string) OptionFunc

WithModelName sets the model name (e.g. "gpt-5-codex").

func WithOriginator

func WithOriginator(originator string) OptionFunc

WithOriginator overrides the originator header.

func WithPromptCacheKey

func WithPromptCacheKey(key string) OptionFunc

WithPromptCacheKey enables server-side prompt caching for a stable session.

func WithReasoningEffort

func WithReasoningEffort(effort string) OptionFunc

WithReasoningEffort sets the reasoning effort for gpt-5-codex models.

func WithReasoningSummary

func WithReasoningSummary(summary string) OptionFunc

WithReasoningSummary sets the reasoning summary mode.

func WithUserAgent

func WithUserAgent(ua string) OptionFunc

WithUserAgent overrides the User-Agent header.

type Options

type Options struct {
	// AuthFile overrides the path to auth.json. Empty uses $CODEX_HOME/auth.json
	// (fallback: ~/.codex/auth.json).
	AuthFile string

	// Model is the model ID to send to the Responses API (e.g. "gpt-5-codex").
	Model string

	// BaseURL overrides the Codex backend base URL.
	BaseURL string

	// Originator is sent as the "originator" header. Defaults to "codex_cli_rs"
	// so traffic looks like a regular Codex CLI session to the backend.
	Originator string

	// UserAgent overrides the User-Agent header.
	UserAgent string

	// ReasoningEffort controls reasoning depth for gpt-5-codex-family models.
	// Valid values: "minimal", "low", "medium", "high", "xhigh".
	ReasoningEffort string

	// ReasoningSummary controls the reasoning summary mode (e.g. "auto", "none").
	ReasoningSummary string

	// Instructions is appended to or used as the system-level instructions.
	// Most callers should pass a system message instead; this is here for
	// providers/codex consumers that want a baseline instruction string.
	Instructions string

	// MaxOutputTokens optionally caps response length.
	MaxOutputTokens *int

	// PromptCacheKey enables server-side caching of repeated prefixes.
	PromptCacheKey string

	// HTTPTimeout for non-streaming requests. Streaming uses no timeout.
	HTTPTimeout int // seconds; 0 means no timeout
}

Options holds configuration for the Codex chat model.

func DefaultOptions

func DefaultOptions() *Options

DefaultOptions returns sensible defaults for the Codex provider.

Jump to

Keyboard shortcuts

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