openrouter-go
CLAUDE.md4 starsChanged 13 months agoUnlicenseArchived repositoryView on GitHub
Writing code against the SDK? Read AGENTS.md first — it covers the functional-options pattern, the streaming contract, endpoint selection, and common pitfalls. This file is for build/test commands only. ALWAYS run the following after adding, removing, or changing any exported type, function, method, or constant — CI fails on a stale docs/api-surface.json: Commit the updated docs/api-surface.json alongside the code change in the same PR.
- Reads credentials
The file
We split this CLAUDE.md into the rules it gives an agent
10 rules. About 0 are common, 3 are distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈3
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 120
ALWAYS: run the following after adding, removing, or changing any exported type, function, method, or constant — CI fails on a stale …
- Very specific: line 126
Commit the updated docs/api-surface.json alongside the code change in the same PR.
- Distinctive: line 165
Context Support: All API methods accept context.Context for proper cancellation and timeout handling
- Very specific: line 177
IMPORTANT: When adding a new endpoint, always add a corresponding e2e test to cmd/openrouter-test/main.go:
- Very specific: line 178
Add the test name to the -test flag description
- Distinctive: line 179
Add a case handler in the switch statement
- Very specific: line 181
Add the test to the runAllTests() function array
- Very specific: line 186
Test function signatures that make API calls MUST accept model string as a parameter
- Very specific: line 192
When using model suffixes, concatenate properly: model+":nitro", model+":floor", model+":online"
- Distinctive: line 196
Always check error returns from API calls
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Writing code against the SDK? Read AGENTS.md first — it covers the functional-options pattern, the streaming contract, endpoint selection, and common pitfalls. This file is for build/test commands only.
Commands
Build and Test
# Run all tests
go test ./...
# Run tests with coverage
go test -cover ./...
# Run tests with race detection
go test -race ./...
# Run specific test
go test -run TestChatComplete
# Run tests in verbose mode
go test -v ./...
# Build the package
go build ./...
# Format code
go fmt ./...
# Run go vet for static analysis
go vet ./...
# Install dependencies
go mod download
# Update dependencies
go mod tidyRunning Examples
# Set API key
export OPENROUTER_API_KEY="your-api-key"
# Run examples
go run examples/basic/main.go
go run examples/streaming/main.go
go run examples/list-models/main.go
go run examples/advanced/main.go
go run examples/structured-output/main.go
go run examples/tool-calling/main.go
go run examples/web_search/main.go
go run examples/transforms/main.go
go run examples/app-attribution/main.go
go run examples/image-inputs/main.go
go run examples/audio-inputs/main.go
go run examples/pdf-inputs/main.go
go run examples/text-file-inputs/main.go
go run examples/mcp-tools/main.go
go run examples/responses/main.go
go run examples/embedding-chunking/main.go
go run examples/rerank/main.go
go run examples/broadcast-webhook/main.go
go run examples/list-organization-members/main.go
go run examples/videos/main.go
go run examples/workspaces/main.goRunning E2E Tests
# Set API key
export OPENROUTER_API_KEY="your-api-key"
# Run all tests
go run cmd/openrouter-test/main.go -test all
# Run specific test
go run cmd/openrouter-test/main.go -test models
go run cmd/openrouter-test/main.go -test chat
go run cmd/openrouter-test/main.go -test streaming
go run cmd/openrouter-test/main.go -test chatcost
go run cmd/openrouter-test/main.go -test image
go run cmd/openrouter-test/main.go -test audio
go run cmd/openrouter-test/main.go -test audiobuilder
go run cmd/openrouter-test/main.go -test audioformats
go run cmd/openrouter-test/main.go -test pdf
go run cmd/openrouter-test/main.go -test pdfengine
go run cmd/openrouter-test/main.go -test pdfannotations
go run cmd/openrouter-test/main.go -test base64pdf
go run cmd/openrouter-test/main.go -test pdfcomparison
go run cmd/openrouter-test/main.go -test textfile
go run cmd/openrouter-test/main.go -test multipletextfiles
go run cmd/openrouter-test/main.go -test textbuilder
go run cmd/openrouter-test/main.go -test textformats
go run cmd/openrouter-test/main.go -test mcp
go run cmd/openrouter-test/main.go -test responses
go run cmd/openrouter-test/main.go -test responses-reasoning
go run cmd/openrouter-test/main.go -test responses-tools
go run cmd/openrouter-test/main.go -test responses-websearch
go run cmd/openrouter-test/main.go -test responses-stream
go run cmd/openrouter-test/main.go -test zdr-endpoints
go run cmd/openrouter-test/main.go -test models-user
go run cmd/openrouter-test/main.go -test chunking
go run cmd/openrouter-test/main.go -test chunkedembedding
go run cmd/openrouter-test/main.go -test rerank
go run cmd/openrouter-test/main.go -test guardrails
go run cmd/openrouter-test/main.go -test organizationmembers
go run cmd/openrouter-test/main.go -test workspaces
go run cmd/openrouter-test/main.go -test videomodels
go run cmd/openrouter-test/main.go -test videos
# Run with verbose output
go run cmd/openrouter-test/main.go -test models -vRegenerating the API surface snapshot
ALWAYS run the following after adding, removing, or changing any exported type, function, method, or constant — CI fails on a stale docs/api-surface.json:
go run ./cmd/gen-api-surfaceCommit the updated docs/api-surface.json alongside the code change in the same PR.
Architecture Overview
This is a zero-dependency Go client library for the OpenRouter API that follows idiomatic Go patterns.
Core Components
Client (client.go): The main client struct that manages HTTP communication, authentication, and request routing. Uses functional options pattern for configuration.
Request/Response Types (models.go): Defines all data structures for API requests and responses, including messages, tools, and completion parameters.
Functional Options (options.go): Implements the options pattern for flexible configuration of both client and request parameters. This allows clean API usage like WithModel(), WithMessages(), etc.
Streaming (stream.go): Implements Server-Sent Events (SSE) parsing for streaming responses without external dependencies. Handles reconnection and error recovery.
Error Handling (errors.go): Custom error types that preserve OpenRouter API error details including rate limits, retry information, and moderation flags.
Retry Logic (retry.go): Implements exponential backoff with jitter for handling transient failures and rate limits.
API Endpoints
Chat Completions (chat.go): Modern chat API supporting messages, tools, structured outputs, and streaming.
Legacy Completions (completions.go): Support for older prompt-based completion API.
Models Listing (models_endpoint.go): Retrieve available models with filtering by category and detailed model information.
Web Search (web_search.go): Integration with OpenRouter's web search plugin for augmented responses.
MCP Tool Conversion (mcp.go): Utilities for converting MCP (Model Context Protocol) tool definitions to OpenAI-compatible format for use with OpenRouter.
Responses API (responses.go, responses_models.go, responses_options.go): [BETA - UNSTABLE] OpenAI-compatible Responses API with support for reasoning, tool calling, web search, and streaming. This is a stateless API where each request is independent. WARNING: This API is in beta and may have breaking changes at any time. Do not use in production workloads.
Broadcast Webhook (broadcast.go, broadcast_models.go): Utilities for parsing OTLP JSON trace payloads from OpenRouter's Broadcast webhook feature. Includes OTLP wire types, user-friendly trace extraction, and HTTP handler helpers. No Client dependency — standalone utilities like mcp.go.
Key Design Patterns
- Functional Options: Both client creation and API calls use functional options for clean, extensible configuration
- Context Support: All API methods accept context.Context for proper cancellation and timeout handling
- Zero Dependencies: Entire library uses only Go standard library
- Thread Safety: Client is safe for concurrent use across goroutines
- Streaming: Custom SSE parser handles streaming responses with proper cleanup
Testing Approach
- Unit tests for all public APIs using httptest for mocking HTTP responses
- Table-driven tests for comprehensive coverage of different scenarios
- Race detection tests to ensure thread safety
- Integration test utility in
cmd/openrouter-test/for live API testing
IMPORTANT: When adding a new endpoint, always add a corresponding e2e test to cmd/openrouter-test/main.go:
- Add the test name to the
-testflag description - Add a case handler in the switch statement
- Implement a
runXxxTest()function with comprehensive validation - Add the test to the
runAllTests()function array
CRITICAL E2E Test Guidelines:
- ALWAYS use the
modelparameter for ANY test that makes actual API calls to chat/completion endpoints - NEVER hardcode model names in test functions (e.g., "openai/gpt-4o", "meta-llama/llama-3.1-8b-instruct")
- Test function signatures that make API calls MUST accept
model stringas a parameter - Pass the
modelparameter through the switch statement andrunAllTests()function - The ONLY exceptions are:
runModelEndpointsTest- uses hardcoded models for metadata inspection (not API calls)runErrorTest- uses "invalid/nonexistent-model-xyz" for error testingrunModelsTest- doesn't make completion calls
- When using model suffixes, concatenate properly:
model+":nitro",model+":floor",model+":online"
Important Notes
- Always check error returns from API calls
- Streaming responses require proper cleanup by reading all events or canceling context
- The library automatically handles rate limiting with configurable retry logic
- Tool calls and structured outputs require compatible models (check OpenRouter docs)
- Web search can use either native provider search or Exa, with different pricing models
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

