The OpenRouter SDK is a Go client for building AI-powered features with OpenRouter. It gives you type-safe access to 400+ models across providers through an OpenAI-compatible API, plus OpenRouter-specific features like provider routing, guardrails, and analytics.
To learn more, see the API Reference and Documentation.
Note
This SDK is in beta. Pin to a specific version to avoid unexpected breaking changes:
go get github.com/OpenRouterTeam/go-sdk@v0.5.0The OpenRouter Go SDK wraps the OpenRouter API with idiomatic Go types, retries, and error handling. For a longer introduction, see OVERVIEW.md.
- Chat completions with streaming and non-streaming responses
- Embeddings, rerank, TTS, and video generation
- Beta Responses API for agent-style workflows
- Platform APIs for API keys, credits, models, providers, guardrails, workspaces, and analytics
- Configurable retries, custom HTTP clients, and typed API errors
Install the module with:
go get github.com/OpenRouterTeam/go-sdkSee examples/README.md for runnable examples, starting with examples/chat.
Add the SDK to your module:
go get github.com/OpenRouterTeam/go-sdkFor beta releases, pin an explicit version:
go get github.com/OpenRouterTeam/go-sdk@v0.5.0This SDK requires Go 1.25 or higher.
package main
import (
"context"
"log"
"os"
openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/models/components"
"github.com/OpenRouterTeam/go-sdk/optionalnullable"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Chat.Send(ctx, components.ChatRequest{
Model: openrouter.Pointer("openai/gpt-4o"),
Messages: []components.ChatMessages{
components.CreateChatMessagesUser(
components.ChatUserMessage{
Role: components.ChatUserMessageRoleUser,
Content: components.CreateChatUserMessageContentStr(
"Hello, how are you?",
),
},
),
},
Temperature: optionalnullable.From(openrouter.Pointer(0.7)),
}, nil)
if err != nil {
log.Fatal(err)
}
if res != nil && res.ChatResult != nil {
log.Println(res.ChatResult.Choices)
}
}This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable |
|---|---|---|---|
APIKey |
http | HTTP Bearer | OPENROUTER_API_KEY |
You can configure it using the WithSecurity option when initializing the SDK client instance. For example:
package main
import (
"context"
openrouter "github.com/OpenRouterTeam/go-sdk"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Analytics.GetUserActivity(ctx, nil, nil, nil)
if err != nil {
log.Fatal(err)
}
if res != nil {
// handle response
}
}Some operations in this SDK require the security scheme to be specified at the request level. For example:
package main
import (
"context"
openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/models/operations"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New()
res, err := s.Models.ListForUser(ctx, operations.ListModelsUserSecurity{
Bearer: os.Getenv("OPENROUTER_BEARER"),
})
if err != nil {
log.Fatal(err)
}
if res != nil {
// handle response
}
}Available methods
- GetUserActivity - Get user activity grouped by endpoint
- GetCurrentKeyMetadata - Get current API key
- List - List API keys
- Create - Create a new API key
- Delete - Delete an API key
- Get - Get a single API key
- Update - Update an API key
- GetAnalyticsMeta - Get available analytics metrics and dimensions
- QueryAnalytics - Query analytics data
- Send - Create a response
- List - List BYOK provider credentials
- Create - Create a BYOK provider credential
- Delete - Delete a BYOK provider credential
- Get - Get a BYOK provider credential
- Update - Update a BYOK provider credential
- Send - Create a chat completion
- GetCredits - Get remaining credits
- GetAppRankings - Top apps by token usage
- GetBenchmarksArtificialAnalysis - Artificial Analysis Benchmark Indices
- GetBenchmarksDesignArena - Design Arena Benchmark Rankings
- GetRankingsDaily - Daily token totals for top 50 models
- Generate - Submit an embedding request
- ListModels - List all embeddings models
- ListZdrEndpoints - Preview the impact of ZDR on the available endpoints
- List - List all endpoints for a model
- List - List files
- Upload - Upload a file
- Delete - Delete a file
- Retrieve - Get file metadata
- Download - Download file content
- GetGeneration - Get request & usage metadata for a generation
- ListGenerationContent - Get stored prompt and completion content for a generation
- List - List guardrails
- Create - Create a guardrail
- Delete - Delete a guardrail
- Get - Get a guardrail
- Update - Update a guardrail
- ListGuardrailKeyAssignments - List key assignments for a guardrail
- BulkAssignKeys - Bulk assign keys to a guardrail
- BulkUnassignKeys - Bulk unassign keys from a guardrail
- ListGuardrailMemberAssignments - List member assignments for a guardrail
- BulkAssignMembers - Bulk assign members to a guardrail
- BulkUnassignMembers - Bulk unassign members from a guardrail
- ListKeyAssignments - List all key assignments
- ListMemberAssignments - List all member assignments
- Get - Get a model by its slug
- List - List all models and their properties
- Count - Get total count of available models
- ListForUser - List models filtered by user provider preferences, privacy settings, and guardrails
- ExchangeAuthCodeForAPIKey - Exchange authorization code for API key
- CreateAuthCode - Create authorization code
- List - List observability destinations
- Create - Create an observability destination
- Delete - Delete an observability destination
- Get - Get an observability destination
- Update - Update an observability destination
- ListMembers - List organization members
- List - List presets
- Get - Get a preset
- CreatePresetsChatCompletions - Create a preset from a chat-completions request body
- CreatePresetsMessages - Create a preset from a messages request body
- CreatePresetsResponses - Create a preset from a responses request body
- ListVersions - List versions of a preset
- GetVersion - Get a specific version of a preset
- List - List all providers
- Rerank - Submit a rerank request
- CreateTranscription - Create transcription
- CreateSpeech - Create speech
- Generate - Submit a video generation request
- GetGeneration - Poll video generation status
- GetVideoContent - Download generated video content
- ListVideosModels - List all video generation models
- List - List workspaces
- Create - Create a workspace
- Delete - Delete a workspace
- Get - Get a workspace
- Update - Update a workspace
- BulkAddMembers - Bulk add members to a workspace
- BulkRemoveMembers - Bulk remove members from a workspace
Server-sent events are used to stream content from certain
operations. These operations will expose the stream as an iterable that
can be consumed using a simple for loop. The loop will
terminate when the server no longer has any events to send and closes the
underlying connection.
For chat completions, check res.EventStream after setting Stream: openrouter.Pointer(true) on components.ChatRequest. See examples/chat-stream for a runnable example.
package main
import (
"context"
openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/models/components"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Beta.Responses.Send(ctx, components.ResponsesRequest{
Input: openrouter.Pointer(components.CreateInputsUnionStr(
"Tell me a joke",
)),
Model: openrouter.Pointer("openai/gpt-4o"),
}, components.MetadataLevelEnabled.ToPointer())
if err != nil {
log.Fatal(err)
}
if res != nil {
defer res.ResponsesStreamingResponse.Close()
for res.ResponsesStreamingResponse.Next() {
event := res.ResponsesStreamingResponse.Value()
log.Print(event)
// Handle the event
}
}
}Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the
returned response object will have a Next method that can be called to pull down the next group of results. If the
return value of Next is nil, then there are no more pages to be fetched.
Here's an example of one such pagination call:
package main
import (
"context"
openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/optionalnullable"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Byok.List(ctx, optionalnullable.From[int64](nil), nil, nil, nil)
if err != nil {
log.Fatal(err)
}
if res != nil {
for {
// handle items
res, err = res.Next()
if err != nil {
// handle error
}
if res == nil {
break
}
}
}
}Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retry.Config object to the call by using the WithRetries option:
package main
import (
"context"
openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/models/operations"
"github.com/OpenRouterTeam/go-sdk/retry"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Analytics.GetUserActivity(ctx, nil, nil, nil, operations.WithRetries(
retry.Config{
Strategy: "backoff",
Backoff: &retry.BackoffStrategy{
InitialInterval: 1,
MaxInterval: 50,
Exponent: 1.1,
MaxElapsedTime: 100,
},
RetryConnectionErrors: false,
}))
if err != nil {
log.Fatal(err)
}
if res != nil {
// handle response
}
}If you'd like to override the default retry strategy for all operations that support retries, you can use the WithRetryConfig option at SDK initialization:
package main
import (
"context"
openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/retry"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithRetryConfig(
retry.Config{
Strategy: "backoff",
Backoff: &retry.BackoffStrategy{
InitialInterval: 1,
MaxInterval: 50,
Exponent: 1.1,
MaxElapsedTime: 100,
},
RetryConnectionErrors: false,
}),
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Analytics.GetUserActivity(ctx, nil, nil, nil)
if err != nil {
log.Fatal(err)
}
if res != nil {
// handle response
}
}Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both.
By Default, an API error will return sdkerrors.APIError. When custom error responses are specified for an operation, the SDK may also return their associated error. You can refer to respective Errors tables in SDK docs for more details on possible error types for each operation.
For example, the GetUserActivity function may return the following errors:
| Error Type | Status Code | Content Type |
|---|---|---|
| sdkerrors.BadRequestResponseError | 400 | application/json |
| sdkerrors.UnauthorizedResponseError | 401 | application/json |
| sdkerrors.ForbiddenResponseError | 403 | application/json |
| sdkerrors.NotFoundResponseError | 404 | application/json |
| sdkerrors.InternalServerResponseError | 500 | application/json |
| sdkerrors.APIError | 4XX, 5XX | */* |
package main
import (
"context"
"errors"
openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/models/sdkerrors"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Analytics.GetUserActivity(ctx, nil, nil, nil)
if err != nil {
var e *sdkerrors.BadRequestResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.UnauthorizedResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.ForbiddenResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.NotFoundResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.InternalServerResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.APIError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
}
}You can override the default server globally using the WithServer(server string) option when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:
| Name | Server | Description |
|---|---|---|
production |
https://openrouter.ai/api/v1 |
Production server |
package main
import (
"context"
openrouter "github.com/OpenRouterTeam/go-sdk"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithServer("production"),
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Analytics.GetUserActivity(ctx, nil, nil, nil)
if err != nil {
log.Fatal(err)
}
if res != nil {
// handle response
}
}The default server can also be overridden globally using the WithServerURL(serverURL string) option when initializing the SDK client instance. For example:
package main
import (
"context"
openrouter "github.com/OpenRouterTeam/go-sdk"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithServerURL("https://openrouter.ai/api/v1"),
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Analytics.GetUserActivity(ctx, nil, nil, nil)
if err != nil {
log.Fatal(err)
}
if res != nil {
// handle response
}
}The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface:
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}The built-in net/http client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout.
import (
"net/http"
"time"
"github.com/OpenRouterTeam/go-sdk"
)
var (
httpClient = &http.Client{Timeout: 30 * time.Second}
sdkClient = openrouter.New(openrouter.WithClient(httpClient))
)This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration.
This SDK is in beta. Breaking changes may ship in minor 0.x releases. Pin to a specific module version in production, and review RELEASES.md before upgrading.
While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.
Safe to edit manually without being overwritten by Speakeasy generation:
- USAGE.md — source for the README SDK Example Usage section
- OVERVIEW.md — extended introduction
- examples/ — runnable example modules
- docs/sdks/chat/README.md and other files tracked in Speakeasy persistent edits