openai

package
v0.0.41 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 44 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

llm proxy

Proxy LLM and remap model, and inspect request details.

Installation

go install github.com/xhd2015/llm-proxy@latest

Usages

Start a server:

llm-proxy --base-url https://api.anthropic.com --port 7788

Start cluade code with:

export ANTHROPIC_BASE_URL=http://localhost:7788
claude

Special note with sst/opencode

When running opencode with llm-proxy, you might encounter the following error:

Error: AI_TypeValidationError: Type validation failed: Value: {"type":"text","text":"I'm open","snapshot":"I'm open"}.
Error message: [{"code":"invalid_union","errors":[],"note":"No matching discriminator","discriminator":"type","path":["type"],"message":"Invalid input"}]

This is due to the server returned a message in the stream: {"type":"text","text":"I'm open","snapshot":"I'm open"}, which cannot be validated by the vercel AI SDK used by sst/opencode.

To tackle this issue:

llm-proxy --base-url https://api.anthropic.com --port 7789 --filter-text-snapshot

And configure opencode.json:

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "anthropic": {
      "models": {
        "claude-sonnet-4-20250514": {
          "name": "Claude Sonnet 4"
        }
      },
      "options": {
        "apiKey": "<YOUR_API_KEY>",
        "baseURL": "http://localhost:7789"
      }
    }
  }
}

Test with opencode:

opencode run "Who are you?"

Result:

I'm opencode, an interactive CLI tool that helps with software engineering tasks. I can help you write code, debug issues, run commands, search through codebases, and manage development workflows.

Command Code subscription proxy

--proxy-commandcode serves an Anthropic Messages API on loopback backed by your Command Code subscription, so clients such as Grok CLI can use Command Code models without running the cmd binary:

llm-proxy --proxy-commandcode --port 8892

Credentials are read from ~/.commandcode/auth.json on every request, so a rotated API key is picked up without a restart. Pass --commandcode-home DIR to read them from elsewhere (for example the cmd-xhd2015 sandbox) and --commandcode-version VER if Command Code raises its minimum client version. When the client sends thinking.display=summarized (Grok CLI does), the proxy coalesces Command Code's token-level reasoning and assistant text into fewer thinking_delta / text_delta events so Grok's TUI is not redrawn on every token. Pass --no-coalesce-thinking to flush every delta as before.

Generate the matching ~/.grok/config.toml model blocks:

llm-proxy commandcode-models >> ~/.grok/config.toml
grok -m cc-deepseek-v4-flash -p "hello" --always-approve

The proxy uses the messages (Anthropic) backend because Command Code's wire format already uses Anthropic-shaped content blocks and input_schema tools. It also serves GET /v1/models-v2 so Grok can refresh model context windows.

Note this routes your real Command Code subscription and consumes its quota/credits; Command Code's own plan gating still applies, so the usable model list is whatever your plan allows.

Capture Command Code traffic

capture runs a command with Command Code redirected to a local capture server and records every HTTP exchange (request + response) as JSONL:

llm-proxy capture --env-commandcode cmd-xhd2015 -p "hello" --yolo --skip-onboarding

The capture is written to /tmp/llm-proxy-capture.jsonl by default; pass -o FILE (must end with .jsonl) to change it. Sensitive headers such as Authorization are redacted unless --no-redact is given.

Responses are mocked, so the wrapped command finishes cleanly while the real outgoing requests are logged. The general HTTP/HTTPS proxy capture mode is not implemented yet, so --env-commandcode is currently required.

Grok CLI session proxy

--proxy-grok serves an OpenAI Responses API on loopback backed by your Grok CLI session (~/.grok/auth.json → https://cli-chat-proxy.grok.com):

llm-proxy --proxy-grok --port 8893

Credentials are re-read from ~/.grok/auth.json on every request and refreshed via the stored refresh_token when expired. Pass --grok-home DIR to read them from elsewhere. The proxy injects Authorization, X-XAI-Token-Auth, x-grok-model-override, and x-grok-client-version; the client key is ignored.

Print Codex config.toml for every cached Grok model:

llm-proxy grok-models

Note this routes your real Grok subscription and consumes its quota.

Codex ChatGPT/OAuth proxy

Use --codex when Codex is signed in with ChatGPT/OAuth and you want to route Codex traffic through llm-proxy:

llm-proxy --codex --port 8891

When routing the Codex backend to Grok CLI, add --feed-to-grok-cli to enable Grok CLI compatibility behavior: incompatible JSON keepalive SSE events are dropped while logged, and the local proxy serves Grok's models-v2 catalog request from the Codex model cache.

llm-proxy --codex --feed-to-grok-cli --port 8891

See Grok CLI compatibility for the session-resume behavior, model catalog response, and opt-in scope.

Append full proxy logs while keeping terminal output brief. The requested path is a symlink to an hourly log segment; the current and preceding hour are retained. Use tail -F to follow rotations:

llm-proxy --codex --port 8891 --log proxy.log
tail -F proxy.log

Configure Codex with the built-in OpenAI provider:

model_provider = "openai"
openai_base_url = "http://localhost:8891/v1"

Or with a custom provider:

model_provider = "llm-proxy"

[model_providers.llm-proxy]
name = "LLM Proxy"
base_url = "http://localhost:8891/v1"
requires_openai_auth = true
wire_api = "responses"
supports_websockets = true

Documentation

Index

Constants

View Source
const AdminPrefix = "/_llmproxy"

AdminPrefix is the control-plane surface mounted on the same listener as the proxy routes. The leading underscore keeps it out of the /v1 namespace and makes an accidental public exposure obvious in logs.

View Source
const DefaultClientTimeout = 30 * time.Second

DefaultClientTimeout bounds one control call. Mutations rewrite the config and rebuild route handlers, so this stays well above a plain status probe.

Variables

View Source
var CapNoImage = ModelCapability{NoImage: true}

CapNoImage is a capability value with only NoImage set.

Functions

func ApplyModelCapabilities added in v0.0.10

func ApplyModelCapabilities(data map[string]interface{}, caps map[string]ModelCapability, logf func(format string, args ...any)) int

ApplyModelCapabilities delegates to the unexported applyModelCapabilities so the doctest harness can exercise image stripping on decoded request bodies.

func DefaultConfigPath added in v0.0.35

func DefaultConfigPath() (string, error)

DefaultConfigPath is where the proxy config lives when nothing overrides it. modelcatalog owns the value because the model listing reads the same file.

func Handle added in v0.0.6

func Handle(args []string) error

Handle dispatches a llm-proxy CLI invocation to the doc subcommand, the usage summary, the OpenAI/Codex proxies, or a generic --base-url proxy.

func HandleUsages

func HandleUsages(args []string) error

func ParseModelCapabilities added in v0.0.10

func ParseModelCapabilities(entries []string) (map[string]ModelCapability, error)

ParseModelCapabilities delegates to the unexported parseModelCapabilities so the doctest harness can exercise --model-capability flag parsing.

func PatchCodexSSEOutput added in v0.0.6

func PatchCodexSSEOutput(body []byte) []byte

PatchCodexSSEOutput delegates to the unexported patchCodexSSEOutput so the doctest harness can exercise SSE output-item injection.

func ReadCodexAuth added in v0.0.6

func ReadCodexAuth(path string) (accessToken string, accountID string, err error)

ReadCodexAuth delegates to the unexported readCodexAuth so the doctest harness can exercise auth.json parsing against temp files.

func StartAPIProxy

func StartAPIProxy(baseUrl string, modelMappings []string, port string, verbose bool, logFile string, modelCaps map[string]ModelCapability, colorEnabled bool) error

func StartCodexProxy

func StartCodexProxy(baseUrl string, modelMappings []string, port string, verbose bool, logFile string, modelCaps map[string]ModelCapability, colorEnabled bool) error

StartCodexProxy starts a Codex OAuth proxy with the default stream behavior.

func TransformCodexRequest added in v0.0.6

func TransformCodexRequest(data map[string]interface{}, logf func(format string, args ...any))

TransformCodexRequest delegates to the unexported transformCodexRequest so the doctest harness can exercise system-message -> instructions adaptation.

Types

type AdminError added in v0.0.35

type AdminError struct {
	Status  int
	Message string
}

AdminError carries the HTTP status a mutation failure maps to, so the CLI, the embedded API, and the HTTP surface all report the same verdict.

func IsAdminError added in v0.0.35

func IsAdminError(err error) (*AdminError, bool)

adminStatusOfError is exported through the embeddable API so a supervisor can map a failed mutation onto its own HTTP status without string matching.

func (*AdminError) Error added in v0.0.35

func (e *AdminError) Error() string

type Client added in v0.0.35

type Client struct {
	// BaseURL is the proxy origin, for example http://127.0.0.1:8890. A path
	// prefix is allowed when the proxy is mounted under one.
	BaseURL string
	// HTTPClient carries the deadline. Nil uses DefaultClientTimeout, which is
	// generous enough for a reload that rebuilds every route.
	HTTPClient *http.Client
}

Client is an HTTP client for the control plane of a proxy that is already running, either as a separate process or as an embedded server mounted by a host that can only reach it over the wire.

It speaks exactly the endpoints config_admin.go serves, so a supervisor such as eluc does not need its own copy of the wire types: the same StatusReport, ReloadReport and SelectReport travel on the wire and come back as values.

func NewClient added in v0.0.35

func NewClient(baseURL string) *Client

NewClient returns a client for baseURL with the default timeout.

func (*Client) RefreshModelListing added in v0.0.35

func (c *Client) RefreshModelListing() error

RefreshModelListing asks the proxy to probe providers now. The proxy answers before the probe finishes, so the caller polls Status for the result.

func (*Client) Reload added in v0.0.35

func (c *Client) Reload() (ReloadReport, error)

Reload re-reads the config file. A failure is an *AdminError carrying the status a host should surface.

func (*Client) SelectCredential added in v0.0.35

func (c *Client) SelectCredential(provider, credential string) (SelectReport, error)

SelectCredential switches one provider's account and rewrites the config.

func (*Client) Status added in v0.0.35

func (c *Client) Status() (StatusReport, error)

Status reads the live configuration snapshot.

type ColorMode added in v0.0.12

type ColorMode int

ColorMode selects when ANSI color is emitted, per the three-mode policy (auto / always / never). See go-best-practice cli/color.

const (
	// ColorAuto enables color on a TTY unless NO_COLOR is set (default).
	ColorAuto ColorMode = iota
	// ColorAlways forces color on (--color).
	ColorAlways
	// ColorNever forces color off (--no-color).
	ColorNever
)

type ConfigWebGrokDiffResult added in v0.0.29

type ConfigWebGrokDiffResult struct {
	State   string
	Region  string
	Hash    string
	Note    string
	Preview string
	Changes int
}

ConfigWebGrokDiffResult mirrors the Grok read-only comparison for the doctest harness: the located [model.*] run, the export reduced to the same run, and how far apart they are.

func ConfigWebGrokDiff added in v0.0.29

func ConfigWebGrokDiff(path, preview string) ConfigWebGrokDiffResult

ConfigWebGrokDiff delegates to the same engine the report uses, with the target's path passed in so a leaf never resolves the developer's own ~/.grok/config.toml. The Grok target is compare-only, so nothing here writes.

type ConfigWebSaveResult added in v0.0.29

type ConfigWebSaveResult struct {
	Result  string
	Backup  string
	Content string
}

ConfigWebSaveResult mirrors the outcome of one block save.

func ConfigWebSaveRegion added in v0.0.29

func ConfigWebSaveRegion(path, key, preview, hash, region string, dryRun bool) (ConfigWebSaveResult, error)

ConfigWebSaveRegion delegates to the unexported block writer so the doctest harness can exercise the submitted text, conflict detection, locking, and the backup. The target behaves like the DSH one: it participates in the lock.

type ConfigWebSyncDiffResult added in v0.0.29

type ConfigWebSyncDiffResult struct {
	State   string
	Region  string
	Hash    string
	Note    string
	Preview string
	Changes int
	Err     string
}

ConfigWebSyncDiffResult mirrors the on-disk half of a fragment target for the doctest harness: the located block, its revision, and how far the preview and the file differ.

func ConfigWebSyncDiff added in v0.0.29

func ConfigWebSyncDiff(path, key, preview string) ConfigWebSyncDiffResult

ConfigWebSyncDiff delegates to the unexported fragment engine so the doctest harness can lock down block location and the preview/disk comparison. It mirrors the report and /api/diff paths without adding behavior.

type CredentialReport added in v0.0.35

type CredentialReport struct {
	Name      string `json:"name"`
	Selected  bool   `json:"selected"`
	Available bool   `json:"available"`
	Problem   string `json:"problem,omitempty"`
}

CredentialReport exposes a credential's identity and usability, never a secret.

type EmbedOptions added in v0.0.35

type EmbedOptions struct {
	// ConfigPath is the llm-proxy config file. Account switching and reload
	// write to this file, so it must be a regular file.
	ConfigPath string
	// PublicBase is the base URL clients see, including the version segment
	// (for example https://host/api/llm-proxy/v1). Empty keeps the standalone
	// default of http://<listen>/v1.
	PublicBase string
	// Logger receives model listing and control-plane messages. Nil opens
	// LogFile, or the log file named by the config when LogFile is empty too.
	Logger *logutil.Logger
	// LogFile is where the embedded proxy appends its own messages. A host that
	// runs the standalone form under a supervisor passes the same path both
	// ways so switching modes never moves the log.
	LogFile string
}

EmbedOptions configures an in-process proxy. Embedding keeps the proxy's routing, model listing, and control endpoints, but the host process owns the listener, so there is no listen address to reconcile.

type EmbeddedServer added in v0.0.35

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

EmbeddedServer is a proxy running inside another Go program. It implements http.Handler so the host can mount it under any prefix.

func StartEmbedded added in v0.0.35

func StartEmbedded(opts EmbedOptions) (*EmbeddedServer, error)

StartEmbedded loads opts.ConfigPath and prepares the proxy. It does not bind a socket: mount Handler() on the host's mux.

func (*EmbeddedServer) Close added in v0.0.35

func (s *EmbeddedServer) Close() error

Close stops background work. In-flight requests finish normally.

func (*EmbeddedServer) ConfigPath added in v0.0.35

func (s *EmbeddedServer) ConfigPath() string

ConfigPath reports the config file the proxy watches.

func (*EmbeddedServer) Endpoint added in v0.0.35

func (s *EmbeddedServer) Endpoint() string

Endpoint reports the base URL advertised to clients.

func (*EmbeddedServer) Handler added in v0.0.35

func (s *EmbeddedServer) Handler() http.Handler

Handler serves /v1 models, /v1/{messages,responses,chat/completions}, and the /_llmproxy control endpoints.

func (*EmbeddedServer) RefreshModelListing added in v0.0.35

func (s *EmbeddedServer) RefreshModelListing()

RefreshModelListing asks the listing loop to probe providers now.

func (*EmbeddedServer) Reload added in v0.0.35

func (s *EmbeddedServer) Reload() (ReloadReport, error)

Reload re-reads the config file. Failures are *AdminError values carrying the HTTP status a supervisor should surface.

func (*EmbeddedServer) SelectCredential added in v0.0.35

func (s *EmbeddedServer) SelectCredential(provider, credential string) (SelectReport, error)

SelectCredential switches one provider's account and rewrites the config.

func (*EmbeddedServer) Status added in v0.0.35

func (s *EmbeddedServer) Status() StatusReport

Status reports the live configuration and listing state.

type ListingReport added in v0.0.35

type ListingReport struct {
	Seed      bool   `json:"seed"`
	Source    string `json:"source,omitempty"`
	FetchedAt string `json:"fetchedAt,omitempty"`
	Error     string `json:"error,omitempty"`
}

ListingReport is the dynamic model listing state of one provider.

type ModelCapability added in v0.0.10

type ModelCapability struct {
	// NoImage marks a model that rejects image input upstream (e.g. a
	// text-only gateway endpoint answers 404). Image content parts are
	// replaced with a text note before the request leaves the proxy.
	NoImage bool
	// EffortMapping rewrites Anthropic output_config.effort to Command Code
	// params.reasoning_effort. Keys are the client-sent effort; values are
	// low, high, max, drop (omit the upstream field), or invalid (400 the
	// client). A missing key leaves today's behavior (do not send reasoning_effort).
	EffortMapping map[string]string
	// AdjustUsageForDSH rewrites Command Code Anthropic usage so input_tokens
	// is the uncached miss (DSH cache-hit % is cache_read / (input + cache_read)).
	AdjustUsageForDSH bool
}

ModelCapability is the per-model limits declared via --model-capability MODEL=opt1,opt2.

type ModelListingReport added in v0.0.35

type ModelListingReport struct {
	Mode            string `json:"mode"`
	RefreshInterval string `json:"refreshInterval,omitempty"`
	ProbeTimeout    string `json:"probeTimeout,omitempty"`
}

ModelListingReport describes how model names are resolved: a static list from the config, or names fetched from the provider on a schedule.

type ProviderReport added in v0.0.35

type ProviderReport struct {
	Name        string             `json:"name"`
	Kind        string             `json:"kind"`
	Models      int                `json:"models"`
	Selected    string             `json:"selected,omitempty"`
	Credentials []CredentialReport `json:"credentials,omitempty"`
	Listing     ListingReport      `json:"listing"`
}

ProviderReport summarises one configured provider.

type ReloadReport added in v0.0.35

type ReloadReport struct {
	Listen    string   `json:"listen"`
	Endpoint  string   `json:"endpoint"`
	Models    int      `json:"models"`
	Providers int      `json:"providers"`
	Warnings  []string `json:"warnings,omitempty"`
}

ReloadReport describes what a reload installed.

type SelectReport added in v0.0.35

type SelectReport struct {
	Provider     string `json:"provider"`
	Credential   string `json:"credential"`
	Previous     string `json:"previous"`
	Changed      bool   `json:"changed"`
	BackupPath   string `json:"backupPath,omitempty"`
	Listen       string `json:"listen"`
	Models       int    `json:"models"`
	Providers    int    `json:"providers"`
	RefreshAfter bool   `json:"refreshAfter"`
}

SelectReport describes an account switch.

type StatusReport added in v0.0.35

type StatusReport struct {
	Listen     string `json:"listen"`
	Endpoint   string `json:"endpoint"`
	ConfigPath string `json:"configPath,omitempty"`
	// LogPath is the file this proxy appends its own messages to. Empty when
	// the host mounted it with a logger it owns.
	LogPath      string             `json:"logPath,omitempty"`
	Models       int                `json:"models"`
	Providers    []ProviderReport   `json:"providers"`
	ModelListing ModelListingReport `json:"modelListing"`
	UptimeMillis int64              `json:"uptimeMillis"`
	Generation   uint64             `json:"generation"`
}

StatusReport is the full control-plane snapshot.

func InspectConfig added in v0.0.35

func InspectConfig(path string) (StatusReport, error)

InspectConfig describes a config file without starting anything: the listen address, how many routes it defines, and which credentials are usable right now. A host that supervises the proxy uses it to render a stopped service truthfully instead of guessing or inventing a sample.

The report reuses StatusReport so a stopped service and a running one have one shape; only the live fields (uptime, generation, listing progress) stay empty.

Jump to

Keyboard shortcuts

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