agentleFS
hra42hra42/openrouter-go/AGENTS.md

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.

  • In this repository2 other files it gives its agents.

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
  1. Very specific:

    API key: read from env (OPENROUTER_API_KEY).

    line 13
  2. Very specific:

    Context: every API call takes context.Context as the first arg.

    line 14
  3. Very specific:

    Every configurable call uses functional options.

    line 32
  4. Very specific:

    When adding a feature, search options.go (and *_options.go) first — the option almost certainly already exists.

    line 37
  5. Very specific:

    Every stream type (ChatStream, CompletionStream, ResponsesStream) follows the same protocol.

    line 43
  6. Very specific:

    All API errors unwrap to *openrouter.RequestError:

    line 76
  7. Very specific:

    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 …

    line 134
  8. Very specific:

    ChatCompleteStream returns a ChatStream, not a channel: Don't wrap it in a goroutine that publishes to a chan unless you also propagate …

    line 135
  9. Very specific:

    Context cancellation interrupts streams cleanly: Prefer ctx cancellation over closing the stream prematurely from a different goroutine.

    line 137
  10. Very specific:

    WithTransforms("middle-out") silently drops content: when the prompt exceeds the context window.

    line 138
  11. Very specific:

    Add an e2e test in cmd/openrouter-test/main.go — see the CRITICAL E2E Test Guidelines in CLAUDE.md.

    line 146
  12. Distinctive:

    Follow the functional-options pattern — don't introduce new config shapes.

    line 147
  13. Very specific:

    If the endpoint streams, reuse internal/sse/.

    line 148
  14. Very specific:

    Add an example under examples/<feature>/main.go runnable via go run.

    line 150

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

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

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 is openrouter.
  • 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.Context as the first arg. Plumb it through; don't context.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 at NewClient(...). 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:

  1. defer stream.Close() immediately after the nil-error check.
  2. Drain stream.Events() to completion OR cancel the context — don't break early without cancel.
  3. stream.Err() is checked after the Events() channel closes.
  4. Tool calls stream as deltas — accumulate Choices[0].Delta.ToolCalls by 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…UseWhy
Have a chat-style conversationChatComplete / ChatCompleteStreamModern, supports tools, structured output, multimodal
Use a raw prompt (legacy / base models)Complete / CompleteStreamPrompt-in, text-out
Use OpenAI's Responses API shapeCreateResponse / CreateResponseStreamBeta — unstable. Prefer ChatComplete for production
Talk to Claude via Anthropic shapeCreateAnthropicMessage / StreamDrop-in for code already using Anthropic SDK types
Get vector embeddingsCreateEmbedding / CreateEmbeddingsPair with Chunk* helpers in chunking.go for long docs
Discover models / pricingListModels, ListModelEndpoints, ListProvidersMetadata, no inference calls
Manage account / keysGetCredits, GetActivity, ListKeys, CreateKey, …Admin surface
Manage workspacesListWorkspaces, CreateWorkspace, UpdateWorkspace, DeleteWorkspace, AddWorkspaceMembers, RemoveWorkspaceMembersManagement (Provisioning) key required
List organization membersListOrganizationMembersManagement key required
Configure spend/model guardrailsCreateGuardrail, ListGuardrails, AssignKeysToGuardrail, AssignMembersToGuardrail, …Management key required. Caps USD spend, restricts models/providers, enforces ZDR
Generate a videoCreateVideo → GetVideo (poll) → GetVideoContentAsync: submit, poll until terminal status, then download bytes
Synthesize speechCreateSpeechReturns raw mp3 or pcm bytes
Rerank documentsRerankSecond-stage scoring after vector retrieval
Parse an OpenRouter Broadcast webhookbroadcast.ParseTrace* functionsNo Client needed — standalone utilities
Convert an MCP tool to OpenAI shapeConvertMCPToolNo Client needed — standalone utility
Complete an OAuth PKCE flowExchangeAuthCodeConverts 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. See examples/image-inputs/.
  • Audio: openrouter.NewAudioContentPart(base64Data, format) where format is "wav" or "mp3". Helpers in audio_utils.go. See examples/audio-inputs/.
  • PDF: openrouter.NewFileContentPart(filename, base64Data) + WithPDFEngine(...) option. See examples/pdf-inputs/.
  • Text file: same NewFileContentPart. See examples/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.go may have breaking changes without notice. Don't put it behind a public stable interface.
  • Web search pricing is not uniform. WithWebSearch can 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 ChatComplete without tools; surface it.
  • ChatCompleteStream returns a ChatStream, not a channel. Don't wrap it in a goroutine that publishes to a chan unless you also propagate stream.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 ctx cancellation 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 in resp.Usage.Cost (a *float64 in credits) — no request flag is needed (the old usage:{include:true} param is deprecated and ignored). For streaming, the cost arrives on the final chunk's Usage, so accumulate it while ranging over stream.Events(). For BYOK (Bring Your Own Key) requests, Usage.Cost is typically 0 (no OpenRouter charge) and the real spend is in Usage.CostDetails.UpstreamInferenceCost; Usage.IsBYOK (bool) tells you which case you're in.

When adding a new endpoint (SDK contributors)

  1. 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 accept model string; never hardcode model names.
  2. Follow the functional-options pattern — don't introduce new config shapes.
  3. If the endpoint streams, reuse internal/sse/.
  4. Errors go through RequestError — don't invent new error types for the same failure modes.
  5. Add an example under examples/<feature>/main.go runnable via go run.

Reference

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.