openrouter

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// AuthorizeURL is where the user approves the connection. OpenRouter's OAuth
	// is PKCE-only: there is no app to register, so no client ID or secret.
	AuthorizeURL = "https://openrouter.ai/auth"

	// KeysURL exchanges the authorization code for an inference API key.
	KeysURL = baseURL + "/auth/keys"
)
View Source
const (
	// SecretAPIKey holds the inference key returned by the OAuth exchange.
	SecretAPIKey = "apiKey"

	// SecretCodeVerifier holds the PKCE verifier between the authorize redirect
	// and the callback. It is a secret rather than metadata because integration
	// metadata is serialized to the browser in plaintext.
	SecretCodeVerifier = "codeVerifier"
)
View Source
const (
	ResourceTypeModel    = "model"
	ResourceTypeProvider = "provider"
)
View Source
const ChatCompletionPayloadType = "openrouter.chatCompletion.result"
View Source
const ChildKeyTTLSlack = 15 * time.Minute

ChildKeyTTLSlack covers broker queue delay after SuperPlane mints a key.

View Source
const GetCreditsPayloadType = "openrouter.getCredits.result"

Variables

This section is empty.

Functions

func ChildKeyExpiresAt

func ChildKeyExpiresAt(now time.Time, executionTimeoutSeconds int) time.Time

func FormatKeyExpiresAt

func FormatKeyExpiresAt(expiresAt time.Time) string

func RunnerKeyName

func RunnerKeyName(runID uuid.UUID) string

Types

type Annotation

type Annotation struct {
	Type        string       `json:"type"`
	URLCitation *URLCitation `json:"url_citation,omitempty"`
}

Annotation is a source the web plugin cited.

type Auth

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

func NewAuth

func NewAuth(httpClient core.HTTPContext) *Auth

func (*Auth) ExchangeCode

func (a *Auth) ExchangeCode(code, verifier string) (string, error)

ExchangeCode trades the authorization code for an inference API key. The response carries a normal sk-or-v1 key; OpenRouter's OAuth cannot issue a provisioning key, which is why Get Credits still takes one from configuration.

type ChatCompletion

type ChatCompletion struct{}

func (*ChatCompletion) Cancel

func (c *ChatCompletion) Cancel(ctx core.ExecutionContext) error

func (*ChatCompletion) Cleanup

func (c *ChatCompletion) Cleanup(ctx core.SetupContext) error

func (*ChatCompletion) Color

func (c *ChatCompletion) Color() string

func (*ChatCompletion) Configuration

func (c *ChatCompletion) Configuration() []configuration.Field

func (*ChatCompletion) Description

func (c *ChatCompletion) Description() string

func (*ChatCompletion) Documentation

func (c *ChatCompletion) Documentation() string

func (*ChatCompletion) ExampleOutput

func (c *ChatCompletion) ExampleOutput() map[string]any

func (*ChatCompletion) Execute

func (c *ChatCompletion) Execute(ctx core.ExecutionContext) error

func (*ChatCompletion) HandleHook

func (c *ChatCompletion) HandleHook(ctx core.ActionHookContext) error

func (*ChatCompletion) HandleWebhook

func (*ChatCompletion) Hooks

func (c *ChatCompletion) Hooks() []core.Hook

func (*ChatCompletion) Icon

func (c *ChatCompletion) Icon() string

func (*ChatCompletion) Label

func (c *ChatCompletion) Label() string

func (*ChatCompletion) Name

func (c *ChatCompletion) Name() string

func (*ChatCompletion) OutputChannels

func (c *ChatCompletion) OutputChannels(config any) []core.OutputChannel

func (*ChatCompletion) Setup

func (c *ChatCompletion) Setup(ctx core.SetupContext) error

type ChatCompletionNodeMetadata

type ChatCompletionNodeMetadata struct {
	Model            string `json:"model" mapstructure:"model"`
	ProviderRouting  bool   `json:"providerRouting" mapstructure:"providerRouting"`
	StructuredOutput bool   `json:"structuredOutput" mapstructure:"structuredOutput"`
	WebSearch        bool   `json:"webSearch" mapstructure:"webSearch"`
}

ChatCompletionNodeMetadata is node-level metadata surfaced in the UI so the configured model and routing are visible without opening the node.

type ChatCompletionPayload

type ChatCompletionPayload struct {
	ID           string                  `json:"id"`
	Model        string                  `json:"model"`
	Provider     string                  `json:"provider"`
	Text         string                  `json:"text"`
	Parsed       any                     `json:"parsed,omitempty"`
	Reasoning    string                  `json:"reasoning,omitempty"`
	Citations    []Citation              `json:"citations,omitempty"`
	FinishReason string                  `json:"finishReason"`
	Usage        *Usage                  `json:"usage,omitempty"`
	Response     *ChatCompletionResponse `json:"response"`
}

type ChatCompletionRequest

type ChatCompletionRequest struct {
	Model          string           `json:"model,omitempty"`
	Models         []string         `json:"models,omitempty"`
	Messages       []Message        `json:"messages"`
	MaxTokens      *int             `json:"max_tokens,omitempty"`
	Temperature    *float64         `json:"temperature,omitempty"`
	Provider       *ProviderRouting `json:"provider,omitempty"`
	ResponseFormat *ResponseFormat  `json:"response_format,omitempty"`
	Plugins        []Plugin         `json:"plugins,omitempty"`
}

ChatCompletionRequest is the OpenAI-compatible chat completions body. Model and Models are mutually exclusive: Models replaces Model with an ordered fallback chain whose first entry is the primary. Provider carries the per-request provider routing preferences.

type ChatCompletionResponse

type ChatCompletionResponse struct {
	ID       string   `json:"id"`
	Object   string   `json:"object"`
	Created  int64    `json:"created"`
	Model    string   `json:"model"`
	Provider string   `json:"provider"`
	Choices  []Choice `json:"choices"`
	Usage    *Usage   `json:"usage,omitempty"`
}

type ChatCompletionSpec

type ChatCompletionSpec struct {
	Model         string               `json:"model" mapstructure:"model"`
	Prompt        string               `json:"prompt" mapstructure:"prompt"`
	SystemPrompt  string               `json:"systemPrompt" mapstructure:"systemPrompt"`
	MaxTokens     *int                 `json:"maxTokens" mapstructure:"maxTokens"`
	Temperature   *float64             `json:"temperature" mapstructure:"temperature"`
	Models        []string             `json:"models" mapstructure:"models"`
	Provider      *ProviderRoutingSpec `json:"provider" mapstructure:"provider"`
	OutputSchema  string               `json:"outputSchema" mapstructure:"outputSchema"`
	WebSearch     bool                 `json:"webSearch" mapstructure:"webSearch"`
	WebMaxResults *int                 `json:"webMaxResults" mapstructure:"webMaxResults"`
}

type Choice

type Choice struct {
	Index              int           `json:"index"`
	FinishReason       string        `json:"finish_reason"`
	NativeFinishReason string        `json:"native_finish_reason"`
	Message            ChoiceMessage `json:"message"`
}

type ChoiceMessage

type ChoiceMessage struct {
	Role        string       `json:"role"`
	Content     *string      `json:"content"`
	Reasoning   string       `json:"reasoning,omitempty"`
	Refusal     string       `json:"refusal,omitempty"`
	Annotations []Annotation `json:"annotations,omitempty"`
}

ChoiceMessage carries the generated message. Content is a pointer because OpenRouter returns null when reasoning tokens consumed the whole token budget, which is distinct from an empty string.

type Citation

type Citation struct {
	URL   string `json:"url"`
	Title string `json:"title"`
}

Citation is a source the web plugin used, flattened for downstream nodes.

type Client

type Client struct {
	APIKey        string
	ManagementKey string
	// contains filtered or unexported fields
}

func NewClient

func NewClient(httpClient core.HTTPContext, ctx core.IntegrationContext) (*Client, error)

func NewManagementClient

func NewManagementClient(httpClient core.HTTPContext, managementKey string) *Client

func (*Client) CreateChatCompletion

func (c *Client) CreateChatCompletion(req ChatCompletionRequest) (*ChatCompletionResponse, error)

func (*Client) CreateKey

func (c *Client) CreateKey(req CreateKeyRequest) (*CreatedKey, error)

func (*Client) DeleteKey

func (c *Client) DeleteKey(hash string) error

func (*Client) GetCredits

func (c *Client) GetCredits() (*Credits, error)

GetCredits reads the account credit totals. OpenRouter documents /credits as a management-key endpoint, so it is signed with the provisioning key rather than the inference key, even though the endpoint currently also accepts the latter.

func (*Client) GetKey

func (c *Client) GetKey() (*KeyInfo, error)

GetKey reports usage and limits for the key that signs the request, so it uses the inference key: the provisioning key's own usage is not what the component reports on.

func (*Client) ListModelEndpoints

func (c *Client) ListModelEndpoints(model string) ([]ModelEndpoint, error)

ListModelEndpoints returns every provider endpoint serving the given model.

func (*Client) ListModels

func (c *Client) ListModels() ([]Model, error)

func (*Client) ListProviders

func (c *Client) ListProviders() ([]Provider, error)

func (*Client) Verify

func (c *Client) Verify() error

func (*Client) VerifyManagement

func (c *Client) VerifyManagement() error

VerifyManagement checks the management key against an endpoint that rejects normal API keys with 403.

type CompletionTokensDetails

type CompletionTokensDetails struct {
	ReasoningTokens int `json:"reasoning_tokens"`
	AudioTokens     int `json:"audio_tokens"`
}

type Configuration

type Configuration struct {
	ManagementKey string `json:"managementKey"`
}

type CostDetails

type CostDetails struct {
	UpstreamInferenceCost           float64 `json:"upstream_inference_cost"`
	UpstreamInferencePromptCost     float64 `json:"upstream_inference_prompt_cost"`
	UpstreamInferenceCompletionCost float64 `json:"upstream_inference_completions_cost"`
}

type CreateKeyRequest

type CreateKeyRequest struct {
	Name      string `json:"name"`
	ExpiresAt string `json:"expires_at"`
}

type CreatedKey

type CreatedKey struct {
	Key  string
	Hash string
}

type Credits

type Credits struct {
	TotalCredits float64 `json:"total_credits"`
	TotalUsage   float64 `json:"total_usage"`
}

type CreditsResponse

type CreditsResponse struct {
	Data Credits `json:"data"`
}

type GetCredits

type GetCredits struct{}

func (*GetCredits) Cancel

func (c *GetCredits) Cancel(ctx core.ExecutionContext) error

func (*GetCredits) Cleanup

func (c *GetCredits) Cleanup(ctx core.SetupContext) error

func (*GetCredits) Color

func (c *GetCredits) Color() string

func (*GetCredits) Configuration

func (c *GetCredits) Configuration() []configuration.Field

func (*GetCredits) Description

func (c *GetCredits) Description() string

func (*GetCredits) Documentation

func (c *GetCredits) Documentation() string

func (*GetCredits) ExampleOutput

func (c *GetCredits) ExampleOutput() map[string]any

func (*GetCredits) Execute

func (c *GetCredits) Execute(ctx core.ExecutionContext) error

func (*GetCredits) HandleHook

func (c *GetCredits) HandleHook(ctx core.ActionHookContext) error

func (*GetCredits) HandleWebhook

func (*GetCredits) Hooks

func (c *GetCredits) Hooks() []core.Hook

func (*GetCredits) Icon

func (c *GetCredits) Icon() string

func (*GetCredits) Label

func (c *GetCredits) Label() string

func (*GetCredits) Name

func (c *GetCredits) Name() string

func (*GetCredits) OutputChannels

func (c *GetCredits) OutputChannels(config any) []core.OutputChannel

func (*GetCredits) Setup

func (c *GetCredits) Setup(ctx core.SetupContext) error

type GetCreditsOutput

type GetCreditsOutput struct {
	TotalCredits float64  `json:"totalCredits"`
	TotalUsage   float64  `json:"totalUsage"`
	Balance      float64  `json:"balance"`
	Key          KeyUsage `json:"key"`
}

type JSONSchema

type JSONSchema struct {
	Name   string `json:"name"`
	Strict bool   `json:"strict"`
	Schema any    `json:"schema"`
}

type KeyInfo

type KeyInfo struct {
	Label          string   `json:"label"`
	Limit          *float64 `json:"limit"`
	LimitRemaining *float64 `json:"limit_remaining"`
	LimitReset     *string  `json:"limit_reset"`
	Usage          float64  `json:"usage"`
	UsageDaily     float64  `json:"usage_daily"`
	UsageWeekly    float64  `json:"usage_weekly"`
	UsageMonthly   float64  `json:"usage_monthly"`
	IsFreeTier     bool     `json:"is_free_tier"`
}

type KeyResponse

type KeyResponse struct {
	Data KeyInfo `json:"data"`
}

type KeyUsage

type KeyUsage struct {
	Label          string   `json:"label"`
	Limit          *float64 `json:"limit"`
	LimitRemaining *float64 `json:"limitRemaining"`
	LimitReset     *string  `json:"limitReset"`
	Usage          float64  `json:"usage"`
	UsageDaily     float64  `json:"usageDaily"`
	UsageWeekly    float64  `json:"usageWeekly"`
	UsageMonthly   float64  `json:"usageMonthly"`
	IsFreeTier     bool     `json:"isFreeTier"`
}

KeyUsage is the usage and limits of the API key the integration is configured with, as opposed to the account-wide credit totals.

type Message

type Message struct {
	Role    string `json:"role"`
	Content any    `json:"content"`
}

Message is one chat message.

type Metadata

type Metadata struct {
	State string `json:"state" mapstructure:"state"`
}

type Model

type Model struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type ModelEndpoint

type ModelEndpoint struct {
	Name         string `json:"name"`
	ProviderName string `json:"provider_name"`
	Tag          string `json:"tag"`
	Quantization string `json:"quantization"`
}

ModelEndpoint is one provider serving a model. Tag identifies the specific endpoint and may carry a region suffix (e.g. "azure/swedencentral"); the part before the slash is the provider slug that routing accepts.

type ModelEndpointsResponse

type ModelEndpointsResponse struct {
	Data struct {
		ID        string          `json:"id"`
		Endpoints []ModelEndpoint `json:"endpoints"`
	} `json:"data"`
}

type ModelsResponse

type ModelsResponse struct {
	Data []Model `json:"data"`
}

type OpenRouter

type OpenRouter struct{}

func (*OpenRouter) Actions

func (o *OpenRouter) Actions() []core.Action

func (*OpenRouter) Cleanup

func (*OpenRouter) Configuration

func (o *OpenRouter) Configuration() []configuration.Field

func (*OpenRouter) Description

func (o *OpenRouter) Description() string

func (*OpenRouter) HandleHook

func (o *OpenRouter) HandleHook(ctx core.IntegrationHookContext) error

func (*OpenRouter) HandleRequest

func (o *OpenRouter) HandleRequest(ctx core.HTTPRequestContext)

func (*OpenRouter) Hooks

func (o *OpenRouter) Hooks() []core.Hook

func (*OpenRouter) Icon

func (o *OpenRouter) Icon() string

func (*OpenRouter) Instructions

func (o *OpenRouter) Instructions() string

func (*OpenRouter) Label

func (o *OpenRouter) Label() string

func (*OpenRouter) ListResources

func (o *OpenRouter) ListResources(resourceType string, ctx core.ListResourcesContext) ([]core.IntegrationResource, error)

func (*OpenRouter) Name

func (o *OpenRouter) Name() string

func (*OpenRouter) ResolveSecrets

func (*OpenRouter) Sync

func (o *OpenRouter) Sync(ctx core.SyncContext) error

func (*OpenRouter) Triggers

func (o *OpenRouter) Triggers() []core.Trigger

type Plugin

type Plugin struct {
	ID         string `json:"id"`
	MaxResults *int   `json:"max_results,omitempty"`
}

Plugin enables an OpenRouter plugin. The web plugin runs a search before the model answers and is billed on top of tokens, even on free models.

type PromptTokensDetails

type PromptTokensDetails struct {
	CachedTokens int `json:"cached_tokens"`
	AudioTokens  int `json:"audio_tokens"`
}

type Provider

type Provider struct {
	Name string `json:"name"`
	Slug string `json:"slug"`
}

type ProviderRouting

type ProviderRouting struct {
	Sort              string   `json:"sort,omitempty"`
	Only              []string `json:"only,omitempty"`
	Ignore            []string `json:"ignore,omitempty"`
	AllowFallbacks    *bool    `json:"allow_fallbacks,omitempty"`
	RequireParameters *bool    `json:"require_parameters,omitempty"`
	DataCollection    string   `json:"data_collection,omitempty"`
}

ProviderRouting controls which upstream provider serves the request. A model ID is a listing served by many providers that differ in price, context length and quantization, so these preferences are how a workflow pins that choice instead of letting OpenRouter pick silently.

type ProviderRoutingSpec

type ProviderRoutingSpec struct {
	Sort              string   `json:"sort" mapstructure:"sort"`
	Only              []string `json:"only" mapstructure:"only"`
	Ignore            []string `json:"ignore" mapstructure:"ignore"`
	AllowFallbacks    *bool    `json:"allowFallbacks" mapstructure:"allowFallbacks"`
	RequireParameters *bool    `json:"requireParameters" mapstructure:"requireParameters"`
	DataCollection    string   `json:"dataCollection" mapstructure:"dataCollection"`
}

type ProvidersResponse

type ProvidersResponse struct {
	Data []Provider `json:"data"`
}

type ResponseFormat

type ResponseFormat struct {
	Type       string      `json:"type"`
	JSONSchema *JSONSchema `json:"json_schema,omitempty"`
}

ResponseFormat constrains the reply to a JSON schema. Note this is the chat completions shape (response_format.json_schema), not the Responses API's text.format that the OpenAI integration uses.

type URLCitation

type URLCitation struct {
	URL     string `json:"url"`
	Title   string `json:"title"`
	Content string `json:"content,omitempty"`
}

type Usage

type Usage struct {
	PromptTokens            int                      `json:"prompt_tokens"`
	CompletionTokens        int                      `json:"completion_tokens"`
	TotalTokens             int                      `json:"total_tokens"`
	Cost                    float64                  `json:"cost"`
	CostDetails             *CostDetails             `json:"cost_details,omitempty"`
	PromptTokensDetails     *PromptTokensDetails     `json:"prompt_tokens_details,omitempty"`
	CompletionTokensDetails *CompletionTokensDetails `json:"completion_tokens_details,omitempty"`
}

Jump to

Keyboard shortcuts

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