Developer-friendly & type-safe Go SDK specifically catered to leverage openrouter API.
Important
This SDK is not yet ready for production use. To complete setup please follow the steps outlined in your workspace. Delete this section before > publishing to a package manager.
OpenRouter API: OpenAI-compatible API with additional OpenRouter features
For more information about the API: OpenRouter Documentation
To add the SDK as a dependency to your project:
go get github.com/OpenRouterTeam/go-sdkpackage 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.OpenResponsesRequest{})
if err != nil {
log.Fatal(err)
}
if res != nil {
defer res.Object.Close()
for res.Object.Next() {
event := res.Object.Value()
log.Print(event)
// Handle the event
}
}
}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"
"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.OpenResponsesRequest{})
if err != nil {
log.Fatal(err)
}
if res != nil {
defer res.Object.Close()
for res.Object.Next() {
event := res.Object.Value()
log.Print(event)
// Handle the event
}
}
}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/components"
"github.com/OpenRouterTeam/go-sdk/models/operations"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New()
res, err := s.Credits.CreateCoinbaseCharge(ctx, operations.CreateCoinbaseChargeSecurity{
Bearer: os.Getenv("OPENROUTER_BEARER"),
}, components.CreateChargeRequest{
Amount: 100,
Sender: "0x1234567890123456789012345678901234567890",
ChainID: components.ChainIDOne,
})
if err != nil {
log.Fatal(err)
}
if res != nil {
// handle response
}
}Available methods
- GetUserActivity - Get user activity grouped by endpoint
- List - List API keys
- Create - Create a new API key
- Update - Update an API key
- Delete - Delete an API key
- Get - Get a single API key
- GetCurrentKeyMetadata - Get current API key
- Send - Create a response
- Send - Create a chat completion
- GetCredits - Get remaining credits
- CreateCoinbaseCharge - Create a Coinbase charge for crypto payment
- Generate - Submit an embedding request
- ListModels - List all embeddings models
- List - List all endpoints for a model
- ListZdrEndpoints - Preview the impact of ZDR on the available endpoints
- GetGeneration - Get request & usage metadata for a generation
- List - List guardrails
- Create - Create a guardrail
- Get - Get a guardrail
- Update - Update a guardrail
- Delete - Delete a guardrail
- ListKeyAssignments - List all key assignments
- ListMemberAssignments - List all member assignments
- ListGuardrailKeyAssignments - List key assignments for a guardrail
- BulkAssignKeys - Bulk assign keys to a guardrail
- ListGuardrailMemberAssignments - List member assignments for a guardrail
- BulkAssignMembers - Bulk assign members to a guardrail
- BulkUnassignKeys - Bulk unassign keys from a guardrail
- BulkUnassignMembers - Bulk unassign members from a guardrail
- Count - Get total count of available models
- List - List all models and their properties
- 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 all providers
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.
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.OpenResponsesRequest{})
if err != nil {
log.Fatal(err)
}
if res != nil {
defer res.Object.Close()
for res.Object.Next() {
event := res.Object.Value()
log.Print(event)
// Handle the event
}
}
}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/components"
"github.com/OpenRouterTeam/go-sdk/retry"
"log"
"models/operations"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Beta.Responses.Send(ctx, components.OpenResponsesRequest{}, 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 {
defer res.Object.Close()
for res.Object.Next() {
event := res.Object.Value()
log.Print(event)
// Handle the event
}
}
}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/models/components"
"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.Beta.Responses.Send(ctx, components.OpenResponsesRequest{})
if err != nil {
log.Fatal(err)
}
if res != nil {
defer res.Object.Close()
for res.Object.Next() {
event := res.Object.Value()
log.Print(event)
// Handle the event
}
}
}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 Send function may return the following errors:
| Error Type | Status Code | Content Type |
|---|---|---|
| sdkerrors.BadRequestResponseError | 400 | application/json |
| sdkerrors.UnauthorizedResponseError | 401 | application/json |
| sdkerrors.PaymentRequiredResponseError | 402 | application/json |
| sdkerrors.NotFoundResponseError | 404 | application/json |
| sdkerrors.RequestTimeoutResponseError | 408 | application/json |
| sdkerrors.PayloadTooLargeResponseError | 413 | application/json |
| sdkerrors.UnprocessableEntityResponseError | 422 | application/json |
| sdkerrors.TooManyRequestsResponseError | 429 | application/json |
| sdkerrors.InternalServerResponseError | 500 | application/json |
| sdkerrors.BadGatewayResponseError | 502 | application/json |
| sdkerrors.ServiceUnavailableResponseError | 503 | application/json |
| sdkerrors.EdgeNetworkTimeoutResponseError | 524 | application/json |
| sdkerrors.ProviderOverloadedResponseError | 529 | application/json |
| sdkerrors.APIError | 4XX, 5XX | */* |
package main
import (
"context"
"errors"
openrouter "github.com/OpenRouterTeam/go-sdk"
"github.com/OpenRouterTeam/go-sdk/models/components"
"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.Beta.Responses.Send(ctx, components.OpenResponsesRequest{})
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.PaymentRequiredResponseError
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.RequestTimeoutResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.PayloadTooLargeResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.UnprocessableEntityResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.TooManyRequestsResponseError
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.BadGatewayResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.ServiceUnavailableResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.EdgeNetworkTimeoutResponseError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.ProviderOverloadedResponseError
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"
"github.com/OpenRouterTeam/go-sdk/models/components"
"log"
"os"
)
func main() {
ctx := context.Background()
s := openrouter.New(
openrouter.WithServer("production"),
openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
)
res, err := s.Beta.Responses.Send(ctx, components.OpenResponsesRequest{})
if err != nil {
log.Fatal(err)
}
if res != nil {
defer res.Object.Close()
for res.Object.Next() {
event := res.Object.Value()
log.Print(event)
// Handle the event
}
}
}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"
"github.com/OpenRouterTeam/go-sdk/models/components"
"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.Beta.Responses.Send(ctx, components.OpenResponsesRequest{})
if err != nil {
log.Fatal(err)
}
if res != nil {
defer res.Object.Close()
for res.Object.Next() {
event := res.Object.Value()
log.Print(event)
// Handle the event
}
}
}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, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
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.