openrouter

package module
v0.7.160 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 18, 2026 License: Apache-2.0 Imports: 20 Imported by: 0

README

hero illustration

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

[!NOTE] This SDK is in beta. Pin to a specific version to avoid unexpected breaking changes:

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

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

To add the SDK as a dependency to your project:

go get github.com/OpenRouterTeam/go-sdk

Requirements

This SDK requires Go 1.25 or higher.

SDK Example Usage

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, nil, nil)
	if err != nil {
		log.Fatal(err)
	}
	if res != nil {
		// handle response
	}
}

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, 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"
	"github.com/OpenRouterTeam/go-sdk/optionalnullable"
	"log"
	"os"
)

func main() {
	ctx := context.Background()

	s := openrouter.New()

	res, err := s.Models.ListForUser(ctx, operations.ListModelsUserSecurity{
		Bearer: os.Getenv("OPENROUTER_BEARER"),
	}, optionalnullable.From(openrouter.Pointer[int64](0)), openrouter.Pointer[int64](500), 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
			}
		}
	}
}

Available Resources and Operations

Available methods
Alpha.Decisions
  • Create - Submit a Decisions (questions and answers) request
Analytics
APIKeys
Benchmarks
Beta.Responses
  • Send - Create a response
BYOK
  • 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
Chat
  • Send - Create a chat completion
Classifications
Containers
Credits
Datasets
Embeddings
Endpoints
  • ListZdrEndpoints - Preview the impact of ZDR on the available endpoints
  • List - List all endpoints for a model
Files
Generations
Guardrails
Images
Interns
Models
  • 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
OAuth
Observability
  • List - List observability destinations
  • Create - Create an observability destination
  • Delete - Delete an observability destination
  • Get - Get an observability destination
  • Update - Update an observability destination
Organization
Presets
Providers
  • List - List all providers
Rerank
  • Rerank - Submit a rerank request
Responses
  • Send - Create a response
Scim
STT
TTS
Vault
VideoGeneration
Workspaces

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.

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.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(openrouter.Pointer[int64](0)), openrouter.Pointer[int64](50), 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/retry"
	"log"
	"models/operations"
	"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, 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, 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, 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, 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, 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

Documentation

Overview

Package openrouter provides an OpenAI-compatible API client with additional OpenRouter features.

The OpenRouter API offers OpenAI-compatible endpoints with additional features like model routing, provider selection, and unified billing.

This SDK is in beta. Pin to a specific module version to avoid unexpected breaking changes:

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

For full API documentation, visit: https://openrouter.ai/docs/client-sdks/go/overview

Authentication:

import (
    "context"

    openrouter "github.com/OpenRouterTeam/go-sdk"
    "github.com/OpenRouterTeam/go-sdk/models/components"
)

sdk := openrouter.New(
    openrouter.WithSecurity("your-api-key"),
)

The API key can also be read from the OPENROUTER_API_KEY environment variable when using New without WithSecurity.

For license information, see the LICENSE file at the repository root.

Examples:

Basic chat completion:

ctx := context.Background()
res, err := sdk.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!"),
            },
        ),
    },
}, nil)
Example

Example demonstrates basic usage of the OpenRouter SDK for chat completions.

package main

import (
	"context"
	"fmt"
	"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()

	sdk := openrouter.New(
		openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
	)

	res, err := sdk.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 && len(res.ChatResult.Choices) > 0 {
		fmt.Printf("Response received with %d choices\n", len(res.ChatResult.Choices))
	}
}
Example (ChatWithMaxTokens)

Example_chatWithMaxTokens demonstrates sending a chat request with max tokens limit.

package main

import (
	"context"
	"fmt"
	"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()
	sdk := openrouter.New(
		openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
	)

	res, err := sdk.Chat.Send(ctx, components.ChatRequest{
		Model: openrouter.Pointer("anthropic/claude-3-sonnet"),
		Messages: []components.ChatMessages{
			components.CreateChatMessagesUser(
				components.ChatUserMessage{
					Role:    components.ChatUserMessageRoleUser,
					Content: components.CreateChatUserMessageContentStr("Say hello"),
				},
			),
		},
		MaxTokens: optionalnullable.From(openrouter.Pointer(int64(100))),
	}, nil)
	if err != nil {
		log.Fatal(err)
	}

	if res != nil && res.ChatResult != nil {
		fmt.Printf("Model used: %s\n", res.ChatResult.Model)
	}
}
Example (GenerateEmbedding)

Example_generateEmbedding demonstrates generating text embeddings.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	openrouter "github.com/OpenRouterTeam/go-sdk"
	"github.com/OpenRouterTeam/go-sdk/models/operations"
)

func main() {
	ctx := context.Background()
	sdk := openrouter.New(
		openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
	)

	res, err := sdk.Embeddings.Generate(ctx, operations.CreateEmbeddingsRequest{
		Model: "openai/text-embedding-ada-002",
		Input: operations.CreateInputUnionStr("The quick brown fox jumps over the lazy dog"),
	}, nil)
	if err != nil {
		log.Fatal(err)
	}

	if res != nil && res.CreateEmbeddingsResponseBody != nil && len(res.CreateEmbeddingsResponseBody.Data) > 0 {
		embedding := res.CreateEmbeddingsResponseBody.Data[0].GetEmbedding()
		if embedding.Type == operations.EmbeddingTypeArrayOfNumber {
			fmt.Printf("Vector dimensions: %d\n", len(embedding.ArrayOfNumber))
		}
	}
}
Example (GetModel)

Example_getModel demonstrates retrieving information about a specific model.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	openrouter "github.com/OpenRouterTeam/go-sdk"
)

func main() {
	ctx := context.Background()
	sdk := openrouter.New(
		openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
	)

	res, err := sdk.Models.Get(ctx, "openai", "gpt-4o")
	if err != nil {
		log.Fatal(err)
	}

	if res != nil {
		fmt.Printf("Model: %s\n", res.Data.Name)
		fmt.Printf("ID: %s\n", res.Data.ID)
	}
}
Example (ListModels)

Example_listModels demonstrates listing available models.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	openrouter "github.com/OpenRouterTeam/go-sdk"
)

func main() {
	ctx := context.Background()
	sdk := openrouter.New(
		openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
	)

	res, err := sdk.Models.List(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}

	if res != nil {
		fmt.Println("Successfully fetched models")
	}
}
Example (ListProviders)

Example_listProviders demonstrates listing available providers.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	openrouter "github.com/OpenRouterTeam/go-sdk"
)

func main() {
	ctx := context.Background()
	sdk := openrouter.New(
		openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
	)

	res, err := sdk.Providers.List(ctx, nil)
	if err != nil {
		log.Fatal(err)
	}

	if res != nil && len(res.Data) > 0 {
		fmt.Printf("Found %d providers\n", len(res.Data))
		for i, provider := range res.Data {
			if i < 3 {
				fmt.Printf("- %s\n", provider.Name)
			}
		}
	}
}
Example (StreamChat)

Example_streamChat demonstrates streaming chat responses.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	openrouter "github.com/OpenRouterTeam/go-sdk"
	"github.com/OpenRouterTeam/go-sdk/models/components"
)

func main() {
	ctx := context.Background()
	sdk := openrouter.New(
		openrouter.WithSecurity(os.Getenv("OPENROUTER_API_KEY")),
	)

	res, err := sdk.Chat.Send(ctx, components.ChatRequest{
		Model: openrouter.Pointer("openai/gpt-4o-mini"),
		Messages: []components.ChatMessages{
			components.CreateChatMessagesUser(
				components.ChatUserMessage{
					Role: components.ChatUserMessageRoleUser,
					Content: components.CreateChatUserMessageContentStr(
						"Count from 1 to 3, one number per line.",
					),
				},
			),
		},
		Stream: openrouter.Pointer(true),
	}, nil)
	if err != nil {
		log.Fatal(err)
	}
	if res == nil || res.EventStream == nil {
		log.Fatal("expected streaming response")
	}

	stream := res.EventStream
	defer stream.Close()

	for stream.Next() {
		chunk := stream.Value()
		if chunk == nil {
			continue
		}
		for _, choice := range chunk.Data.Choices {
			if text, ok := choice.Delta.Content.Get(); ok && text != nil {
				fmt.Print(*text)
			}
		}
	}
	fmt.Println()

	if err := stream.Err(); err != nil {
		log.Fatal(err)
	}
}

Index

Examples

Constants

View Source
const (
	// Production server
	ServerProduction string = "production"
)

Variables

View Source
var ServerList = map[string]string{
	ServerProduction: "https://openrouter.ai/api/v1",
}

ServerList contains the list of servers available to the SDK

Functions

func Bool

func Bool(b bool) *bool

Bool provides a helper function to return a pointer to a bool

func Float32

func Float32(f float32) *float32

Float32 provides a helper function to return a pointer to a float32

func Float64

func Float64(f float64) *float64

Float64 provides a helper function to return a pointer to a float64

func Int

func Int(i int) *int

Int provides a helper function to return a pointer to an int

func Int64

func Int64(i int64) *int64

Int64 provides a helper function to return a pointer to an int64

func Pointer

func Pointer[T any](v T) *T

Pointer provides a helper function to return a pointer to a type

func String

func String(s string) *string

String provides a helper function to return a pointer to a string

Types

type APIKeys

type APIKeys struct {
	// contains filtered or unexported fields
}

APIKeys - API key management endpoints

func (*APIKeys) Create

Create a new API key Create a new API key for the authenticated user. The plaintext `key` is returned only in this response. Treat it as a write-only, sensitive value; it cannot be retrieved later. Authenticate with a [management key](/docs/guides/overview/auth/management-api-keys). The optional `external` object associates the key with a partner-defined user and lookup key.

func (*APIKeys) Delete

func (s *APIKeys) Delete(ctx context.Context, hash string, opts ...operations.Option) (*operations.DeleteKeysResponse, error)

Delete an API key Delete an existing API key. Authenticate with a [management key](/docs/guides/overview/auth/management-api-keys).

func (*APIKeys) Get

func (s *APIKeys) Get(ctx context.Context, hash string, opts ...operations.Option) (*operations.GetKeyResponse, error)

Get a single API key Get a single API key by hash. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*APIKeys) GetCurrentKeyMetadata

func (s *APIKeys) GetCurrentKeyMetadata(ctx context.Context, opts ...operations.Option) (*operations.GetCurrentKeyResponse, error)

GetCurrentKeyMetadata - Get current API key Get information on the API key associated with the current authentication session

func (*APIKeys) List

func (s *APIKeys) List(ctx context.Context, includeDisabled *bool, offset optionalnullable.OptionalNullable[int64], workspaceID *string, opts ...operations.Option) (*operations.ListResponse, error)

List API keys List all API keys for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*APIKeys) Update

Update an API key Update an existing API key. Authenticate with a [management key](/docs/guides/overview/auth/management-api-keys).

type Alpha added in v0.7.158

type Alpha struct {
	// Alpha feature endpoints for Decisions (questions and answers) requests
	Decisions *Decisions
	// contains filtered or unexported fields
}

type Analytics

type Analytics struct {
	// contains filtered or unexported fields
}

Analytics and usage endpoints

func (*Analytics) GetAnalyticsMeta added in v0.7.63

func (s *Analytics) GetAnalyticsMeta(ctx context.Context, opts ...operations.Option) (*operations.GetAnalyticsMetaResponse, error)

GetAnalyticsMeta - Get available analytics metrics and dimensions Returns the available metrics, dimensions, filter operators, and granularities for the analytics query endpoint. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Analytics) GetUserActivity

func (s *Analytics) GetUserActivity(ctx context.Context, date *string, apiKeyHash *string, userID *string, groupBy *operations.GroupBy, workspaceID *string, opts ...operations.Option) (*components.ActivityResponse, error)

GetUserActivity - Get user activity grouped by endpoint Returns user activity data grouped by endpoint for the last 30 (completed) UTC days. Pass `workspace_id` to scope the response to a single workspace. Pass `group_by=workspace` to split each row per workspace and include `workspace_id` on every item; by default rows are aggregated across workspaces and `workspace_id` is not returned. Activity recorded before workspace resolution existed is permanently attributed to the account default workspace (no backfill is possible). [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Analytics) QueryAnalytics added in v0.7.63

QueryAnalytics - Query analytics data Execute an analytics query with specified metrics, dimensions, filters, and time range. [Management key](/docs/guides/overview/auth/management-api-keys) required.

type BYOK added in v0.7.13

type BYOK struct {
	// contains filtered or unexported fields
}

BYOK endpoints

func (*BYOK) Create added in v0.7.13

Create a BYOK provider credential Create a new bring-your-own-key (BYOK) provider credential. The raw key is encrypted at rest and never returned in API responses. When `workspace_id` is omitted, the credential is created in the default workspace; if that default has been deleted, the request returns a 400 and you must pass `workspace_id` explicitly. Treat the raw key as write-only; it is never returned after creation. Use `allowed_api_key_hashes` to restrict the credential to specific OpenRouter API keys. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*BYOK) Delete added in v0.7.13

Delete a BYOK provider credential Delete (soft-delete) a bring-your-own-key (BYOK) provider credential by its `id`. The encrypted key material is wiped and the record is marked as deleted. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*BYOK) Get added in v0.7.13

Get a BYOK provider credential Get a single bring-your-own-key (BYOK) provider credential by its `id`. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*BYOK) List added in v0.7.13

func (s *BYOK) List(ctx context.Context, offset optionalnullable.OptionalNullable[int64], limit *int64, workspaceID *string, provider *operations.Provider, opts ...operations.Option) (*operations.ListBYOKKeysResponse, error)

List BYOK provider credentials List the bring-your-own-key (BYOK) provider credentials for the authenticated entity's default workspace. Use the `workspace_id` query parameter to scope the result to a different workspace, or the `provider` query parameter to filter by upstream provider. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*BYOK) Update added in v0.7.13

func (s *BYOK) Update(ctx context.Context, id string, updateBYOKKeyRequest components.UpdateBYOKKeyRequest, opts ...operations.Option) (*components.UpdateBYOKKeyResponse, error)

Update a BYOK provider credential Update an existing bring-your-own-key (BYOK) provider credential by its `id`. Include the `key` field to rotate the raw provider API key in-place (the previous key material is overwritten). Use `allowed_api_key_hashes` to restrict the credential to specific OpenRouter API keys (`null` clears the restriction). [Management key](/docs/guides/overview/auth/management-api-keys) required.

type Benchmarks

type Benchmarks struct {
	// contains filtered or unexported fields
}

Benchmarks endpoints

func (*Benchmarks) GetBenchmarks

GetBenchmarks - List Benchmarks Unified benchmark endpoint that aggregates scores from multiple benchmark sources (Artificial Analysis, Design Arena, and OpenRouter's own tau-bench, GPQA, and web-search evals). Filter by source to reproduce the exact shapes from the legacy per-source endpoints, or use task_type to find models suited for specific workloads. Use task_type=search (or a search_* benchmark_type) for OpenRouter's search benchmarks, which publish each model's highest-scoring eligible evaluation configuration with same-configuration runs combined by task-weighted mean. Authenticate with any valid OpenRouter API key. Rate-limited to 30 requests/minute per key and 500 requests/day per account.

type Beta

type Beta struct {
	// Deprecated alias of responses. Use responses instead; scheduled for removal (sunset date TBD).
	Responses *BetaResponses
	// contains filtered or unexported fields
}

type BetaResponses added in v0.6.0

type BetaResponses struct {
	// contains filtered or unexported fields
}

BetaResponses - Deprecated alias of responses. Use responses instead; scheduled for removal (sunset date TBD).

func (*BetaResponses) Send added in v0.6.0

Send - Create a response Creates a streaming or non-streaming response using OpenResponses API format

type Chat

type Chat struct {
	// contains filtered or unexported fields
}

Chat - Stream a chat completion with an intern Sends a prompt to one of your interns and streams the reply as OpenAI-compatible server-sent events ending with `[DONE]`. The run executes on the intern, which may pause to ask you something. It then streams one `openrouter.provide_input` tool call and finishes with `finish_reason: "tool_calls"`, and the run stays open on the intern.

Every response, whether it ends with `stop`, `tool_calls` or `error`, is followed by a final chunk with empty `choices` that carries `session_id`, then `data: [DONE]`. That chunk carries the `usage` the intern reported for the run, after `stop` or `error`, and `null` when the intern reported none. After `tool_calls` its `usage` is `null` because the turn is not over. Read through `[DONE]`: the `session_id` you need to reply arrives after the `tool_calls` finish chunk.

To answer, send a second request with the same `session_id`, the assistant message echoing that tool call, and a `tool` message whose `tool_call_id` is the tool call id and whose `content` is the answer. The answer is delivered to the run that asked and the stream continues from where it paused. A question stays open for its interaction deadline (5 minutes by default) and the run is cancelled when that passes. Rejected replies do not extend the deadline.

Closing the connection after the `[DONE]` that follows `finish_reason: "tool_calls"` keeps the run alive. Disconnecting while a response is still streaming cancels the run. The disconnect is noticed when the intern next writes to the stream, which during a silent tool run can take more than one 30 second heartbeat interval.

A run the intern ends while you are still connected, by cancellation or by a deadline, ends the stream with a `finish_reason: "error"` chunk carrying `410` and reason `run_ended`, then the final empty-`choices` chunk and `[DONE]`. That error reports only an ending the intern confirmed. A connection that breaks without that confirmation ends with reason `stream_severed`, and a client that has already disconnected is promised no final event.

Set `approval_mode` to `manual` to have the intern ask before approval-bearing tools such as the shell. Omitted, the run self-drives and consents on your behalf. The mode belongs to the run started by that prompt and must be repeated on later prompts.

Available to interns programme members. Callers outside the programme receive `404` for every path under `/api/v1/interns`.

func (*Chat) Send

Send - Create a chat completion Sends a request for a model response for the given chat conversation. Supports both streaming and non-streaming modes.

type Classifications

type Classifications struct {
	// contains filtered or unexported fields
}

Classifications - Task classification market-share endpoints

func (*Classifications) GetTaskClassifications

func (s *Classifications) GetTaskClassifications(ctx context.Context, window *operations.Window, opts ...operations.Option) (*components.TaskClassificationResponse, error)

GetTaskClassifications - Task classification market share Returns the market-share breakdown of OpenRouter traffic by task classification (e.g. code generation, web search, summarization) over a trailing time window.

Each classification reports its share of classified sampled requests (`usage_share`) and classified sampled token volume (`token_share`) as fractions between 0 and 1. The unclassified `other` bucket is excluded. Absolute volumes are not exposed because the underlying data is sampled.

Each classification also includes a `models` array listing the top models by request volume within that classification, with their within-tag usage and token shares.

Classifications are grouped into macro-categories (Code, Data, Agent, General) with aggregate shares provided for each.

Authenticate with any valid OpenRouter API key (same key used for inference). Rate-limited to 30 requests/minute per key and 500 requests/day per account.

When republishing or quoting this data, cite as: "Source: OpenRouter (openrouter.ai/rankings), as of {as_of}."

type Containers added in v0.7.68

type Containers struct {
	// contains filtered or unexported fields
}

Containers endpoints

func (*Containers) DownloadContainerFileContent added in v0.7.68

func (s *Containers) DownloadContainerFileContent(ctx context.Context, containerID string, fileID string, opts ...operations.Option) (io.ReadCloser, error)

DownloadContainerFileContent - Download container file content Streams the raw bytes of a file in a container.

func (*Containers) GetContainerFile added in v0.7.68

func (s *Containers) GetContainerFile(ctx context.Context, containerID string, fileID string, opts ...operations.Option) (*components.ContainerFile, error)

GetContainerFile - Retrieve a container file Returns the metadata of a single file in a container.

func (*Containers) ListContainerFiles added in v0.7.68

func (s *Containers) ListContainerFiles(ctx context.Context, containerID string, limit *int64, after *string, opts ...operations.Option) (*components.ContainerFileListResponse, error)

ListContainerFiles - List container files Lists the files in a container, in lexicographic path order. The container id is the canonical id returned in bash/shell tool results; a restarted session is a separate container with its own id. Paginate with `limit` and `after` (pass the previous page’s `last_id`); `has_more: true` always means the next page is fetchable that way. `last_id` is the resume cursor: it is the last listed file’s id, except when a page ends at the per-request scan bound on hidden bookkeeping objects, where it names the scan position instead and may not appear in `data` (which can then be empty).

func (*Containers) PromoteContainerFile added in v0.7.78

func (s *Containers) PromoteContainerFile(ctx context.Context, containerID string, fileID string, opts ...operations.Option) (*components.FileResponse, error)

PromoteContainerFile - Promote a container file into workspace documents Copies a file from the container's sandbox prefix into the workspace's durable document storage, so it outlives the container. Returns the new document in the Files API shape, with a durable file id in the documents namespace. The copy counts against the workspace's storage quota. Unlike a direct upload, promoted files are downloadable.

type Credits

type Credits struct {
	// contains filtered or unexported fields
}

Credits - Credit management endpoints

func (*Credits) GetCredits

func (s *Credits) GetCredits(ctx context.Context, opts ...operations.Option) (*operations.GetCreditsResponse, error)

GetCredits - Get remaining credits Get total credits purchased and used for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.

type Datasets

type Datasets struct {
	// contains filtered or unexported fields
}

Datasets - Public OpenRouter usage datasets. Data returned by these endpoints is licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/): reuse and republish it, including commercially, with attribution to OpenRouter.

func (*Datasets) GetAppRankings

GetAppRankings - Top apps by token usage Returns the top public apps on OpenRouter ranked by token usage inside the requested date window, matching the public apps marketplace on openrouter.ai/apps. Token totals are `prompt_tokens + completion_tokens`; hidden and private apps are excluded and traffic from related app aliases is merged into the canonical visible app.

`sort=popular` (default) ranks by total token volume inside the window. `sort=trending` ranks by absolute excess token growth: window volume minus the average volume of the three equal-length periods immediately preceding the window. Apps with no excess growth are omitted, so `trending` may return fewer than `limit` rows.

Filter with `category` (marketplace category group, e.g. `coding`) or `subcategory` (e.g. `cli-agent`). Ranks are re-numbered 1..N after filtering. Page with `offset` — `rank` stays absolute, so the first row of `offset=50` is `rank: 51`.

Authenticate with any valid OpenRouter API key (same key used for inference). Rate-limited to 30 requests/minute per key and 500 requests/day per account.

When republishing or quoting this dataset, OpenRouter must be cited as: "Source: OpenRouter (openrouter.ai/apps), as of {as_of}."

Token counts come from each upstream provider's own tokenizer, so a token attributed to one app is not directly comparable to a token attributed to another app whose traffic flows through a different provider.

Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/): reuse and republish with attribution to OpenRouter.

func (*Datasets) GetRankingsDaily

GetRankingsDaily - Daily token totals for top 50 models Returns the top 50 public models per day by total token usage on OpenRouter, plus a single aggregated `other` row per day that sums every model outside that top 50. Token totals are `prompt_tokens + completion_tokens`, matching the public rankings chart on openrouter.ai/rankings.

Each row is a distinct `(date, model_permaslug)` pair. The `other` row uses the reserved permaslug `other` and is always returned last within its date, so callers can compute `top-50 traffic / total daily traffic` without a second request.

Optional filters slice the dataset. `period` (`day`/`week`/`month`) sets the time grain. `modality` and `context_bucket` narrow the exact dataset by output/input modality (or tool-calling activity) and request context length. `category` and `language_type` instead read a sampled, upsampled dataset whose `total_tokens` are weekly-grain estimates — they cannot be combined with each other or with the exact filters, and reject `period=day` with a 400.

Authenticate with any valid OpenRouter API key (same key used for inference). Rate-limited to 30 requests/minute per key and 500 requests/day per account.

When republishing or quoting this dataset, OpenRouter must be cited as: "Source: OpenRouter (openrouter.ai/rankings), as of {as_of}."

Token counts come from each upstream provider's own tokenizer (Anthropic counts are as reported by Anthropic, OpenAI counts are as reported by OpenAI, etc.), so a token in one row is not directly comparable to a token in another row from a different provider.

Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/): reuse and republish with attribution to OpenRouter.

func (*Datasets) GetSessionCost added in v0.7.44

GetSessionCost - Cost per session by harness and model Returns weekly refreshed, aggregated cost-per-session cells for the published harnesses. Sessions are never pooled across apps. Medians are of per-session USD spend, and privacy-preserving aggregation never exposes clerk_user_id values or per-session rows.

Filter by `app_slug`, `model`, or `turn_range`. Filtering by `model` alone works across apps for harness-vs-harness comparison at a fixed model. Results refresh weekly and include the source snapshot window in `meta`.

Licensed under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/): reuse and republish with attribution to OpenRouter.

type Decisions added in v0.7.153

type Decisions struct {
	// contains filtered or unexported fields
}

Decisions - Alpha feature endpoints for Decisions (questions and answers) requests

func (*Decisions) Create added in v0.7.154

Create - Submit a Decisions (questions and answers) request Submits a Decisions request to the Decisions router

type Embeddings

type Embeddings struct {
	// contains filtered or unexported fields
}

Embeddings - Text embedding endpoints

func (*Embeddings) Generate

Generate - Submit an embedding request Submits an embedding request to the embeddings router

func (*Embeddings) ListModels

ListModels - List all embeddings models Returns a list of all available embeddings models and their properties

type Endpoints

type Endpoints struct {
	// contains filtered or unexported fields
}

Endpoints - Endpoint information

func (*Endpoints) List

func (s *Endpoints) List(ctx context.Context, author string, slug string, opts ...operations.Option) (*operations.ListEndpointsResponse, error)

List all endpoints for a model

func (*Endpoints) ListZdrEndpoints

func (s *Endpoints) ListZdrEndpoints(ctx context.Context, opts ...operations.Option) (*operations.ListEndpointsZdrResponse, error)

ListZdrEndpoints - Preview the impact of ZDR on the available endpoints

type Files

type Files struct {
	// contains filtered or unexported fields
}

Files endpoints

func (*Files) Delete

func (s *Files) Delete(ctx context.Context, fileID string, workspaceID *string, provider *components.FileProvider, opts ...operations.Option) (*components.FileDeleteResponse, error)

Delete a file Deletes a file owned by the requesting workspace. Deletion is irreversible.

func (*Files) Download

func (s *Files) Download(ctx context.Context, fileID string, workspaceID *string, provider *components.FileProvider, opts ...operations.Option) (io.ReadCloser, error)

Download file content Downloads the raw bytes of a file. Only files created server-side are downloadable; uploaded files return 400.

func (*Files) List

List files Lists files belonging to the workspace of the authenticating API key.

func (*Files) Retrieve

func (s *Files) Retrieve(ctx context.Context, fileID string, workspaceID *string, provider *components.FileProvider, opts ...operations.Option) (*components.FileResponse, error)

Retrieve - Get file metadata Retrieves metadata for a single file owned by the requesting workspace.

func (*Files) Upload

func (s *Files) Upload(ctx context.Context, requestBody operations.UploadFileRequestBody, workspaceID *string, provider *components.FileProvider, opts ...operations.Option) (*components.FileResponse, error)

Upload a file Uploads a file to be referenced in future API calls. The file is stored under the workspace of the authenticating API key. Maximum file size: 100 MB; empty files are rejected. The file type is determined from the file contents — not the filename or the declared content type — and must be a PDF, a PNG/JPEG/GIF/WebP image, a DOCX/XLSX/PPTX document, an MP3/WAV/FLAC/OGG audio file, or UTF-8 text. Text is reported by its structure as `application/json`, `application/x-ndjson`, `text/csv`, `text/markdown`, or `text/plain`.

type Generations

type Generations struct {
	// contains filtered or unexported fields
}

Generations - Generation history endpoints

func (*Generations) GetGeneration

func (s *Generations) GetGeneration(ctx context.Context, id string, opts ...operations.Option) (*components.GenerationResponse, error)

GetGeneration - Get request & usage metadata for a generation

func (*Generations) ListGenerationContent

func (s *Generations) ListGenerationContent(ctx context.Context, id string, opts ...operations.Option) (*components.GenerationContentResponse, error)

ListGenerationContent - Get stored prompt, completion, and error content for a generation

func (*Generations) SubmitFeedback added in v0.5.13

SubmitFeedback - Submit feedback for a generation Submit structured feedback on a generation the authenticated user made. [Management key](/docs/guides/overview/auth/management-api-keys) required.

type Guardrails

type Guardrails struct {
	// contains filtered or unexported fields
}

Guardrails endpoints

func (*Guardrails) BulkAssignKeys

func (s *Guardrails) BulkAssignKeys(ctx context.Context, id string, bulkAssignKeysRequest components.BulkAssignKeysRequest, opts ...operations.Option) (*components.BulkAssignKeysResponse, error)

BulkAssignKeys - Bulk assign keys to a guardrail Assign multiple API keys to a specific guardrail. A key may hold at most one guardrail; assigning replaces any existing assignment. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) BulkAssignMembers

func (s *Guardrails) BulkAssignMembers(ctx context.Context, id string, bulkAssignMembersRequest components.BulkAssignMembersRequest, opts ...operations.Option) (*components.BulkAssignMembersResponse, error)

BulkAssignMembers - Bulk assign members to a guardrail Assign multiple organization members to a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) BulkUnassignKeys

func (s *Guardrails) BulkUnassignKeys(ctx context.Context, id string, bulkUnassignKeysRequest components.BulkUnassignKeysRequest, opts ...operations.Option) (*components.BulkUnassignKeysResponse, error)

BulkUnassignKeys - Bulk unassign keys from a guardrail Unassign multiple API keys from a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) BulkUnassignMembers

func (s *Guardrails) BulkUnassignMembers(ctx context.Context, id string, bulkUnassignMembersRequest components.BulkUnassignMembersRequest, opts ...operations.Option) (*components.BulkUnassignMembersResponse, error)

BulkUnassignMembers - Bulk unassign members from a guardrail Unassign multiple organization members from a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) Create

Create a guardrail Create a new guardrail for the authenticated user. A newly created guardrail enforces nothing until it is assigned to API keys or organization members; `workspace_id` places the guardrail in a workspace but does not apply it to that workspace's traffic. To restrict all traffic in a workspace, update the workspace's default guardrail instead. Set `allowed_data_regions` to enforce [In-Region Routing](/docs/guides/features/in-region-routing#enforcing-in-region-routing-with-guardrails): governed requests must arrive through one of the listed OpenRouter domains and are rejected with a 403 otherwise. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) Delete

Delete a guardrail Delete an existing guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) Get

Get a guardrail Get a single guardrail by ID. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) List

List guardrails List all guardrails for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) ListGuardrailKeyAssignments

ListGuardrailKeyAssignments - List key assignments for a guardrail List all API key assignments for a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) ListGuardrailMemberAssignments

func (s *Guardrails) ListGuardrailMemberAssignments(ctx context.Context, id string, offset optionalnullable.OptionalNullable[int64], limit *int64, opts ...operations.Option) (*operations.ListGuardrailMemberAssignmentsResponse, error)

ListGuardrailMemberAssignments - List member assignments for a guardrail List all organization member assignments for a specific guardrail. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) ListKeyAssignments

ListKeyAssignments - List all key assignments List all API key guardrail assignments for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) ListMemberAssignments

ListMemberAssignments - List all member assignments List all organization member guardrail assignments for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Guardrails) Update

Update a guardrail Update an existing guardrail, or materialize an unconfigured workspace default guardrail. Collection fields use replace semantics: send the full desired set on every update. [Management key](/docs/guides/overview/auth/management-api-keys) required.

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient provides an interface for supplying the SDK with a custom HTTP client

type Images

type Images struct {
	// contains filtered or unexported fields
}

Images endpoints

func (*Images) Generate

Generate an image Generates an image from a text prompt via the image generation router

func (*Images) ListModelEndpoints

func (s *Images) ListModelEndpoints(ctx context.Context, author string, slug string, opts ...operations.Option) (*components.ImageModelEndpointsResponse, error)

ListModelEndpoints - List endpoints for an image model Returns the full per-endpoint records for an image model: each endpoint's definitive supported parameters, pricing, and passthrough allowlist.

func (*Images) ListModels

ListModels - List image generation models Lists every image generation model with its top-level supported-parameter superset and a URL to its full per-endpoint records.

type Interns added in v0.7.148

type Interns struct {
	// contains filtered or unexported fields
}

Interns - Create, inspect, update, provision, suspend and delete OpenRouter interns through an API key, and talk to them: the chat route streams OpenAI-compatible completions from one intern, pausing as an `openrouter.provide_input` tool call when the intern needs your permission or an answer. Available to interns programme members; other callers receive 404. See https://openrouter.ai/docs/guides/ori/intern-chat.

func (*Interns) Chat added in v0.7.150

Chat - Stream a chat completion with an intern Sends a prompt to one of your interns and streams the reply as OpenAI-compatible server-sent events ending with `[DONE]`. The run executes on the intern, which may pause to ask you something. It then streams one `openrouter.provide_input` tool call and finishes with `finish_reason: "tool_calls"`, and the run stays open on the intern.

Every response, whether it ends with `stop`, `tool_calls` or `error`, is followed by a final chunk with empty `choices` that carries `session_id`, then `data: [DONE]`. That chunk carries the `usage` the intern reported for the run, after `stop` or `error`, and `null` when the intern reported none. After `tool_calls` its `usage` is `null` because the turn is not over. Read through `[DONE]`: the `session_id` you need to reply arrives after the `tool_calls` finish chunk.

To answer, send a second request with the same `session_id`, the assistant message echoing that tool call, and a `tool` message whose `tool_call_id` is the tool call id and whose `content` is the answer. The answer is delivered to the run that asked and the stream continues from where it paused. A question stays open for its interaction deadline (5 minutes by default) and the run is cancelled when that passes. Rejected replies do not extend the deadline.

Closing the connection after the `[DONE]` that follows `finish_reason: "tool_calls"` keeps the run alive. Disconnecting while a response is still streaming cancels the run. The disconnect is noticed when the intern next writes to the stream, which during a silent tool run can take more than one 30 second heartbeat interval.

A run the intern ends while you are still connected, by cancellation or by a deadline, ends the stream with a `finish_reason: "error"` chunk carrying `410` and reason `run_ended`, then the final empty-`choices` chunk and `[DONE]`. That error reports only an ending the intern confirmed. A connection that breaks without that confirmation ends with reason `stream_severed`, and a client that has already disconnected is promised no final event.

Set `approval_mode` to `manual` to have the intern ask before approval-bearing tools such as the shell. Omitted, the run self-drives and consents on your behalf. The mode belongs to the run started by that prompt and must be repeated on later prompts.

Available to interns programme members. Callers outside the programme receive `404` for every path under `/api/v1/interns`.

If set, this operation will use [Security.APIKey] from the global security.

func (*Interns) CreateIntern added in v0.7.148

func (s *Interns) CreateIntern(ctx context.Context, createInternRequest components.CreateInternRequest, idempotencyKey *string, opts ...operations.Option) (*components.Intern, error)

CreateIntern - Create an intern Creates an intern in an explicit workspace. The operation also creates its private vault. It can start provisioning immediately or wait for a later provision call. A retry with the same idempotency key and body resumes unfinished work. The request body is capped at 1048576 bytes and a larger body is refused with 413. The API key selects the caller, workspace and visible interns. There is no default workspace fallback. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Interns) DeleteIntern added in v0.7.148

func (s *Interns) DeleteIntern(ctx context.Context, internID string, opts ...operations.Option) (*components.DeleteInternResponse, error)

DeleteIntern - Delete an intern Starts safe teardown of the intern, its runtime and its private vault. The API key selects the caller, workspace and visible interns. There is no default workspace fallback. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Interns) GetIntern added in v0.7.148

func (s *Interns) GetIntern(ctx context.Context, internID string, opts ...operations.Option) (*components.Intern, error)

GetIntern - Get an intern Returns the public lifecycle state and settings for one visible intern. The API key selects the caller, workspace and visible interns. There is no default workspace fallback. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Interns) ListInterns added in v0.7.148

func (s *Interns) ListInterns(ctx context.Context, limit *int64, status []operations.Status, workspaceID *string, opts ...operations.Option) (*components.InternListResponse, error)

ListInterns - List interns Lists interns visible to the authenticated key, newest first. Filter by workspace and one or more lifecycle statuses. The API key selects the caller, workspace and visible interns. There is no default workspace fallback. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Interns) ProvisionIntern added in v0.7.148

func (s *Interns) ProvisionIntern(ctx context.Context, internID string, opts ...operations.Option) (*components.ProvisionInternResponse, error)

ProvisionIntern - Provision an intern Starts the first boot, or resumes an intern after suspension. The API key selects the caller, workspace and visible interns. There is no default workspace fallback. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Interns) SuspendIntern added in v0.7.148

func (s *Interns) SuspendIntern(ctx context.Context, internID string, opts ...operations.Option) (*components.SuspendInternResponse, error)

SuspendIntern - Suspend an intern Stops the intern runtime while keeping its disk and configuration for a later provision call. The API key selects the caller, workspace and visible interns. There is no default workspace fallback. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Interns) UpdateIntern added in v0.7.148

func (s *Interns) UpdateIntern(ctx context.Context, internID string, updateInternRequest components.UpdateInternRequest, opts ...operations.Option) (*components.Intern, error)

UpdateIntern - Update an intern Changes the intern name, description, instructions or model. Omitted fields stay unchanged. The request body is capped at 1048576 bytes and a larger body is refused with 413. The API key selects the caller, workspace and visible interns. There is no default workspace fallback. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

type Models

type Models struct {
	// contains filtered or unexported fields
}

Models - Model information endpoints

func (*Models) Count

func (s *Models) Count(ctx context.Context, outputModalities *string, opts ...operations.Option) (*components.ModelsCountResponse, error)

Count - Get total count of available models

func (*Models) Get

func (s *Models) Get(ctx context.Context, author string, slug string, opts ...operations.Option) (*components.ModelResponse, error)

Get a model by its slug Returns full details for a single model identified by its author and slug (e.g. openai/gpt-4). Supports variant suffixes (e.g. openai/gpt-4:free) and resolves known slug aliases.

func (*Models) List

List all models and their properties

func (*Models) ListForUser

func (s *Models) ListForUser(ctx context.Context, security operations.ListModelsUserSecurity, offset optionalnullable.OptionalNullable[int64], limit *int64, outputModalities *string, opts ...operations.Option) (*operations.ListModelsUserResponse, error)

ListForUser - List models filtered by user provider preferences, privacy settings, and guardrails List models filtered by user provider preferences, [privacy settings](https://openrouter.ai/docs/guides/privacy/provider-logging), and [guardrails](https://openrouter.ai/docs/guides/features/guardrails). Returns text-output models by default; pass `output_modalities` (a comma-separated list of `text`, `image`, `embeddings`, `audio`, `video`, `rerank`, `speech`, `transcription`, or `all`) to include other modalities. If requesting through a regional hostname, the results will be filtered to models that satisfy in-region routing for that region.

type OAuth

type OAuth struct {
	// contains filtered or unexported fields
}

OAuth authentication endpoints

func (*OAuth) CreateAuthCode

CreateAuthCode - Create authorization code Create an authorization code for the PKCE flow to generate a user-controlled API key

func (*OAuth) CreateOauthToken added in v0.7.112

CreateOauthToken - Exchange a workload identity token RFC 8693 token exchange. Presents a JWT from an issuer your organization trusts (Settings → Workload identity) and receives a short-lived OpenRouter access token that acts as the API key the matching federation policy targets.

func (*OAuth) ExchangeAuthCodeForAPIKey

ExchangeAuthCodeForAPIKey - Exchange authorization code for API key Exchange an authorization code from the PKCE flow for a user-controlled API key

func (*OAuth) ListOauthJwks added in v0.7.112

func (s *OAuth) ListOauthJwks(ctx context.Context, opts ...operations.Option) (*components.OAuthJwks, error)

ListOauthJwks - OpenRouter access token signing keys RFC 7517 JWK Set containing the public keys OpenRouter signs access tokens with.

type Observability

type Observability struct {
	// contains filtered or unexported fields
}

Observability endpoints

func (*Observability) Create

Create an observability destination Create a new observability destination. A maximum of 5 destinations per type is allowed. Defaults to the authenticated entity's default workspace; use the `workspace_id` body field to scope to a different workspace. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Observability) Delete

Delete an observability destination Delete an existing observability destination. This performs a soft delete. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Observability) Get

Get an observability destination Fetch a single observability destination by its UUID. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Observability) List

List observability destinations List the observability destinations configured for the authenticated entity's default workspace. Use the `workspace_id` query parameter to scope the result to a different workspace. Only destinations with stable release status are surfaced — destinations of other types are excluded. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Observability) Update

Update an observability destination Update an existing observability destination. Only the fields provided in the request body are updated. [Management key](/docs/guides/overview/auth/management-api-keys) required.

type OpenRouter

type OpenRouter struct {
	SDKVersion string
	// Analytics and usage endpoints
	Analytics *Analytics
	Alpha     *Alpha
	// Text-to-speech endpoints
	TTS *TTS
	// Speech-to-text endpoints
	STT *STT
	// OAuth authentication endpoints
	OAuth *OAuth
	// Benchmarks endpoints
	Benchmarks *Benchmarks
	// BYOK endpoints
	BYOK *BYOK
	// Stream a chat completion with an intern
	// Sends a prompt to one of your interns and streams the reply as OpenAI-compatible server-sent events ending with `[DONE]`. The run executes on the intern, which may pause to ask you something. It then streams one `openrouter.provide_input` tool call and finishes with `finish_reason: "tool_calls"`, and the run stays open on the intern.
	//
	// Every response, whether it ends with `stop`, `tool_calls` or `error`, is followed by a final chunk with empty `choices` that carries `session_id`, then `data: [DONE]`. That chunk carries the `usage` the intern reported for the run, after `stop` or `error`, and `null` when the intern reported none. After `tool_calls` its `usage` is `null` because the turn is not over. Read through `[DONE]`: the `session_id` you need to reply arrives after the `tool_calls` finish chunk.
	//
	// To answer, send a second request with the same `session_id`, the assistant message echoing that tool call, and a `tool` message whose `tool_call_id` is the tool call id and whose `content` is the answer. The answer is delivered to the run that asked and the stream continues from where it paused. A question stays open for its interaction deadline (5 minutes by default) and the run is cancelled when that passes. Rejected replies do not extend the deadline.
	//
	// Closing the connection after the `[DONE]` that follows `finish_reason: "tool_calls"` keeps the run alive. Disconnecting while a response is still streaming cancels the run. The disconnect is noticed when the intern next writes to the stream, which during a silent tool run can take more than one 30 second heartbeat interval.
	//
	// A run the intern ends while you are still connected, by cancellation or by a deadline, ends the stream with a `finish_reason: "error"` chunk carrying `410` and reason `run_ended`, then the final empty-`choices` chunk and `[DONE]`. That error reports only an ending the intern confirmed. A connection that breaks without that confirmation ends with reason `stream_severed`, and a client that has already disconnected is promised no final event.
	//
	// Set `approval_mode` to `manual` to have the intern ask before approval-bearing tools such as the shell. Omitted, the run self-drives and consents on your behalf. The mode belongs to the run started by that prompt and must be repeated on later prompts.
	//
	// Available to interns programme members. Callers outside the programme receive `404` for every path under `/api/v1/interns`.
	Chat *Chat
	// Task classification market-share endpoints
	Classifications *Classifications
	// Containers endpoints
	Containers *Containers
	// Credit management endpoints
	Credits *Credits
	// Public OpenRouter usage datasets. Data returned by these endpoints is licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/): reuse and republish it, including commercially, with attribution to OpenRouter.
	Datasets *Datasets
	// Text embedding endpoints
	Embeddings *Embeddings
	// Endpoint information
	Endpoints *Endpoints
	// Files endpoints
	Files *Files
	// Generation history endpoints
	Generations *Generations
	// Guardrails endpoints
	Guardrails *Guardrails
	// Images endpoints
	Images *Images
	// Create, inspect, update, provision, suspend and delete OpenRouter interns through an API key, and talk to them: the chat route streams OpenAI-compatible completions from one intern, pausing as an `openrouter.provide_input` tool call when the intern needs your permission or an answer. Available to interns programme members; other callers receive 404. See https://openrouter.ai/docs/guides/ori/intern-chat.
	Interns *Interns
	// API key management endpoints
	APIKeys *APIKeys
	// Model information endpoints
	Models *Models
	// Observability endpoints
	Observability *Observability
	// Organization endpoints
	Organization *Organization
	// Presets endpoints
	Presets *Presets
	// Provider information endpoints
	Providers *Providers
	// Rerank endpoints
	Rerank *Rerank
	// OpenAI-compatible Responses API endpoints
	Responses *Responses
	Beta      *Beta
	// Management endpoints for SCIM group-to-workspace mappings, authenticated with a management key. These are not the SCIM 2.0 connector endpoints for your identity provider. In your identity provider, enter the SCIM endpoint URL shown when you enable provisioning under Settings > Members > SCIM Mappings. See https://openrouter.ai/docs/guides/features/scim-mappings#set-up-provisioning.
	Scim *Scim
	// Store host-bound secrets for a workspace or for one intern. Scope is selected by the API key. Responses return metadata only, never secret values. See https://openrouter.ai/docs/guides/ori/vault.
	Vault *Vault
	// Video Generation endpoints
	VideoGeneration *VideoGeneration
	// Workspaces endpoints
	Workspaces *Workspaces
	// contains filtered or unexported fields
}

OpenRouter API: OpenAI-compatible API with additional OpenRouter features

https://openrouter.ai/docs - OpenRouter Documentation

func New

func New(opts ...SDKOption) *OpenRouter

New creates a new instance of the SDK with the provided options

Example

ExampleNew demonstrates creating a new OpenRouter client.

package main

import (
	"fmt"

	openrouter "github.com/OpenRouterTeam/go-sdk"
)

func main() {
	sdk := openrouter.New(
		openrouter.WithSecurity("your-api-key"),
	)
	fmt.Println(sdk.SDKVersion)
}
Output:
0.7.160

type Organization

type Organization struct {
	// contains filtered or unexported fields
}

Organization endpoints

func (*Organization) ListMembers

ListMembers - List organization members List all members of the organization associated with the authenticated management key. [Management key](/docs/guides/overview/auth/management-api-keys) required.

type Presets

type Presets struct {
	// contains filtered or unexported fields
}

Presets endpoints

func (*Presets) CreatePresetsChatCompletions

func (s *Presets) CreatePresetsChatCompletions(ctx context.Context, slug string, chatRequest components.ChatRequest, opts ...operations.Option) (*components.CreatePresetFromInferenceResponse, error)

CreatePresetsChatCompletions - Create a preset from a chat-completions request body Creates a preset (or a new version of an existing one) from an inference request body. Only fields that overlap with the preset config are persisted; other fields (e.g. `messages`, `stream`, `prompt`) are silently ignored.

If set, this operation will use [Security.APIKey] from the global security.

func (*Presets) CreatePresetsMessages

func (s *Presets) CreatePresetsMessages(ctx context.Context, slug string, messagesRequest components.MessagesRequest, opts ...operations.Option) (*components.CreatePresetFromInferenceResponse, error)

CreatePresetsMessages - Create a preset from a messages request body Creates a preset (or a new version of an existing one) from an inference request body. Only fields that overlap with the preset config are persisted; other fields (e.g. `messages`, `stream`, `prompt`) are silently ignored.

If set, this operation will use [Security.APIKey] from the global security.

func (*Presets) CreatePresetsResponses

func (s *Presets) CreatePresetsResponses(ctx context.Context, slug string, responsesRequest components.ResponsesRequest, opts ...operations.Option) (*components.CreatePresetFromInferenceResponse, error)

CreatePresetsResponses - Create a preset from a responses request body Creates a preset (or a new version of an existing one) from an inference request body. Only fields that overlap with the preset config are persisted; other fields (e.g. `messages`, `stream`, `prompt`) are silently ignored.

If set, this operation will use [Security.APIKey] from the global security.

func (*Presets) Get

Get a preset Retrieves a preset by its slug with its currently designated version inline.

If set, this operation will use [Security.APIKey] from the global security.

func (*Presets) GetVersion

func (s *Presets) GetVersion(ctx context.Context, slug string, version string, opts ...operations.Option) (*components.GetPresetVersionResponse, error)

GetVersion - Get a specific version of a preset Retrieves a specific version of a preset by its slug and version number.

If set, this operation will use [Security.APIKey] from the global security.

func (*Presets) List

List presets Lists all presets for the authenticated user, ordered by most recently updated first.

If set, this operation will use [Security.APIKey] from the global security.

func (*Presets) ListVersions

ListVersions - List versions of a preset Lists all versions of a preset, ordered by version number ascending (oldest first).

If set, this operation will use [Security.APIKey] from the global security.

type Providers

type Providers struct {
	// contains filtered or unexported fields
}

Providers - Provider information endpoints

func (*Providers) List

List all providers

type Rerank

type Rerank struct {
	// contains filtered or unexported fields
}

Rerank endpoints

func (*Rerank) Rerank

Rerank - Submit a rerank request Submits a rerank request to the rerank router

type Responses

type Responses struct {
	// contains filtered or unexported fields
}

OpenAI-compatible Responses API endpoints

func (*Responses) Send

func (s *Responses) Send(ctx context.Context, responsesRequest components.ResponsesRequest, xOpenRouterMetadata *components.MetadataLevel, opts ...operations.Option) (*operations.CreateResponsesResponse, error)

Send - Create a response Creates a streaming or non-streaming response using OpenResponses API format

type SDKOption

type SDKOption func(*OpenRouter)

func WithClient

func WithClient(client HTTPClient) SDKOption

WithClient allows the overriding of the default HTTP client used by the SDK

func WithHTTPReferer

func WithHTTPReferer(httpReferer string) SDKOption

WithHTTPReferer allows setting the HTTPReferer parameter for all supported operations

func WithRetryConfig

func WithRetryConfig(retryConfig retry.Config) SDKOption

func WithSecurity

func WithSecurity(apiKey string) SDKOption

WithSecurity configures the SDK to use the provided security details

func WithSecuritySource

func WithSecuritySource(security func(context.Context) (components.Security, error)) SDKOption

WithSecuritySource configures the SDK to invoke the Security Source function on each method call to determine authentication

func WithServer

func WithServer(server string) SDKOption

WithServer allows the overriding of the default server by name

func WithServerURL

func WithServerURL(serverURL string) SDKOption

WithServerURL allows providing an alternative server URL

func WithTemplatedServerURL

func WithTemplatedServerURL(serverURL string, params map[string]string) SDKOption

WithTemplatedServerURL allows the overriding of the default server URL with a templated URL populated with the provided parameters

func WithTimeout

func WithTimeout(timeout time.Duration) SDKOption

WithTimeout Optional request timeout applied to each operation

func WithXTitle

func WithXTitle(xTitle string) SDKOption

WithXTitle allows setting the XTitle parameter for all supported operations

type STT added in v0.7.13

type STT struct {
	// contains filtered or unexported fields
}

STT - Speech-to-text endpoints

func (*STT) CreateTranscription added in v0.7.13

func (s *STT) CreateTranscription(ctx context.Context, request components.STTRequest, opts ...operations.Option) (*components.STTResponse, error)

CreateTranscription - Create transcription Transcribes audio into text. Accepts base64-encoded audio input as JSON or an OpenAI-style multipart/form-data file upload, and returns the transcribed text.

func (*STT) CreateTranscriptionMultipart added in v0.7.13

func (s *STT) CreateTranscriptionMultipart(ctx context.Context, request operations.CreateAudioTranscriptionsMultipartRequest, opts ...operations.Option) (*components.STTResponse, error)

CreateTranscriptionMultipart - Create transcription Transcribes audio into text. Accepts base64-encoded audio input as JSON or an OpenAI-style multipart/form-data file upload, and returns the transcribed text.

type Scim added in v0.7.14

type Scim struct {
	// contains filtered or unexported fields
}

Scim - Management endpoints for SCIM group-to-workspace mappings, authenticated with a management key. These are not the SCIM 2.0 connector endpoints for your identity provider. In your identity provider, enter the SCIM endpoint URL shown when you enable provisioning under Settings > Members > SCIM Mappings. See https://openrouter.ai/docs/guides/features/scim-mappings#set-up-provisioning.

func (*Scim) Create added in v0.7.14

Create a SCIM group mapping Create a SCIM group-to-workspace role mapping. Creating a mapping that already exists with the same role succeeds and re-applies the mapping to the group members. Requesting a different role for an existing mapping returns 409. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Scim) CreateSyncJob added in v0.7.117

func (s *Scim) CreateSyncJob(ctx context.Context, opts ...operations.Option) (*operations.CreateScimSyncJobResponse, error)

CreateSyncJob - Start a SCIM directory sync Start a SCIM directory sync. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Scim) Delete added in v0.7.14

Delete a SCIM group mapping Delete a SCIM group-to-workspace mapping. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Scim) GetSyncJob added in v0.7.117

func (s *Scim) GetSyncJob(ctx context.Context, id string, opts ...operations.Option) (*components.GetScimSyncJobResponse, error)

GetSyncJob - Get SCIM directory sync status Get SCIM directory sync status. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Scim) ListGroups added in v0.7.14

ListGroups - List SCIM groups List SCIM groups for the organization. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Scim) ListMappings added in v0.7.14

ListMappings - List SCIM group mappings List SCIM group-to-workspace mappings for the organization. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Scim) Read added in v0.7.14

Read - Get a SCIM group mapping Get a SCIM group-to-workspace mapping. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Scim) Update added in v0.7.14

Update a SCIM group mapping Update a SCIM group mapping role. [Management key](/docs/guides/overview/auth/management-api-keys) required.

type TTS added in v0.7.13

type TTS struct {
	// contains filtered or unexported fields
}

TTS - Text-to-speech endpoints

func (*TTS) CreateSpeech added in v0.7.13

func (s *TTS) CreateSpeech(ctx context.Context, request components.SpeechRequest, opts ...operations.Option) (io.ReadCloser, error)

CreateSpeech - Create speech Synthesizes audio from the input text. Returns a raw audio bytestream in the requested format (e.g. mp3, pcm, wav).

type Vault added in v0.7.145

type Vault struct {
	// contains filtered or unexported fields
}

Vault - Store host-bound secrets for a workspace or for one intern. Scope is selected by the API key. Responses return metadata only, never secret values. See https://openrouter.ai/docs/guides/ori/vault.

func (*Vault) CopyVaultSecretsToIntern added in v0.7.145

func (s *Vault) CopyVaultSecretsToIntern(ctx context.Context, internID string, vaultSecretCopyRequest components.VaultSecretCopyRequest, opts ...operations.Option) (*components.VaultSecretCopyResponse, error)

CopyVaultSecretsToIntern - Copy workspace secrets to an intern Copies the named workspace secrets into one intern's scope, replacing any intern secret with the same name. Each copy keeps the source value and host bindings. Every name must exist in the workspace scope or the request fails with 404 and nothing is copied. A workspace secret whose `hosts` is `null` cannot be copied: the request fails with 409 and nothing is copied until that secret is stored again with hosts. The response carries metadata only. Writes return 503 while vault writes are disabled for the caller. The scope is selected by the API key: workspace routes act on the key's active workspace and intern routes act on one intern inside that workspace. There is no default workspace and no fallback to another scope. Every vault route, including reads, requires access to the Intern API programme and returns 404 outside it. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Vault) DeleteInternVaultSecret added in v0.7.145

func (s *Vault) DeleteInternVaultSecret(ctx context.Context, internID string, name string, opts ...operations.Option) error

DeleteInternVaultSecret - Delete an intern secret Deletes a secret stored for one intern. Returns 204 with no body on success and 404 when the secret does not exist in the selected scope. Writes return 503 while vault writes are disabled for the caller. The scope is selected by the API key: workspace routes act on the key's active workspace and intern routes act on one intern inside that workspace. There is no default workspace and no fallback to another scope. Every vault route, including reads, requires access to the Intern API programme and returns 404 outside it. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Vault) DeleteVaultSecret added in v0.7.145

func (s *Vault) DeleteVaultSecret(ctx context.Context, name string, opts ...operations.Option) error

DeleteVaultSecret - Delete a workspace secret Deletes a secret from the workspace of the authenticated API key. Returns 204 with no body on success and 404 when the secret does not exist in the selected scope. Writes return 503 while vault writes are disabled for the caller. The scope is selected by the API key: workspace routes act on the key's active workspace and intern routes act on one intern inside that workspace. There is no default workspace and no fallback to another scope. Every vault route, including reads, requires access to the Intern API programme and returns 404 outside it. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Vault) ListInternVaultSecrets added in v0.7.145

func (s *Vault) ListInternVaultSecrets(ctx context.Context, internID string, limit *int64, offset *int64, opts ...operations.Option) (*components.VaultSecretListResponse, error)

ListInternVaultSecrets - List intern secrets Lists secret metadata stored for one intern. Responses contain names, bound hosts, fingerprints and creation times, never secret values. Results are ordered by name and paginated with `limit` and `offset`. The scope is selected by the API key: workspace routes act on the key's active workspace and intern routes act on one intern inside that workspace. There is no default workspace and no fallback to another scope. Every vault route, including reads, requires access to the Intern API programme and returns 404 outside it. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Vault) ListVaultSecrets added in v0.7.145

func (s *Vault) ListVaultSecrets(ctx context.Context, limit *int64, offset *int64, opts ...operations.Option) (*components.VaultSecretListResponse, error)

ListVaultSecrets - List workspace secrets Lists secret metadata for the workspace of the authenticated API key. Responses contain names, bound hosts, fingerprints and creation times, never secret values. Results are ordered by name and paginated with `limit` and `offset`. The scope is selected by the API key: workspace routes act on the key's active workspace and intern routes act on one intern inside that workspace. There is no default workspace and no fallback to another scope. Every vault route, including reads, requires access to the Intern API programme and returns 404 outside it. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Vault) StoreInternVaultSecret added in v0.7.145

func (s *Vault) StoreInternVaultSecret(ctx context.Context, internID string, name string, vaultSecretWriteRequest components.VaultSecretWriteRequest, opts ...operations.Option) (*components.VaultSecretResponse, error)

StoreInternVaultSecret - Store an intern secret Creates or replaces a secret stored for one intern. The value is encrypted at rest and released only to the exact hostnames in `hosts`. The response carries metadata only. Writes return 503 while vault writes are disabled for the caller. The scope is selected by the API key: workspace routes act on the key's active workspace and intern routes act on one intern inside that workspace. There is no default workspace and no fallback to another scope. Every vault route, including reads, requires access to the Intern API programme and returns 404 outside it. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

func (*Vault) StoreVaultSecret added in v0.7.145

func (s *Vault) StoreVaultSecret(ctx context.Context, name string, vaultSecretWriteRequest components.VaultSecretWriteRequest, opts ...operations.Option) (*components.VaultSecretResponse, error)

StoreVaultSecret - Store a workspace secret Creates or replaces a secret in the workspace of the authenticated API key. The value is encrypted at rest and released only to the exact hostnames in `hosts`. The response carries metadata only. Writes return 503 while vault writes are disabled for the caller. The scope is selected by the API key: workspace routes act on the key's active workspace and intern routes act on one intern inside that workspace. There is no default workspace and no fallback to another scope. Every vault route, including reads, requires access to the Intern API programme and returns 404 outside it. Requests on regional hostnames such as `eu.openrouter.ai` are refused. [API key](/docs/api-reference/authentication) required.

If set, this operation will use [Security.APIKey] from the global security.

type VideoGeneration

type VideoGeneration struct {
	// contains filtered or unexported fields
}

VideoGeneration - Video Generation endpoints

func (*VideoGeneration) Generate

Generate - Submit a video generation request Submits a video generation request and returns a polling URL to check status

func (*VideoGeneration) GetGeneration

GetGeneration - Poll video generation status Returns job status and content URLs when completed

func (*VideoGeneration) GetVideoContent

func (s *VideoGeneration) GetVideoContent(ctx context.Context, jobID string, index optionalnullable.OptionalNullable[int64], opts ...operations.Option) (io.ReadCloser, error)

GetVideoContent - Download generated video content Streams the generated video content from the upstream provider

func (*VideoGeneration) ListVideosModels

ListVideosModels - List all video generation models Returns a list of all available video generation models and their properties

type Workspaces

type Workspaces struct {
	// contains filtered or unexported fields
}

Workspaces endpoints

func (*Workspaces) BulkAddMembers

func (s *Workspaces) BulkAddMembers(ctx context.Context, id string, bulkAddWorkspaceMembersRequest components.BulkAddWorkspaceMembersRequest, opts ...operations.Option) (*components.BulkAddWorkspaceMembersResponse, error)

BulkAddMembers - Bulk add members to a workspace Add multiple organization members to a workspace. Members are assigned the same role they hold in the organization. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) BulkRemoveMembers

func (s *Workspaces) BulkRemoveMembers(ctx context.Context, id string, bulkRemoveWorkspaceMembersRequest components.BulkRemoveWorkspaceMembersRequest, opts ...operations.Option) (*components.BulkRemoveWorkspaceMembersResponse, error)

BulkRemoveMembers - Bulk remove members from a workspace Remove multiple members from a workspace. Members with active API keys in the workspace cannot be removed. SCIM-managed members cannot be removed; changes must be made in your identity provider. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) Create

Create a workspace Create a new workspace for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) Delete

func (s *Workspaces) Delete(ctx context.Context, id string, confirmDefaultWorkspaceDeletion *bool, opts ...operations.Option) (*components.DeleteWorkspaceResponse, error)

Delete a workspace Delete an existing workspace. Workspaces with active API keys cannot be deleted; remove the keys first. Deleting the default workspace requires confirm_default_workspace_deletion=true. Deleting any workspace permanently deletes its budgets and guardrails and disables its classifiers and broadcast destinations. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) DeleteBudget

DeleteBudget - Delete a workspace budget Remove the budget for a given interval. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) Get

Get a workspace Get a single workspace by ID or slug. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) GetBudget added in v0.7.21

GetBudget - Get a workspace budget Retrieve the budget for a given interval. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) List

List workspaces List all workspaces for the authenticated user. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) ListBudgets

func (s *Workspaces) ListBudgets(ctx context.Context, workspaceRef string, opts ...operations.Option) (*components.ListWorkspaceBudgetsResponse, error)

ListBudgets - List workspace budgets List all budgets configured for a workspace. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) ListMembers added in v0.5.11

ListMembers - List workspace members List all members of a workspace. Returns paginated results. For the default workspace, returns all organization members (implicit membership). [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) SetBudget

SetBudget - Create or update a workspace budget Create or update the budget for a given interval. Budget limits must strictly decrease as the interval narrows (lifetime > monthly > weekly > daily). The optional `include_byok_in_budgets` flag is a workspace-wide setting: when provided it applies to every budget interval for the workspace, not just the interval in this request. Note that a change made here is applied to budget enforcement immediately, but an already-open workspace settings page in the web dashboard may keep showing the previous value until it is reloaded. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Workspaces) Update

Update a workspace Update an existing workspace by ID or slug. [Management key](/docs/guides/overview/auth/management-api-keys) required.

Directories

Path Synopsis
internal
models

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL