openai

package
v0.0.24 Latest Latest
Warning

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

Go to latest
Published: Sep 20, 2026 License: MIT Imports: 25 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

This section is empty.

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 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 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 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.

Jump to

Keyboard shortcuts

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