Skip to content

Latest commit

 

History

History
764 lines (578 loc) · 24 KB

File metadata and controls

764 lines (578 loc) · 24 KB

OpenRouter Go SDK

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.

Built by Speakeasy License: Apache 2.0

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.0

Overview

The 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-sdk

See examples/README.md for runnable examples, starting with examples/chat.

Table of Contents

SDK Installation

Add the SDK to your module:

go get github.com/OpenRouterTeam/go-sdk

For beta releases, pin an explicit version:

go get github.com/OpenRouterTeam/go-sdk@v0.5.0

Requirements

This SDK requires Go 1.25 or higher.

SDK Example Usage

Example

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)
	}
}

Authentication

Per-Client Security Schemes

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
	}
}

Per-Operation Security Schemes

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 Resources and Operations

Available methods
  • 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
  • ListZdrEndpoints - Preview the impact of ZDR on the available endpoints
  • List - List all endpoints for a model
  • 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
  • List - List observability destinations
  • Create - Create an observability destination
  • Delete - Delete an observability destination
  • Get - Get an observability destination
  • Update - Update an observability destination
  • List - List all providers
  • Rerank - Submit a rerank request

Server-sent event streaming

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
		}
	}
}

Pagination

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
			}
		}
	}
}

Retries

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
	}
}

Error Handling

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 */*

Example

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())
		}
	}
}

Server Selection

Select Server by Name

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

Example

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
	}
}

Override Server URL Per-Client

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
	}
}

Custom HTTP Client

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.

Development

Maturity

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.

Contributions

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:

SDK Created by Speakeasy