openrouter

package module
v0.5.29 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 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.5.29

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

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)
	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)
	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))
	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
Analytics
APIKeys
Benchmarks
Beta.Analytics
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
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
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
Stt
Tts
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.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(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, 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

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

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. [Management key](/docs/guides/overview/auth/management-api-keys) required.

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. [Management key](/docs/guides/overview/auth/management-api-keys) required.

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. [Management key](/docs/guides/overview/auth/management-api-keys) required.

type Analytics

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

Analytics and usage endpoints

func (*Analytics) GetUserActivity

func (s *Analytics) GetUserActivity(ctx context.Context, date *string, apiKeyHash *string, userID *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. [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). 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. 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 {
	// beta.Analytics endpoints
	Analytics *BetaAnalytics
	// beta.responses endpoints
	Responses *Responses
	// contains filtered or unexported fields
}

type BetaAnalytics

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

BetaAnalytics - beta.Analytics endpoints

func (*BetaAnalytics) GetAnalyticsMeta

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 (*BetaAnalytics) QueryAnalytics

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

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

Byok - BYOK endpoints

func (*Byok) Create

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. Defaults to the authenticated entity's default workspace; use the `workspace_id` body field to scope to a different workspace. Treat the raw key as write-only; it is never returned after creation. [Management key](/docs/guides/overview/auth/management-api-keys) required.

func (*Byok) Delete

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

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

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

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). [Management key](/docs/guides/overview/auth/management-api-keys) required.

type Chat

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

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

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.

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.

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

func (s *Files) List(ctx context.Context, limit *int64, cursor *string, workspaceID *string, opts ...operations.Option) (*operations.ListFilesResponse, error)

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, opts ...operations.Option) (*components.FileMetadata, 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, opts ...operations.Option) (*components.FileMetadata, 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.

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 and completion 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. [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. 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 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

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). If requesting through `eu.openrouter.ai/api/v1/...` the results will be filtered to models that satisfy [EU in-region routing](https://openrouter.ai/docs/guides/privacy/provider-logging#enterprise-eu-in-region-routing).

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

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

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
	Beta      *Beta
	// 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
	Chat *Chat
	// Task classification market-share endpoints
	Classifications *Classifications
	// Credit management endpoints
	Credits *Credits
	// Datasets endpoints
	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
	// 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
	// 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.5.29

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
}

Responses - beta.responses 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

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

Stt - Speech-to-text endpoints

func (*Stt) CreateTranscription

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.5.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 Tts

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

Tts - Text-to-speech endpoints

func (*Tts) CreateSpeech

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

Delete a workspace Delete an existing workspace. The default workspace cannot be deleted. Workspaces with active API keys cannot be deleted; remove the keys first. [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) List

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

func (*Workspaces) ListBudgets

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). [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