openrouter-go
AGENTS.md4 starsChanged 13 months agoUnlicenseArchived repositoryView on GitHub
Conventions for AI coding agents (Claude Code, Cursor, etc.) writing code against github.com/hra42/openrouter-go. Read this once per session before generating SDK code. For build, test, and e2e commands see CLAUDE.md. For a task → file index see llms.txt. Minimum viable call: Every configurable call uses functional options. Do not invent config structs. If you need to set something, look for a With* function. When adding a feature, search options.go (and *_options.go) first — the option almost certainly already exists. Every…
- Reads credentials
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,337 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
14 rules. About 0 are common, 1 is distinctive, and 13 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
13
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 13
API key: read from env (OPENROUTER_API_KEY).
- Very specific: line 14
Context: every API call takes context.Context as the first arg.
- Very specific: line 32
Every configurable call uses functional options.
- Very specific: line 37
When adding a feature, search options.go (and *_options.go) first — the option almost certainly already exists.
- Very specific: line 43
Every stream type (ChatStream, CompletionStream, ResponsesStream) follows the same protocol.
- Very specific: line 76
All API errors unwrap to *openrouter.RequestError:
- Very specific: line 134
Tool calling requires a tool-capable model: If a model doesn't support tools, the API returns an error — don't paper over it with a …
- Very specific: line 135
ChatCompleteStreamreturns aChatStream, not a channel: Don't wrap it in a goroutine that publishes to a chan unless you also propagate … - Very specific: line 137
Context cancellation interrupts streams cleanly: Prefer ctx cancellation over closing the stream prematurely from a different goroutine.
- Very specific: line 138
WithTransforms("middle-out")silently drops content: when the prompt exceeds the context window. - Very specific: line 146
Add an e2e test in cmd/openrouter-test/main.go — see the CRITICAL E2E Test Guidelines in CLAUDE.md.
- Distinctive: line 147
Follow the functional-options pattern — don't introduce new config shapes.
- Very specific: line 148
If the endpoint streams, reuse internal/sse/.
- Very specific: line 150
Add an example under examples/<feature>/main.go runnable via go run.
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.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
AGENTS.md
Conventions for AI coding agents (Claude Code, Cursor, etc.) writing code against github.com/hra42/openrouter-go. Read this once per session before generating SDK code.
For build, test, and e2e commands see CLAUDE.md. For a task → file index see llms.txt.
Before you write code
- Import:
import "github.com/hra42/openrouter-go"— package name isopenrouter. - Go version: 1.26+. No external dependencies are used or welcome — the SDK is standard-library only.
- API key: read from env (
OPENROUTER_API_KEY). Never hardcode. - Context: every API call takes
context.Contextas the first arg. Plumb it through; don'tcontext.Background()inside library-style code.
Minimum viable call:
client := openrouter.NewClient(openrouter.WithAPIKey(os.Getenv("OPENROUTER_API_KEY")))
resp, err := client.ChatComplete(ctx,
[]openrouter.Message{openrouter.CreateUserMessage("hi")},
openrouter.WithModel("openai/gpt-4o-mini"),
)
if err != nil { /* see Errors below */ }
fmt.Println(resp.Choices[0].Message.Content)The one pattern: functional options
Every configurable call uses functional options. Do not invent config structs. If you need to set something, look for a With* function.
- Client-level:
ClientOption— applied once atNewClient(...). Examples:WithAPIKey,WithBaseURL,WithHTTPClient,WithTimeout,WithReferer,WithAppName,WithMaxRetries,WithRetryDelay,WithCustomHeader. - Request-level: distinct option types per endpoint (
ChatCompletionOption,CompletionOption,ResponsesOption, …) but same shape. Examples:WithModel,WithMessages,WithTemperature,WithMaxTokens,WithTopP,WithStop,WithTools,WithToolChoice,WithResponseFormat,WithTransforms,WithReasoning,WithProvider.
When adding a feature, search options.go (and *_options.go) first — the option almost certainly already exists.
Streaming contract
Every stream type (ChatStream, CompletionStream, ResponsesStream) follows the same protocol. Violating this leaks the underlying HTTP connection.
stream, err := client.ChatCompleteStream(ctx, messages, openrouter.WithModel(m))
if err != nil { return err }
defer func() { _ = stream.Close() }() // always
for event := range stream.Events() {
for _, choice := range event.Choices {
if choice.Delta != nil {
if s, ok := choice.Delta.Content.(string); ok {
fmt.Print(s)
}
}
}
}
if err := stream.Err(); err != nil { // check AFTER the channel drains
return err
}Rules:
defer stream.Close()immediately after the nil-error check.- Drain
stream.Events()to completion OR cancel the context — don't break early without cancel. stream.Err()is checked after theEvents()channel closes.- Tool calls stream as deltas — accumulate
Choices[0].Delta.ToolCallsby index before acting.
SSE parsing lives in internal/sse/ — do not reach into it from user code.
Errors
All API errors unwrap to *openrouter.RequestError:
var rerr *openrouter.RequestError
if errors.As(err, &rerr) {
switch {
case rerr.IsRateLimitError(): // 429 — respect rerr.RetryAfter
case rerr.IsAuthenticationError(): // 401/403
case rerr.IsModerationError(): // provider moderation
case rerr.IsContextLengthError(): // shrink messages or use WithTransforms
}
}The client already retries transient failures with exponential backoff (configurable via WithMaxRetries / WithRetryDelay). Don't layer your own retry on top unless you have a reason.
Which endpoint for which task
| You want to… | Use | Why |
| Have a chat-style conversation | ChatComplete / ChatCompleteStream | Modern, supports tools, structured output, multimodal |
| Use a raw prompt (legacy / base models) | Complete / CompleteStream | Prompt-in, text-out |
| Use OpenAI's Responses API shape | CreateResponse / CreateResponseStream | Beta — unstable. Prefer ChatComplete for production |
| Talk to Claude via Anthropic shape | CreateAnthropicMessage / Stream | Drop-in for code already using Anthropic SDK types |
| Get vector embeddings | CreateEmbedding / CreateEmbeddings | Pair with Chunk* helpers in chunking.go for long docs |
| Discover models / pricing | ListModels, ListModelEndpoints, ListProviders | Metadata, no inference calls |
| Manage account / keys | GetCredits, GetActivity, ListKeys, CreateKey, … | Admin surface |
| Manage workspaces | ListWorkspaces, CreateWorkspace, UpdateWorkspace, DeleteWorkspace, AddWorkspaceMembers, RemoveWorkspaceMembers | Management (Provisioning) key required |
| List organization members | ListOrganizationMembers | Management key required |
| Configure spend/model guardrails | CreateGuardrail, ListGuardrails, AssignKeysToGuardrail, AssignMembersToGuardrail, … | Management key required. Caps USD spend, restricts models/providers, enforces ZDR |
| Generate a video | CreateVideo → GetVideo (poll) → GetVideoContent | Async: submit, poll until terminal status, then download bytes |
| Synthesize speech | CreateSpeech | Returns raw mp3 or pcm bytes |
| Rerank documents | Rerank | Second-stage scoring after vector retrieval |
| Parse an OpenRouter Broadcast webhook | broadcast.ParseTrace* functions | No Client needed — standalone utilities |
| Convert an MCP tool to OpenAI shape | ConvertMCPTool | No Client needed — standalone utility |
| Complete an OAuth PKCE flow | ExchangeAuthCode | Converts a PKCE auth code into an API key |
Multimodal inputs
Messages hold Content as either a plain string or []ContentPart. Use helpers to build parts:
- Image:
openrouter.NewImageContentPart(url)or base64 data URL. Seeexamples/image-inputs/. - Audio:
openrouter.NewAudioContentPart(base64Data, format)where format is"wav"or"mp3". Helpers inaudio_utils.go. Seeexamples/audio-inputs/. - PDF:
openrouter.NewFileContentPart(filename, base64Data)+WithPDFEngine(...)option. Seeexamples/pdf-inputs/. - Text file: same
NewFileContentPart. Seeexamples/text-file-inputs/.
Model must support the modality — check ListModelEndpoints or OpenRouter docs before assuming.
Things that will bite you
- Responses API is beta.
responses.gomay have breaking changes without notice. Don't put it behind a public stable interface. - Web search pricing is not uniform.
WithWebSearchcan use native provider search or Exa; they price differently. Callers should know which engine they asked for. - Tool calling requires a tool-capable model. If a model doesn't support tools, the API returns an error — don't paper over it with a fallback to
ChatCompletewithout tools; surface it. ChatCompleteStreamreturns aChatStream, not a channel. Don't wrap it in a goroutine that publishes to a chan unless you also propagatestream.Err().model+":nitro"/":floor"/":online"are suffix modifiers. Concatenate with the base model string — they aren't separate options.- Context cancellation interrupts streams cleanly. Prefer
ctxcancellation over closing the stream prematurely from a different goroutine. WithTransforms("middle-out")silently drops content when the prompt exceeds the context window. Useful, but don't enable it by default in code that needs determinism.- App attribution headers (
WithReferer,WithAppName) affect OpenRouter's app leaderboard and some provider analytics. Set them in production apps. - Two kinds of cost — estimated vs. actual.
cost.go(EstimateCost,EstimateCostFromTokens) computes a client-side estimate from model pricing × tokens, useful before a call. The actual cost OpenRouter charged is always returned inresp.Usage.Cost(a*float64in credits) — no request flag is needed (the oldusage:{include:true}param is deprecated and ignored). For streaming, the cost arrives on the final chunk'sUsage, so accumulate it while ranging overstream.Events(). For BYOK (Bring Your Own Key) requests,Usage.Costis typically 0 (no OpenRouter charge) and the real spend is inUsage.CostDetails.UpstreamInferenceCost;Usage.IsBYOK(bool) tells you which case you're in.
When adding a new endpoint (SDK contributors)
- Add an e2e test in
cmd/openrouter-test/main.go— see the CRITICAL E2E Test Guidelines in CLAUDE.md. Test functions that hit chat/completion endpoints MUST acceptmodel string; never hardcode model names. - Follow the functional-options pattern — don't introduce new config shapes.
- If the endpoint streams, reuse
internal/sse/. - Errors go through
RequestError— don't invent new error types for the same failure modes. - Add an example under
examples/<feature>/main.gorunnable viago run.
Reference
- Public godoc: https://pkg.go.dev/github.com/hra42/openrouter-go
- Examples:
examples/(27 subdirs, eachgo run-able) - E2E harness:
cmd/openrouter-test/ - Upstream API docs: https://openrouter.ai/docs
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.

