Documentation
¶
Overview ¶
Package openrouter provides Go bindings for the OpenRouter API.
Index ¶
- Variables
- func ConcatenateChatStreamResponses(responses []ChatCompletionResponse) string
- func ConcatenateCompletionStreamResponses(responses []CompletionResponse) string
- func DefaultWebSearchPrompt(date string) string
- func EncodeAudioBytesToBase64(audioData []byte, format string) (string, error)
- func EncodeAudioToBase64(audioPath string) (string, string, error)
- func EncodeImageBytesToBase64(imageData []byte, contentType string) string
- func EncodeImageToBase64(imagePath string) (string, error)
- func EncodePDFBytesToBase64(pdfData []byte) string
- func EncodePDFToBase64(pdfPath string) (string, error)
- func RetryWithBackoff(ctx context.Context, config *RetryConfig, fn func() error) error
- func WithOnlineModel(model string) string
- type APIError
- type APIKey
- type ActivityData
- type ActivityOptions
- type ActivityResponse
- type Annotation
- type ChatCompletionOption
- func WithAllowFallbacks(allow bool) ChatCompletionOption
- func WithDataCollection(policy string) ChatCompletionOption
- func WithFloorPrice() ChatCompletionOption
- func WithFrequencyPenalty(penalty float64) ChatCompletionOption
- func WithIgnoreProviders(providers ...string) ChatCompletionOption
- func WithJSONMode() ChatCompletionOption
- func WithJSONSchema(name string, strict bool, schema map[string]interface{}) ChatCompletionOption
- func WithLogProbs(topLogProbs int) ChatCompletionOption
- func WithMaxPrice(maxPrice MaxPrice) ChatCompletionOption
- func WithMaxTokens(maxTokens int) ChatCompletionOption
- func WithMessages(messages []Message) ChatCompletionOption
- func WithMetadata(metadata map[string]interface{}) ChatCompletionOption
- func WithModel(model string) ChatCompletionOption
- func WithModels(models ...string) ChatCompletionOption
- func WithNitro() ChatCompletionOption
- func WithOnlyProviders(providers ...string) ChatCompletionOption
- func WithParallelToolCalls(parallel *bool) ChatCompletionOption
- func WithPlugins(plugins ...Plugin) ChatCompletionOption
- func WithPresencePenalty(penalty float64) ChatCompletionOption
- func WithProvider(provider Provider) ChatCompletionOption
- func WithProviderOrder(providers ...string) ChatCompletionOption
- func WithProviderSort(sort string) ChatCompletionOption
- func WithQuantizations(quantizations ...string) ChatCompletionOption
- func WithRepetitionPenalty(penalty float64) ChatCompletionOption
- func WithRequireParameters(require bool) ChatCompletionOption
- func WithResponseFormat(format ResponseFormat) ChatCompletionOption
- func WithRoute(route string) ChatCompletionOption
- func WithSeed(seed int) ChatCompletionOption
- func WithStop(stop ...string) ChatCompletionOption
- func WithTemperature(temperature float64) ChatCompletionOption
- func WithToolChoice(toolChoice interface{}) ChatCompletionOption
- func WithTools(tools ...Tool) ChatCompletionOption
- func WithTopK(topK int) ChatCompletionOption
- func WithTopP(topP float64) ChatCompletionOption
- func WithTransforms(transforms ...string) ChatCompletionOption
- func WithWebSearchOptions(options *WebSearchOptions) ChatCompletionOption
- func WithZDR(enabled bool) ChatCompletionOption
- type ChatCompletionRequest
- type ChatCompletionResponse
- type ChatStream
- type Choice
- type Client
- func (c *Client) ChatComplete(ctx context.Context, messages []Message, opts ...ChatCompletionOption) (*ChatCompletionResponse, error)
- func (c *Client) ChatCompleteStream(ctx context.Context, messages []Message, opts ...ChatCompletionOption) (*ChatStream, error)
- func (c *Client) Complete(ctx context.Context, prompt string, opts ...CompletionOption) (*CompletionResponse, error)
- func (c *Client) CompleteStream(ctx context.Context, prompt string, opts ...CompletionOption) (*CompletionStream, error)
- func (c *Client) CompleteWithContext(ctx context.Context, contextPrompt, userPrompt string, ...) (*CompletionResponse, error)
- func (c *Client) CompleteWithExamples(ctx context.Context, instruction string, examples []string, prompt string, ...) (*CompletionResponse, error)
- func (c *Client) CreateEmbedding(ctx context.Context, input interface{}, model string, opts ...EmbeddingOption) (*EmbeddingResponse, error)
- func (c *Client) CreateEmbeddings(ctx context.Context, inputs []string, model string, opts ...EmbeddingOption) (*EmbeddingResponse, error)
- func (c *Client) CreateKey(ctx context.Context, request *CreateKeyRequest) (*CreateKeyResponse, error)
- func (c *Client) DeleteKey(ctx context.Context, hash string) (*DeleteKeyResponse, error)
- func (c *Client) GetActivity(ctx context.Context, opts *ActivityOptions) (*ActivityResponse, error)
- func (c *Client) GetCredits(ctx context.Context) (*CreditsResponse, error)
- func (c *Client) GetKey(ctx context.Context) (*KeyResponse, error)
- func (c *Client) GetKeyByHash(ctx context.Context, hash string) (*GetKeyByHashResponse, error)
- func (c *Client) ListEmbeddingsModels(ctx context.Context) (*EmbeddingsModelsResponse, error)
- func (c *Client) ListKeys(ctx context.Context, options *ListKeysOptions) (*ListKeysResponse, error)
- func (c *Client) ListModelEndpoints(ctx context.Context, author, slug string) (*ModelEndpointsResponse, error)
- func (c *Client) ListModels(ctx context.Context, opts *ListModelsOptions) (*ModelsResponse, error)
- func (c *Client) ListProviders(ctx context.Context) (*ProvidersResponse, error)
- func (c *Client) UpdateKey(ctx context.Context, hash string, request *UpdateKeyRequest) (*UpdateKeyResponse, error)
- type ClientOption
- func WithAPIKey(apiKey string) ClientOption
- func WithAppName(appName string) ClientOption
- func WithBaseURL(baseURL string) ClientOption
- func WithDefaultModel(model string) ClientOption
- func WithHTTPClient(httpClient *http.Client) ClientOption
- func WithHeader(key, value string) ClientOption
- func WithReferer(referer string) ClientOption
- func WithRetry(maxRetries int, retryDelay time.Duration) ClientOption
- func WithTimeout(timeout time.Duration) ClientOption
- type CompletionChoice
- type CompletionOption
- func WithCompletionAllowFallbacks(allow bool) CompletionOption
- func WithCompletionBestOf(bestOf int) CompletionOption
- func WithCompletionDataCollection(policy string) CompletionOption
- func WithCompletionEcho(echo bool) CompletionOption
- func WithCompletionFloorPrice() CompletionOption
- func WithCompletionIgnoreProviders(providers ...string) CompletionOption
- func WithCompletionJSONMode() CompletionOption
- func WithCompletionJSONSchema(name string, strict bool, schema map[string]interface{}) CompletionOption
- func WithCompletionLogProbs(logProbs int) CompletionOption
- func WithCompletionMaxPrice(maxPrice MaxPrice) CompletionOption
- func WithCompletionMaxTokens(maxTokens int) CompletionOption
- func WithCompletionMetadata(metadata map[string]interface{}) CompletionOption
- func WithCompletionModel(model string) CompletionOption
- func WithCompletionModels(models ...string) CompletionOption
- func WithCompletionN(n int) CompletionOption
- func WithCompletionNitro() CompletionOption
- func WithCompletionOnlyProviders(providers ...string) CompletionOption
- func WithCompletionPlugins(plugins ...Plugin) CompletionOption
- func WithCompletionProvider(provider Provider) CompletionOption
- func WithCompletionProviderOrder(providers ...string) CompletionOption
- func WithCompletionProviderSort(sort string) CompletionOption
- func WithCompletionQuantizations(quantizations ...string) CompletionOption
- func WithCompletionRequireParameters(require bool) CompletionOption
- func WithCompletionResponseFormat(format ResponseFormat) CompletionOption
- func WithCompletionRoute(route string) CompletionOption
- func WithCompletionStop(stop ...string) CompletionOption
- func WithCompletionSuffix(suffix string) CompletionOption
- func WithCompletionTemperature(temperature float64) CompletionOption
- func WithCompletionTopP(topP float64) CompletionOption
- func WithCompletionTransforms(transforms ...string) CompletionOption
- func WithCompletionWebSearchOptions(options *WebSearchOptions) CompletionOption
- func WithCompletionZDR(enabled bool) CompletionOption
- type CompletionRequest
- type CompletionResponse
- type CompletionStream
- type ContentBuilder
- func (cb *ContentBuilder) AddAudio(audioData string, format string) *ContentBuilder
- func (cb *ContentBuilder) AddBase64Audio(audioPath string) (*ContentBuilder, error)
- func (cb *ContentBuilder) AddBase64PDF(pdfPath string, filename string) (*ContentBuilder, error)
- func (cb *ContentBuilder) AddFile(filename string, fileData string) *ContentBuilder
- func (cb *ContentBuilder) AddImage(imageURL string) *ContentBuilder
- func (cb *ContentBuilder) AddImageWithDetail(imageURL string, detail string) *ContentBuilder
- func (cb *ContentBuilder) AddPDF(pdfURL string, filename string) *ContentBuilder
- func (cb *ContentBuilder) AddText(text string) *ContentBuilder
- func (cb *ContentBuilder) Build() []ContentPart
- func (cb *ContentBuilder) BuildMessage(role string) Message
- type ContentPart
- type CreateKeyRequest
- type CreateKeyResponse
- type CreditsData
- type CreditsResponse
- type DeleteKeyData
- type DeleteKeyResponse
- type EmbeddingContentPart
- type EmbeddingData
- type EmbeddingImageURL
- type EmbeddingMultimodalInput
- type EmbeddingOption
- func WithEmbeddingAllowFallbacks(allow bool) EmbeddingOption
- func WithEmbeddingDataCollection(policy string) EmbeddingOption
- func WithEmbeddingDimensions(dimensions int) EmbeddingOption
- func WithEmbeddingEncodingFormat(format string) EmbeddingOption
- func WithEmbeddingIgnoreProviders(providers ...string) EmbeddingOption
- func WithEmbeddingInputType(inputType string) EmbeddingOption
- func WithEmbeddingOnlyProviders(providers ...string) EmbeddingOption
- func WithEmbeddingProvider(provider Provider) EmbeddingOption
- func WithEmbeddingProviderOrder(providers ...string) EmbeddingOption
- func WithEmbeddingProviderSort(sort string) EmbeddingOption
- func WithEmbeddingUser(user string) EmbeddingOption
- type EmbeddingRequest
- type EmbeddingResponse
- type EmbeddingUsage
- type EmbeddingsModelsResponse
- type ErrorResponse
- type File
- type FileAnnotation
- type Function
- type FunctionCall
- type GetKeyByHashResponse
- type ImageURL
- type InputAudio
- type JSONSchema
- type KeyData
- type KeyRateLimit
- type KeyResponse
- type ListKeysOptions
- type ListKeysResponse
- type ListModelsOptions
- type LogProbContent
- type LogProbs
- type MaxPrice
- type Message
- func CreateAssistantMessage(content string) Message
- func CreateChatMessage(role string, content string) Message
- func CreateMultiModalMessage(role string, text string, imageURL string) Message
- func CreateSystemMessage(content string) Message
- func CreateToolMessage(content string, toolCallID string) Message
- func CreateUserMessage(content string) Message
- func CreateUserMessageWithAudio(text string, audioData string, format string) Message
- func CreateUserMessageWithBase64Audio(text string, audioPath string) (Message, error)
- func CreateUserMessageWithBase64Image(text string, imagePath string) (Message, error)
- func CreateUserMessageWithBase64Images(text string, imagePaths ...string) (Message, error)
- func CreateUserMessageWithBase64PDF(text string, pdfPath string, filename string) (Message, error)
- func CreateUserMessageWithFiles(text string, files []File) Message
- func CreateUserMessageWithImage(text string, imageURL string) Message
- func CreateUserMessageWithImageDetail(text string, imageURL string, detail string) Message
- func CreateUserMessageWithImages(text string, imageURLs ...string) Message
- func CreateUserMessageWithPDF(text string, pdfURL string, filename string) Message
- type MessageContent
- type Model
- type ModelArchitecture
- type ModelDefaultParameters
- type ModelEndpoint
- type ModelEndpointPricing
- type ModelEndpointsArchitecture
- type ModelEndpointsData
- type ModelEndpointsResponse
- type ModelPerRequestLimits
- type ModelPricing
- type ModelTopProvider
- type ModelsResponse
- type PDFParserConfig
- type Plugin
- type Provider
- type ProviderInfo
- type ProvidersResponse
- type RateLimiter
- type RequestConfig
- type RequestError
- type RequestWithProvider
- type ResponseFormat
- type RetryConfig
- type Stream
- type StreamError
- type StreamEvent
- type Tool
- type ToolCall
- type TopLogProb
- type URLCitation
- type UpdateKeyRequest
- type UpdateKeyResponse
- type Usage
- type ValidationError
- type WebSearchContextSize
- type WebSearchEngine
- type WebSearchOptions
Constants ¶
This section is empty.
Variables ¶
var ErrNoAPIKey = &ValidationError{Field: "apiKey", Message: "API key is required"}
ErrNoAPIKey is returned when no API key is provided.
var ErrNoMessages = &ValidationError{Field: "messages", Message: "at least one message is required"}
ErrNoMessages is returned when no messages are provided for chat completion.
var ErrNoModel = &ValidationError{Field: "model", Message: "model is required"}
ErrNoModel is returned when no model is specified.
var ErrNoPrompt = &ValidationError{Field: "prompt", Message: "prompt is required"}
ErrNoPrompt is returned when no prompt is provided for completion.
Functions ¶
func ConcatenateChatStreamResponses ¶
func ConcatenateChatStreamResponses(responses []ChatCompletionResponse) string
Helper function to concatenate streaming chat responses.
func ConcatenateCompletionStreamResponses ¶
func ConcatenateCompletionStreamResponses(responses []CompletionResponse) string
Helper function to concatenate streaming completion responses.
func DefaultWebSearchPrompt ¶
DefaultWebSearchPrompt returns the default search prompt template. The date should be substituted with the current date when used.
func EncodeAudioBytesToBase64 ¶ added in v1.1.0
EncodeAudioBytesToBase64 encodes audio bytes to base64. The format should be one of: "wav", "mp3"
func EncodeAudioToBase64 ¶ added in v1.1.0
EncodeAudioToBase64 reads an audio file and encodes it to base64. It automatically detects the audio format based on the file extension. Supported formats: wav, mp3 Note: Audio must be base64-encoded; direct URLs are not supported.
func EncodeImageBytesToBase64 ¶ added in v1.1.0
EncodeImageBytesToBase64 encodes image bytes to a base64 data URL. The contentType should be one of: "image/png", "image/jpeg", "image/webp", "image/gif"
func EncodeImageToBase64 ¶ added in v1.1.0
EncodeImageToBase64 reads an image file and encodes it to a base64 data URL. It automatically detects the image format based on the file extension. Supported formats: png, jpg, jpeg, webp, gif
func EncodePDFBytesToBase64 ¶ added in v1.1.0
EncodePDFBytesToBase64 encodes PDF bytes to a base64 data URL.
func EncodePDFToBase64 ¶ added in v1.1.0
EncodePDFToBase64 reads a PDF file and encodes it to a base64 data URL.
func RetryWithBackoff ¶
func RetryWithBackoff(ctx context.Context, config *RetryConfig, fn func() error) error
RetryWithBackoff executes a function with exponential backoff retry logic.
func WithOnlineModel ¶
WithOnlineModel appends ":online" to a model name to enable web search. This is a shortcut for using the web plugin.
Types ¶
type APIError ¶
type APIError struct {
Message string `json:"message"`
Type string `json:"type"`
Code string `json:"code,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
APIError represents the error details in an error response.
type APIKey ¶
type APIKey struct {
Name string `json:"name"`
Label string `json:"label"`
Limit float64 `json:"limit"`
Disabled bool `json:"disabled"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Hash string `json:"hash"`
}
APIKey represents an API key in the list keys response.
type ActivityData ¶
type ActivityData struct {
Date string `json:"date"`
Model string `json:"model"`
ModelPermaslug string `json:"model_permaslug"`
EndpointID string `json:"endpoint_id"`
ProviderName string `json:"provider_name"`
Usage float64 `json:"usage"`
BYOKUsageInference float64 `json:"byok_usage_inference"`
Requests float64 `json:"requests"`
PromptTokens float64 `json:"prompt_tokens"`
CompletionTokens float64 `json:"completion_tokens"`
ReasoningTokens float64 `json:"reasoning_tokens"`
}
ActivityData represents daily user activity data grouped by model endpoint.
type ActivityOptions ¶
type ActivityOptions struct {
// Date filters by a single UTC date in the last 30 days (YYYY-MM-DD format).
// Example: "2024-01-15"
// Note: The API returns dates with timestamps (e.g., "2024-01-15 00:00:00") but expects
// the filter parameter in YYYY-MM-DD format.
Date string
}
ActivityOptions contains optional parameters for retrieving activity data.
type ActivityResponse ¶
type ActivityResponse struct {
Data []ActivityData `json:"data"`
}
ActivityResponse represents the response from the activity endpoint.
type Annotation ¶
type Annotation struct {
// Type of annotation (e.g., "url_citation", "file")
Type string `json:"type"`
// URLCitation contains details for URL citation annotations
URLCitation *URLCitation `json:"url_citation,omitempty"`
// FileAnnotation contains details for file annotations (parsed file metadata)
FileAnnotation *FileAnnotation `json:"file,omitempty"`
}
Annotation represents an annotation in a message response.
type ChatCompletionOption ¶
type ChatCompletionOption func(*ChatCompletionRequest)
ChatCompletionOption is a functional option for chat completion requests.
func WithAllowFallbacks ¶
func WithAllowFallbacks(allow bool) ChatCompletionOption
WithAllowFallbacks controls whether to allow backup providers. When set to false, the request will fail if primary providers are unavailable.
func WithDataCollection ¶
func WithDataCollection(policy string) ChatCompletionOption
WithDataCollection controls whether to use providers that may store data. Use "allow" to allow data collection, "deny" to prevent it.
func WithFloorPrice ¶
func WithFloorPrice() ChatCompletionOption
WithFloorPrice is a shortcut for sorting by price. Equivalent to WithProviderSort("price").
func WithFrequencyPenalty ¶
func WithFrequencyPenalty(penalty float64) ChatCompletionOption
WithFrequencyPenalty sets the frequency penalty.
func WithIgnoreProviders ¶
func WithIgnoreProviders(providers ...string) ChatCompletionOption
WithIgnoreProviders specifies providers to skip for this request.
func WithJSONMode ¶
func WithJSONMode() ChatCompletionOption
WithJSONMode sets the response format to return JSON without a specific schema. Note: This is less strict than WithJSONSchema and doesn't enforce a specific structure.
func WithJSONSchema ¶
func WithJSONSchema(name string, strict bool, schema map[string]interface{}) ChatCompletionOption
WithJSONSchema sets the response format to use a specific JSON schema for structured outputs. This ensures the model response follows the provided schema exactly.
func WithLogProbs ¶
func WithLogProbs(topLogProbs int) ChatCompletionOption
WithLogProbs enables log probabilities in the response.
func WithMaxPrice ¶
func WithMaxPrice(maxPrice MaxPrice) ChatCompletionOption
WithMaxPrice sets maximum pricing constraints for the request.
func WithMaxTokens ¶
func WithMaxTokens(maxTokens int) ChatCompletionOption
WithMaxTokens sets the max_tokens parameter.
func WithMessages ¶
func WithMessages(messages []Message) ChatCompletionOption
WithMessages sets the messages for the chat completion request.
func WithMetadata ¶
func WithMetadata(metadata map[string]interface{}) ChatCompletionOption
WithMetadata sets metadata headers for the request.
func WithModel ¶
func WithModel(model string) ChatCompletionOption
WithModel sets the model for the request.
func WithModels ¶
func WithModels(models ...string) ChatCompletionOption
WithModels sets the models for fallback.
func WithNitro ¶
func WithNitro() ChatCompletionOption
WithNitro is a shortcut for sorting by throughput. Equivalent to WithProviderSort("throughput").
func WithOnlyProviders ¶
func WithOnlyProviders(providers ...string) ChatCompletionOption
WithOnlyProviders restricts the request to only use specified providers.
func WithParallelToolCalls ¶
func WithParallelToolCalls(parallel *bool) ChatCompletionOption
WithParallelToolCalls controls whether multiple tools can be called in parallel. Default is true for most models that support tool calling.
func WithPlugins ¶
func WithPlugins(plugins ...Plugin) ChatCompletionOption
WithPlugins adds plugin configurations to the request.
func WithPresencePenalty ¶
func WithPresencePenalty(penalty float64) ChatCompletionOption
WithPresencePenalty sets the presence penalty.
func WithProvider ¶
func WithProvider(provider Provider) ChatCompletionOption
WithProvider sets provider-specific parameters.
func WithProviderOrder ¶
func WithProviderOrder(providers ...string) ChatCompletionOption
WithProviderOrder sets the order of providers to try. The router will prioritize providers in this list, and in this order.
func WithProviderSort ¶
func WithProviderSort(sort string) ChatCompletionOption
WithProviderSort sorts providers by the specified attribute. Valid values: "price" (lowest cost), "throughput" (highest), "latency" (lowest)
func WithQuantizations ¶
func WithQuantizations(quantizations ...string) ChatCompletionOption
WithQuantizations filters providers by quantization levels. Valid values: "int4", "int8", "fp4", "fp6", "fp8", "fp16", "bf16", "fp32", "unknown"
func WithRepetitionPenalty ¶
func WithRepetitionPenalty(penalty float64) ChatCompletionOption
WithRepetitionPenalty sets the repetition penalty.
func WithRequireParameters ¶
func WithRequireParameters(require bool) ChatCompletionOption
WithRequireParameters only routes to providers that support all request parameters.
func WithResponseFormat ¶
func WithResponseFormat(format ResponseFormat) ChatCompletionOption
WithResponseFormat sets the response format.
func WithRoute ¶
func WithRoute(route string) ChatCompletionOption
WithRoute sets the routing preference.
func WithStop ¶
func WithStop(stop ...string) ChatCompletionOption
WithStop sets the stop sequences.
func WithTemperature ¶
func WithTemperature(temperature float64) ChatCompletionOption
WithTemperature sets the temperature parameter.
func WithToolChoice ¶
func WithToolChoice(toolChoice interface{}) ChatCompletionOption
WithToolChoice sets the tool choice strategy.
func WithTools ¶
func WithTools(tools ...Tool) ChatCompletionOption
WithTools sets the available tools/functions.
func WithTransforms ¶
func WithTransforms(transforms ...string) ChatCompletionOption
WithTransforms sets the transforms to apply.
func WithWebSearchOptions ¶
func WithWebSearchOptions(options *WebSearchOptions) ChatCompletionOption
WithWebSearchOptions sets web search options for the request.
func WithZDR ¶
func WithZDR(enabled bool) ChatCompletionOption
WithZDR enables Zero Data Retention for the request. This ensures the request is only routed to endpoints with Zero Data Retention policy.
type ChatCompletionRequest ¶
type ChatCompletionRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
// Optional parameters
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
PresencePenalty *float64 `json:"presence_penalty,omitempty"`
RepetitionPenalty *float64 `json:"repetition_penalty,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
MinP *float64 `json:"min_p,omitempty"`
TopA *float64 `json:"top_a,omitempty"`
Seed *int `json:"seed,omitempty"`
Stop []string `json:"stop,omitempty"`
Stream bool `json:"stream,omitempty"`
LogProbs *bool `json:"logprobs,omitempty"`
TopLogProbs *int `json:"top_logprobs,omitempty"`
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
Tools []Tool `json:"tools,omitempty"`
ToolChoice interface{} `json:"tool_choice,omitempty"`
ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"`
Provider *Provider `json:"provider,omitempty"`
Transforms []string `json:"transforms,omitempty"`
Models []string `json:"models,omitempty"`
Route string `json:"route,omitempty"`
Plugins []Plugin `json:"plugins,omitempty"`
WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty"`
Metadata map[string]interface{} `json:"-"` // Used for headers
}
ChatCompletionRequest represents a chat completion request to the OpenRouter API.
func (*ChatCompletionRequest) GetMetadata ¶
func (r *ChatCompletionRequest) GetMetadata() map[string]interface{}
GetMetadata helper methods for request types
type ChatCompletionResponse ¶
type ChatCompletionResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []Choice `json:"choices"`
Usage Usage `json:"usage"`
SystemFingerprint string `json:"system_fingerprint,omitempty"`
}
ChatCompletionResponse represents a chat completion response from the OpenRouter API.
type ChatStream ¶
type ChatStream = Stream[ChatCompletionResponse]
ChatStream represents a streaming chat completion response.
type Choice ¶
type Choice struct {
Index int `json:"index"`
Message Message `json:"message"`
FinishReason string `json:"finish_reason"`
LogProbs *LogProbs `json:"logprobs,omitempty"`
Delta *Message `json:"delta,omitempty"` // For streaming
}
Choice represents a choice in the chat completion response.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the main client for interacting with the OpenRouter API.
func NewClient ¶
func NewClient(opts ...ClientOption) *Client
NewClient creates a new OpenRouter API client. The API key can be provided either as the first argument (for backwards compatibility) or via WithAPIKey option. If both are provided, the option takes precedence.
func (*Client) ChatComplete ¶
func (c *Client) ChatComplete(ctx context.Context, messages []Message, opts ...ChatCompletionOption) (*ChatCompletionResponse, error)
ChatComplete sends a chat completion request to the OpenRouter API.
func (*Client) ChatCompleteStream ¶
func (c *Client) ChatCompleteStream(ctx context.Context, messages []Message, opts ...ChatCompletionOption) (*ChatStream, error)
ChatCompleteStream sends a streaming chat completion request to the OpenRouter API. This method returns a stream that can be used to receive events as they arrive.
func (*Client) Complete ¶
func (c *Client) Complete(ctx context.Context, prompt string, opts ...CompletionOption) (*CompletionResponse, error)
Complete sends a legacy completion request to the OpenRouter API.
func (*Client) CompleteStream ¶
func (c *Client) CompleteStream(ctx context.Context, prompt string, opts ...CompletionOption) (*CompletionStream, error)
CompleteStream sends a streaming completion request to the OpenRouter API. This method returns a stream that can be used to receive events as they arrive.
func (*Client) CompleteWithContext ¶
func (c *Client) CompleteWithContext(ctx context.Context, contextPrompt, userPrompt string, opts ...CompletionOption) (*CompletionResponse, error)
CompleteWithContext is a convenience method that combines prompt completion with context.
func (*Client) CompleteWithExamples ¶
func (c *Client) CompleteWithExamples(ctx context.Context, instruction string, examples []string, prompt string, opts ...CompletionOption) (*CompletionResponse, error)
CompleteWithExamples is a convenience method for few-shot prompting.
func (*Client) CreateEmbedding ¶ added in v1.2.0
func (c *Client) CreateEmbedding(ctx context.Context, input interface{}, model string, opts ...EmbeddingOption) (*EmbeddingResponse, error)
CreateEmbedding sends an embedding request to the OpenRouter API. The input can be a string or []string for text embeddings.
func (*Client) CreateEmbeddings ¶ added in v1.2.0
func (c *Client) CreateEmbeddings(ctx context.Context, inputs []string, model string, opts ...EmbeddingOption) (*EmbeddingResponse, error)
CreateEmbeddings is an alias for CreateEmbedding that emphasizes batch embedding. The input should be a []string for batch text embeddings.
func (*Client) CreateKey ¶
func (c *Client) CreateKey(ctx context.Context, request *CreateKeyRequest) (*CreateKeyResponse, error)
CreateKey creates a new API key with the specified name and optional limit. Requires a Provisioning API key (not a regular inference API key).
IMPORTANT: The response contains the actual API key value in the Key field. This is the ONLY time the key value will be returned. Store it securely!
Example:
ctx := context.Background()
limit := 100.0
includeBYOK := true
keyResp, err := client.CreateKey(ctx, &openrouter.CreateKeyRequest{
Name: "Production API Key",
Limit: &limit,
IncludeBYOKInLimit: &includeBYOK,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("New API Key: %s\n", keyResp.Key) // SAVE THIS!
fmt.Printf("Label: %s\n", keyResp.Data.Label)
fmt.Printf("Limit: $%.2f\n", keyResp.Data.Limit)
func (*Client) DeleteKey ¶
DeleteKey deletes an API key by its hash. Requires a Provisioning API key (not a regular inference API key).
WARNING: This operation is irreversible! The API key will be permanently deleted.
Example:
ctx := context.Background()
// Get the hash from ListKeys or from key creation
hash := "abc123hash"
result, err := client.DeleteKey(ctx, hash)
if err != nil {
log.Fatal(err)
}
if result.Data.Success {
fmt.Println("API key successfully deleted")
}
func (*Client) GetActivity ¶
func (c *Client) GetActivity(ctx context.Context, opts *ActivityOptions) (*ActivityResponse, error)
GetActivity retrieves daily user activity data grouped by model endpoint for the last 30 (completed) UTC days.
If ingesting on a schedule, it is recommended to wait for ~30 minutes after the UTC boundary to request the previous day, because events are aggregated by request start time, and some reasoning models may take a few minutes to complete.
Note: A provisioning key is required to access this endpoint, to ensure that your historic usage is not accessible to just anyone in your org with an inference API key.
Example:
ctx := context.Background()
// Get all activity
activity, err := client.GetActivity(ctx, nil)
if err != nil {
log.Fatal(err)
}
// Filter by date
activity, err := client.GetActivity(ctx, &openrouter.ActivityOptions{
Date: "2024-01-15",
})
if err != nil {
log.Fatal(err)
}
for _, data := range activity.Data {
fmt.Printf("%s - %s: %.2f requests, $%.4f usage\n",
data.Date, data.Model, data.Requests, data.Usage)
}
func (*Client) GetCredits ¶
func (c *Client) GetCredits(ctx context.Context) (*CreditsResponse, error)
GetCredits retrieves the total credits purchased and used for the authenticated user.
Example:
ctx := context.Background()
credits, err := client.GetCredits(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Credits: %.2f, Usage: %.2f, Remaining: %.2f\n",
credits.Data.TotalCredits,
credits.Data.TotalUsage,
credits.Data.TotalCredits - credits.Data.TotalUsage)
func (*Client) GetKey ¶
func (c *Client) GetKey(ctx context.Context) (*KeyResponse, error)
GetKey retrieves information about the current API key including usage, limits, and rate limit information for the authenticated user.
Example:
ctx := context.Background()
keyInfo, err := client.GetKey(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Label: %s\n", keyInfo.Data.Label)
if keyInfo.Data.Limit != nil {
fmt.Printf("Limit: $%.2f\n", *keyInfo.Data.Limit)
}
fmt.Printf("Usage: $%.4f\n", keyInfo.Data.Usage)
if keyInfo.Data.LimitRemaining != nil {
fmt.Printf("Remaining: $%.4f\n", *keyInfo.Data.LimitRemaining)
}
func (*Client) GetKeyByHash ¶
GetKeyByHash retrieves details about a specific API key by its hash. Requires a Provisioning API key (not a regular inference API key).
Example:
ctx := context.Background()
// Get the hash from ListKeys or from key creation
hash := "abc123hash"
keyDetails, err := client.GetKeyByHash(ctx, hash)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Label: %s\n", keyDetails.Data.Label)
fmt.Printf("Limit: $%.2f\n", keyDetails.Data.Limit)
fmt.Printf("Disabled: %v\n", keyDetails.Data.Disabled)
func (*Client) ListEmbeddingsModels ¶ added in v1.2.0
func (c *Client) ListEmbeddingsModels(ctx context.Context) (*EmbeddingsModelsResponse, error)
ListEmbeddingsModels retrieves a list of available embedding models.
func (*Client) ListKeys ¶
func (c *Client) ListKeys(ctx context.Context, options *ListKeysOptions) (*ListKeysResponse, error)
ListKeys returns a list of all API keys associated with the account. Requires a Provisioning API key (not a regular inference API key).
Example:
ctx := context.Background()
keys, err := client.ListKeys(ctx, nil)
if err != nil {
log.Fatal(err)
}
for _, key := range keys.Data {
fmt.Printf("Label: %s, Disabled: %v\n", key.Label, key.Disabled)
}
With options:
offset := 10
includeDisabled := true
keys, err := client.ListKeys(ctx, &openrouter.ListKeysOptions{
Offset: &offset,
IncludeDisabled: &includeDisabled,
})
func (*Client) ListModelEndpoints ¶
func (c *Client) ListModelEndpoints(ctx context.Context, author, slug string) (*ModelEndpointsResponse, error)
ListModelEndpoints retrieves the list of endpoints for a specific model. The model is specified by its author and slug (e.g., author="openai", slug="gpt-4"). This endpoint provides detailed information about each provider offering the model, including pricing, context length, supported parameters, and uptime statistics.
func (*Client) ListModels ¶
func (c *Client) ListModels(ctx context.Context, opts *ListModelsOptions) (*ModelsResponse, error)
ListModels retrieves a list of models available through the OpenRouter API. Note: supported_parameters is a union of all parameters supported by all providers for each model. There may not be a single provider which offers all of the listed parameters for a model.
func (*Client) ListProviders ¶
func (c *Client) ListProviders(ctx context.Context) (*ProvidersResponse, error)
ListProviders retrieves a list of all providers available through the OpenRouter API. Returns provider information including name, slug, and policy URLs.
Example:
ctx := context.Background()
providers, err := client.ListProviders(ctx)
if err != nil {
log.Fatal(err)
}
for _, provider := range providers.Data {
fmt.Printf("%s (%s)\n", provider.Name, provider.Slug)
}
func (*Client) UpdateKey ¶
func (c *Client) UpdateKey(ctx context.Context, hash string, request *UpdateKeyRequest) (*UpdateKeyResponse, error)
UpdateKey updates an existing API key by its hash. Requires a Provisioning API key (not a regular inference API key).
All fields in the request are optional - only include the fields you want to update.
Example:
ctx := context.Background()
hash := "abc123hash"
// Update just the name
newName := "Updated Key Name"
result, err := client.UpdateKey(ctx, hash, &openrouter.UpdateKeyRequest{
Name: &newName,
})
// Disable a key
disabled := true
result, err := client.UpdateKey(ctx, hash, &openrouter.UpdateKeyRequest{
Disabled: &disabled,
})
// Update limit
newLimit := 200.0
result, err := client.UpdateKey(ctx, hash, &openrouter.UpdateKeyRequest{
Limit: &newLimit,
})
type ClientOption ¶
type ClientOption func(*Client)
ClientOption is a functional option for configuring the Client.
func WithAPIKey ¶
func WithAPIKey(apiKey string) ClientOption
WithAPIKey sets the API key for the client.
func WithAppName ¶
func WithAppName(appName string) ClientOption
WithAppName sets the X-Title header for requests.
func WithBaseURL ¶
func WithBaseURL(baseURL string) ClientOption
WithBaseURL sets a custom base URL for the API.
func WithDefaultModel ¶
func WithDefaultModel(model string) ClientOption
WithDefaultModel sets a default model to use for requests.
func WithHTTPClient ¶
func WithHTTPClient(httpClient *http.Client) ClientOption
WithHTTPClient sets a custom HTTP client.
func WithHeader ¶
func WithHeader(key, value string) ClientOption
WithHeader adds a custom header to all requests.
func WithReferer ¶
func WithReferer(referer string) ClientOption
WithReferer sets the HTTP-Referer header for requests.
func WithRetry ¶
func WithRetry(maxRetries int, retryDelay time.Duration) ClientOption
WithRetry configures retry behavior.
func WithTimeout ¶
func WithTimeout(timeout time.Duration) ClientOption
WithTimeout sets the HTTP client timeout.
type CompletionChoice ¶
type CompletionChoice struct {
Index int `json:"index"`
Text string `json:"text"`
FinishReason string `json:"finish_reason"`
LogProbs *LogProbs `json:"logprobs,omitempty"`
}
CompletionChoice represents a choice in the legacy completion response.
type CompletionOption ¶
type CompletionOption func(*CompletionRequest)
CompletionOption is a functional option for completion requests.
func WithCompletionAllowFallbacks ¶
func WithCompletionAllowFallbacks(allow bool) CompletionOption
WithCompletionAllowFallbacks controls whether to allow backup providers for completion requests.
func WithCompletionBestOf ¶
func WithCompletionBestOf(bestOf int) CompletionOption
WithCompletionBestOf sets the number of completions to generate server-side.
func WithCompletionDataCollection ¶
func WithCompletionDataCollection(policy string) CompletionOption
WithCompletionDataCollection controls whether to use providers that may store data.
func WithCompletionEcho ¶
func WithCompletionEcho(echo bool) CompletionOption
WithCompletionEcho enables echoing the prompt in the response.
func WithCompletionFloorPrice ¶
func WithCompletionFloorPrice() CompletionOption
WithCompletionFloorPrice is a shortcut for sorting by price for completion requests.
func WithCompletionIgnoreProviders ¶
func WithCompletionIgnoreProviders(providers ...string) CompletionOption
WithCompletionIgnoreProviders specifies providers to skip for this request.
func WithCompletionJSONMode ¶
func WithCompletionJSONMode() CompletionOption
WithCompletionJSONMode sets the response format to return JSON for completion requests.
func WithCompletionJSONSchema ¶
func WithCompletionJSONSchema(name string, strict bool, schema map[string]interface{}) CompletionOption
WithCompletionJSONSchema sets the response format to use a specific JSON schema for completion requests.
func WithCompletionLogProbs ¶
func WithCompletionLogProbs(logProbs int) CompletionOption
WithCompletionLogProbs sets the number of log probabilities to return.
func WithCompletionMaxPrice ¶
func WithCompletionMaxPrice(maxPrice MaxPrice) CompletionOption
WithCompletionMaxPrice sets maximum pricing constraints for the completion request.
func WithCompletionMaxTokens ¶
func WithCompletionMaxTokens(maxTokens int) CompletionOption
WithCompletionMaxTokens sets the max_tokens for completion.
func WithCompletionMetadata ¶
func WithCompletionMetadata(metadata map[string]interface{}) CompletionOption
WithCompletionMetadata sets metadata headers for the completion request.
func WithCompletionModel ¶
func WithCompletionModel(model string) CompletionOption
WithCompletionModel sets the model for the completion request.
func WithCompletionModels ¶
func WithCompletionModels(models ...string) CompletionOption
WithCompletionModels sets the models for fallback in completion requests.
func WithCompletionN ¶
func WithCompletionN(n int) CompletionOption
WithCompletionN sets the number of completions to generate.
func WithCompletionNitro ¶
func WithCompletionNitro() CompletionOption
WithCompletionNitro is a shortcut for sorting by throughput for completion requests.
func WithCompletionOnlyProviders ¶
func WithCompletionOnlyProviders(providers ...string) CompletionOption
WithCompletionOnlyProviders restricts the request to only use specified providers.
func WithCompletionPlugins ¶
func WithCompletionPlugins(plugins ...Plugin) CompletionOption
WithCompletionPlugins adds plugin configurations to the completion request.
func WithCompletionProvider ¶
func WithCompletionProvider(provider Provider) CompletionOption
WithCompletionProvider sets provider-specific parameters for completion.
func WithCompletionProviderOrder ¶
func WithCompletionProviderOrder(providers ...string) CompletionOption
WithCompletionProviderOrder sets the order of providers to try for completion requests.
func WithCompletionProviderSort ¶
func WithCompletionProviderSort(sort string) CompletionOption
WithCompletionProviderSort sorts providers by the specified attribute.
func WithCompletionQuantizations ¶
func WithCompletionQuantizations(quantizations ...string) CompletionOption
WithCompletionQuantizations filters providers by quantization levels.
func WithCompletionRequireParameters ¶
func WithCompletionRequireParameters(require bool) CompletionOption
WithCompletionRequireParameters only routes to providers that support all request parameters.
func WithCompletionResponseFormat ¶
func WithCompletionResponseFormat(format ResponseFormat) CompletionOption
WithCompletionResponseFormat sets the response format for completion requests.
func WithCompletionRoute ¶
func WithCompletionRoute(route string) CompletionOption
WithCompletionRoute sets the routing preference for completion requests.
func WithCompletionStop ¶
func WithCompletionStop(stop ...string) CompletionOption
WithCompletionStop sets stop sequences for completion.
func WithCompletionSuffix ¶
func WithCompletionSuffix(suffix string) CompletionOption
WithCompletionSuffix sets the suffix to append after the completion.
func WithCompletionTemperature ¶
func WithCompletionTemperature(temperature float64) CompletionOption
WithCompletionTemperature sets the temperature for completion.
func WithCompletionTopP ¶
func WithCompletionTopP(topP float64) CompletionOption
WithCompletionTopP sets the top_p for completion.
func WithCompletionTransforms ¶
func WithCompletionTransforms(transforms ...string) CompletionOption
WithCompletionTransforms sets the transforms to apply to completion requests.
func WithCompletionWebSearchOptions ¶
func WithCompletionWebSearchOptions(options *WebSearchOptions) CompletionOption
WithCompletionWebSearchOptions sets web search options for the completion request.
func WithCompletionZDR ¶
func WithCompletionZDR(enabled bool) CompletionOption
WithCompletionZDR enables Zero Data Retention for the completion request. This ensures the request is only routed to endpoints with Zero Data Retention policy.
type CompletionRequest ¶
type CompletionRequest struct {
Model string `json:"model"`
Prompt string `json:"prompt"`
// Optional parameters
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"top_p,omitempty"`
TopK *int `json:"top_k,omitempty"`
FrequencyPenalty *float64 `json:"frequency_penalty,omitempty"`
PresencePenalty *float64 `json:"presence_penalty,omitempty"`
RepetitionPenalty *float64 `json:"repetition_penalty,omitempty"`
MaxTokens *int `json:"max_tokens,omitempty"`
MinP *float64 `json:"min_p,omitempty"`
TopA *float64 `json:"top_a,omitempty"`
Seed *int `json:"seed,omitempty"`
Stop []string `json:"stop,omitempty"`
Stream bool `json:"stream,omitempty"`
LogProbs *int `json:"logprobs,omitempty"`
Echo *bool `json:"echo,omitempty"`
N *int `json:"n,omitempty"`
BestOf *int `json:"best_of,omitempty"`
Suffix *string `json:"suffix,omitempty"`
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
Provider *Provider `json:"provider,omitempty"`
Transforms []string `json:"transforms,omitempty"`
Models []string `json:"models,omitempty"`
Route string `json:"route,omitempty"`
Plugins []Plugin `json:"plugins,omitempty"`
WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty"`
Metadata map[string]interface{} `json:"-"` // Used for headers
}
CompletionRequest represents a legacy completion request to the OpenRouter API.
func (*CompletionRequest) GetMetadata ¶
func (r *CompletionRequest) GetMetadata() map[string]interface{}
type CompletionResponse ¶
type CompletionResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int64 `json:"created"`
Model string `json:"model"`
Choices []CompletionChoice `json:"choices"`
Usage Usage `json:"usage"`
}
CompletionResponse represents a legacy completion response from the OpenRouter API.
type CompletionStream ¶
type CompletionStream = Stream[CompletionResponse]
CompletionStream represents a streaming completion response.
type ContentBuilder ¶ added in v1.1.0
type ContentBuilder struct {
// contains filtered or unexported fields
}
CreateContentParts is a helper to build custom content part arrays.
func NewContentBuilder ¶ added in v1.1.0
func NewContentBuilder() *ContentBuilder
NewContentBuilder creates a new content builder.
func (*ContentBuilder) AddAudio ¶ added in v1.1.0
func (cb *ContentBuilder) AddAudio(audioData string, format string) *ContentBuilder
AddAudio adds an audio input to the content builder. The audioData should be base64-encoded audio data. The format should be one of: "wav", "mp3"
func (*ContentBuilder) AddBase64Audio ¶ added in v1.1.0
func (cb *ContentBuilder) AddBase64Audio(audioPath string) (*ContentBuilder, error)
AddBase64Audio reads and encodes an audio file, then adds it to the content builder.
func (*ContentBuilder) AddBase64PDF ¶ added in v1.1.0
func (cb *ContentBuilder) AddBase64PDF(pdfPath string, filename string) (*ContentBuilder, error)
AddBase64PDF reads and encodes a PDF file, then adds it to the content builder.
func (*ContentBuilder) AddFile ¶ added in v1.1.0
func (cb *ContentBuilder) AddFile(filename string, fileData string) *ContentBuilder
AddFile adds a file to the content builder.
func (*ContentBuilder) AddImage ¶ added in v1.1.0
func (cb *ContentBuilder) AddImage(imageURL string) *ContentBuilder
AddImage adds an image content part.
func (*ContentBuilder) AddImageWithDetail ¶ added in v1.1.0
func (cb *ContentBuilder) AddImageWithDetail(imageURL string, detail string) *ContentBuilder
AddImageWithDetail adds an image content part with a detail level.
func (*ContentBuilder) AddPDF ¶ added in v1.1.0
func (cb *ContentBuilder) AddPDF(pdfURL string, filename string) *ContentBuilder
AddPDF adds a PDF file to the content builder. The pdfURL can be either a direct URL or a base64-encoded data URL.
func (*ContentBuilder) AddText ¶ added in v1.1.0
func (cb *ContentBuilder) AddText(text string) *ContentBuilder
AddText adds a text content part.
func (*ContentBuilder) Build ¶ added in v1.1.0
func (cb *ContentBuilder) Build() []ContentPart
Build returns the content parts array.
func (*ContentBuilder) BuildMessage ¶ added in v1.1.0
func (cb *ContentBuilder) BuildMessage(role string) Message
BuildMessage creates a message with the builder's content.
type ContentPart ¶
type ContentPart struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ImageURL *ImageURL `json:"image_url,omitempty"`
File *File `json:"file,omitempty"`
InputAudio *InputAudio `json:"input_audio,omitempty"`
}
ContentPart represents a part of message content (text, image, file, or audio).
type CreateKeyRequest ¶
type CreateKeyRequest struct {
// Name is the required name/label for the API key
Name string `json:"name"`
// Limit is the optional credit limit for the API key
Limit *float64 `json:"limit,omitempty"`
// IncludeBYOKInLimit controls whether BYOK usage counts toward the limit
IncludeBYOKInLimit *bool `json:"include_byok_in_limit,omitempty"`
}
CreateKeyRequest represents a request to create a new API key.
type CreateKeyResponse ¶
type CreateKeyResponse struct {
Data APIKey `json:"data"`
// Key contains the actual API key value (only returned on creation)
Key string `json:"key,omitempty"`
}
CreateKeyResponse represents the response from creating a new API key.
type CreditsData ¶
type CreditsData struct {
TotalCredits float64 `json:"total_credits"`
TotalUsage float64 `json:"total_usage"`
}
CreditsData contains credit balance information for the authenticated user.
type CreditsResponse ¶
type CreditsResponse struct {
Data CreditsData `json:"data"`
}
CreditsResponse represents the response from the credits endpoint.
type DeleteKeyData ¶
type DeleteKeyData struct {
Success bool `json:"success"`
}
DeleteKeyData contains the result of a delete operation.
type DeleteKeyResponse ¶
type DeleteKeyResponse struct {
Data DeleteKeyData `json:"data"`
}
DeleteKeyResponse represents the response from deleting an API key.
type EmbeddingContentPart ¶ added in v1.2.0
type EmbeddingContentPart struct {
// Type specifies the type of content ("text" or "image_url").
Type string `json:"type"`
// Text is the text content (when Type is "text").
Text string `json:"text,omitempty"`
// ImageURL contains the image URL (when Type is "image_url").
ImageURL *EmbeddingImageURL `json:"image_url,omitempty"`
}
EmbeddingContentPart represents a content part for multimodal embedding input.
type EmbeddingData ¶ added in v1.2.0
type EmbeddingData struct {
// Object is the object type, always "embedding".
Object string `json:"object"`
// Embedding is the embedding vector. Can be []float64 or base64 string depending on encoding_format.
Embedding interface{} `json:"embedding"`
// Index is the index of this embedding in the input list.
Index int `json:"index"`
}
EmbeddingData represents a single embedding in the response.
func (*EmbeddingData) GetEmbeddingBase64 ¶ added in v1.2.0
func (e *EmbeddingData) GetEmbeddingBase64() string
GetEmbeddingBase64 extracts the embedding as a base64 string from an EmbeddingData. Returns empty string if the embedding is not in base64 format.
func (*EmbeddingData) GetEmbeddingVector ¶ added in v1.2.0
func (e *EmbeddingData) GetEmbeddingVector() []float64
GetEmbeddingVector extracts the embedding vector as []float64 from an EmbeddingData. Returns nil if the embedding is not in float format or conversion fails.
type EmbeddingImageURL ¶ added in v1.2.0
type EmbeddingImageURL struct {
// URL is the image URL.
URL string `json:"url"`
}
EmbeddingImageURL represents an image URL for multimodal embedding input.
type EmbeddingMultimodalInput ¶ added in v1.2.0
type EmbeddingMultimodalInput struct {
// Content is the array of content parts.
Content []EmbeddingContentPart `json:"content"`
}
EmbeddingMultimodalInput represents multimodal input for embeddings.
type EmbeddingOption ¶ added in v1.2.0
type EmbeddingOption func(*EmbeddingRequest)
EmbeddingOption is a functional option for embedding requests.
func WithEmbeddingAllowFallbacks ¶ added in v1.2.0
func WithEmbeddingAllowFallbacks(allow bool) EmbeddingOption
WithEmbeddingAllowFallbacks controls whether to allow backup providers.
func WithEmbeddingDataCollection ¶ added in v1.2.0
func WithEmbeddingDataCollection(policy string) EmbeddingOption
WithEmbeddingDataCollection controls whether to use providers that may store data. Use "allow" to allow data collection, "deny" to prevent it.
func WithEmbeddingDimensions ¶ added in v1.2.0
func WithEmbeddingDimensions(dimensions int) EmbeddingOption
WithEmbeddingDimensions sets the number of dimensions for the output embeddings. Only supported by some models.
func WithEmbeddingEncodingFormat ¶ added in v1.2.0
func WithEmbeddingEncodingFormat(format string) EmbeddingOption
WithEmbeddingEncodingFormat sets the encoding format for the embeddings. Valid values are "float" (default) or "base64".
func WithEmbeddingIgnoreProviders ¶ added in v1.2.0
func WithEmbeddingIgnoreProviders(providers ...string) EmbeddingOption
WithEmbeddingIgnoreProviders specifies providers to skip for this request.
func WithEmbeddingInputType ¶ added in v1.2.0
func WithEmbeddingInputType(inputType string) EmbeddingOption
WithEmbeddingInputType sets the input type for the embeddings. Some models distinguish between document and query embeddings.
func WithEmbeddingOnlyProviders ¶ added in v1.2.0
func WithEmbeddingOnlyProviders(providers ...string) EmbeddingOption
WithEmbeddingOnlyProviders restricts the request to only use specified providers.
func WithEmbeddingProvider ¶ added in v1.2.0
func WithEmbeddingProvider(provider Provider) EmbeddingOption
WithEmbeddingProvider sets provider-specific routing parameters.
func WithEmbeddingProviderOrder ¶ added in v1.2.0
func WithEmbeddingProviderOrder(providers ...string) EmbeddingOption
WithEmbeddingProviderOrder sets the order of providers to try.
func WithEmbeddingProviderSort ¶ added in v1.2.0
func WithEmbeddingProviderSort(sort string) EmbeddingOption
WithEmbeddingProviderSort sorts providers by the specified attribute. Valid values: "price" (lowest cost), "throughput" (highest), "latency" (lowest)
func WithEmbeddingUser ¶ added in v1.2.0
func WithEmbeddingUser(user string) EmbeddingOption
WithEmbeddingUser sets an optional unique identifier for the end-user.
type EmbeddingRequest ¶ added in v1.2.0
type EmbeddingRequest struct {
// Input is the text or texts to embed. Can be a string, array of strings,
// array of integers, array of integer arrays, or array of multimodal content parts.
Input interface{} `json:"input"`
// Model specifies the embedding model to use (required).
Model string `json:"model"`
// EncodingFormat specifies the format for the returned embeddings ("float" or "base64").
EncodingFormat string `json:"encoding_format,omitempty"`
// Dimensions specifies the number of dimensions for the output embeddings.
Dimensions *int `json:"dimensions,omitempty"`
// User is an optional unique identifier for the end-user.
User string `json:"user,omitempty"`
// Provider contains provider-specific routing parameters.
Provider *Provider `json:"provider,omitempty"`
// InputType specifies the type of input (e.g., for search vs. document embeddings).
InputType string `json:"input_type,omitempty"`
}
EmbeddingRequest represents a request to create embeddings.
type EmbeddingResponse ¶ added in v1.2.0
type EmbeddingResponse struct {
// ID is the unique identifier for this embeddings request.
ID string `json:"id,omitempty"`
// Object is the object type, always "list".
Object string `json:"object"`
// Data contains the list of embedding objects.
Data []EmbeddingData `json:"data"`
// Model is the model used to generate the embeddings.
Model string `json:"model"`
// Usage contains token usage information for the request.
Usage *EmbeddingUsage `json:"usage,omitempty"`
}
EmbeddingResponse represents the response from an embeddings request.
type EmbeddingUsage ¶ added in v1.2.0
type EmbeddingUsage struct {
// PromptTokens is the number of tokens in the input.
PromptTokens int `json:"prompt_tokens"`
// TotalTokens is the total number of tokens used.
TotalTokens int `json:"total_tokens"`
// Cost is the cost of the request (if available).
Cost *float64 `json:"cost,omitempty"`
}
EmbeddingUsage contains token usage information for an embeddings request.
type EmbeddingsModelsResponse ¶ added in v1.2.0
type EmbeddingsModelsResponse struct {
Data []Model `json:"data"`
}
EmbeddingsModelsResponse represents the response from the list embeddings models endpoint.
type ErrorResponse ¶
type ErrorResponse struct {
Error APIError `json:"error"`
}
ErrorResponse represents an error response from the OpenRouter API.
type File ¶ added in v1.1.0
type File struct {
// Filename is the name of the file (e.g., "document.pdf")
Filename string `json:"filename"`
// FileData can be either a URL or a base64-encoded data URL
FileData string `json:"file_data"`
}
File represents a file attachment in the message content. Supports both URLs and base64-encoded data URLs.
type FileAnnotation ¶ added in v1.1.0
type FileAnnotation struct {
// Filename is the name of the file
Filename string `json:"filename"`
// ContentType is the MIME type of the file (e.g., "application/pdf")
ContentType string `json:"content_type,omitempty"`
// ParsedContent contains the extracted text/data from the file
ParsedContent string `json:"parsed_content,omitempty"`
// Metadata contains additional file information
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
FileAnnotation represents metadata about a parsed file. Can be sent back in subsequent requests to avoid re-parsing costs.
type Function ¶
type Function struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Parameters map[string]interface{} `json:"parameters,omitempty"`
}
Function represents a callable function.
type FunctionCall ¶
FunctionCall represents a function call made by the model.
type GetKeyByHashResponse ¶
type GetKeyByHashResponse struct {
Data APIKey `json:"data"`
}
GetKeyByHashResponse represents the response from getting an API key by hash.
type InputAudio ¶ added in v1.1.0
type InputAudio struct {
// Data is the base64-encoded audio data
Data string `json:"data"`
// Format specifies the audio format (e.g., "wav", "mp3")
Format string `json:"format"`
}
InputAudio represents an audio input in the message content. Audio files must be base64-encoded - direct URLs are not supported.
type JSONSchema ¶
type JSONSchema struct {
Name string `json:"name"`
Strict bool `json:"strict"`
Schema map[string]interface{} `json:"schema"`
}
JSONSchema defines the structure for structured output format.
type KeyData ¶
type KeyData struct {
Label string `json:"label"`
Limit *float64 `json:"limit"`
Usage float64 `json:"usage"`
IsFreeTier bool `json:"is_free_tier"`
LimitRemaining *float64 `json:"limit_remaining"`
IsProvisioningKey bool `json:"is_provisioning_key"`
RateLimit *KeyRateLimit `json:"rate_limit,omitempty"`
}
KeyData contains information about an API key.
type KeyRateLimit ¶
KeyRateLimit contains rate limit information for an API key.
type KeyResponse ¶
type KeyResponse struct {
Data KeyData `json:"data"`
}
KeyResponse represents the response from the get current API key endpoint.
type ListKeysOptions ¶
type ListKeysOptions struct {
// Offset for pagination
Offset *int `json:"offset,omitempty"`
// IncludeDisabled controls whether to include disabled API keys
IncludeDisabled *bool `json:"include_disabled,omitempty"`
}
ListKeysOptions contains optional parameters for listing API keys.
type ListKeysResponse ¶
type ListKeysResponse struct {
Data []APIKey `json:"data"`
}
ListKeysResponse represents the response from the list API keys endpoint.
type ListModelsOptions ¶
type ListModelsOptions struct {
// Category filters models by category (e.g. "programming"). Sorted from most to least used.
Category string
}
ListModelsOptions contains optional parameters for listing models.
type LogProbContent ¶
type LogProbContent struct {
Token string `json:"token"`
LogProb float64 `json:"logprob"`
Bytes []int `json:"bytes,omitempty"`
TopLogProbs []TopLogProb `json:"top_logprobs,omitempty"`
}
LogProbContent represents log probability content.
type LogProbs ¶
type LogProbs struct {
Content []LogProbContent `json:"content,omitempty"`
}
LogProbs represents log probability information.
type MaxPrice ¶
type MaxPrice struct {
// Prompt specifies max price per million prompt tokens
Prompt float64 `json:"prompt,omitempty"`
// Completion specifies max price per million completion tokens
Completion float64 `json:"completion,omitempty"`
// Request specifies max price per request (for providers with per-request pricing)
Request float64 `json:"request,omitempty"`
// Image specifies max price per image
Image float64 `json:"image,omitempty"`
}
MaxPrice represents maximum pricing constraints for a request.
type Message ¶
type Message struct {
Role string `json:"role"`
Content MessageContent `json:"content"`
Name string `json:"name,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
Annotations []Annotation `json:"annotations,omitempty"`
}
Message represents a message in the chat completion request.
func CreateAssistantMessage ¶
CreateAssistantMessage creates an assistant message.
func CreateChatMessage ¶
CreateChatMessage is a helper function to create a chat message.
func CreateMultiModalMessage ¶
CreateMultiModalMessage creates a message with text and image content.
func CreateSystemMessage ¶
CreateSystemMessage creates a system message.
func CreateToolMessage ¶
CreateToolMessage creates a tool message.
func CreateUserMessage ¶
CreateUserMessage creates a user message.
func CreateUserMessageWithAudio ¶ added in v1.1.0
CreateUserMessageWithAudio creates a user message with text and an audio input. The audioData should be base64-encoded audio data. The format should be one of: "wav", "mp3"
func CreateUserMessageWithBase64Audio ¶ added in v1.1.0
CreateUserMessageWithBase64Audio creates a user message with a base64-encoded audio file. This is a convenience function that combines EncodeAudioToBase64 and CreateUserMessageWithAudio.
func CreateUserMessageWithBase64Image ¶ added in v1.1.0
CreateUserMessageWithBase64Image creates a user message with a base64-encoded image. This is a convenience function that combines EncodeImageToBase64 and CreateUserMessageWithImage.
func CreateUserMessageWithBase64Images ¶ added in v1.1.0
CreateUserMessageWithBase64Images creates a user message with multiple base64-encoded images. This is a convenience function that combines EncodeImageToBase64 and CreateUserMessageWithImages.
func CreateUserMessageWithBase64PDF ¶ added in v1.1.0
CreateUserMessageWithBase64PDF creates a user message with a base64-encoded PDF. This is a convenience function that combines EncodePDFToBase64 and CreateUserMessageWithPDF.
func CreateUserMessageWithFiles ¶ added in v1.1.0
CreateUserMessageWithFiles creates a user message with text and multiple files. Files can be PDFs, images, or other supported file types.
func CreateUserMessageWithImage ¶ added in v1.1.0
CreateUserMessageWithImage creates a user message with text and a single image.
func CreateUserMessageWithImageDetail ¶ added in v1.1.0
CreateUserMessageWithImageDetail creates a user message with an image and detail level. The detail parameter can be "auto", "low", or "high". - "low" is faster and cheaper, suitable for understanding general content - "high" provides more detailed analysis at higher cost - "auto" lets the model decide based on image size (default)
func CreateUserMessageWithImages ¶ added in v1.1.0
CreateUserMessageWithImages creates a user message with text and multiple images.
func CreateUserMessageWithPDF ¶ added in v1.1.0
CreateUserMessageWithPDF creates a user message with text and a PDF file. The pdfURL can be either a direct URL to a publicly accessible PDF or a base64-encoded data URL (use EncodePDFToBase64 to encode local files).
type MessageContent ¶
type MessageContent interface{}
MessageContent can be either a string or an array of content parts.
type Model ¶
type Model struct {
ID string `json:"id"`
Name string `json:"name"`
CanonicalSlug *string `json:"canonical_slug"`
Created float64 `json:"created"`
Description string `json:"description"`
ContextLength *float64 `json:"context_length"`
HuggingFaceID *string `json:"hugging_face_id"`
Architecture ModelArchitecture `json:"architecture"`
TopProvider ModelTopProvider `json:"top_provider"`
PerRequestLimits *ModelPerRequestLimits `json:"per_request_limits"`
SupportedParameters []string `json:"supported_parameters,omitempty"`
DefaultParameters *ModelDefaultParameters `json:"default_parameters"`
Pricing ModelPricing `json:"pricing"`
}
Model represents a model available on OpenRouter.
type ModelArchitecture ¶
type ModelArchitecture struct {
InputModalities []string `json:"input_modalities"`
OutputModalities []string `json:"output_modalities"`
Tokenizer string `json:"tokenizer"`
InstructType *string `json:"instruct_type"`
}
ModelArchitecture contains information about a model's architecture.
type ModelDefaultParameters ¶
type ModelDefaultParameters struct {
Temperature *float64 `json:"temperature"`
TopP *float64 `json:"top_p"`
FrequencyPenalty *float64 `json:"frequency_penalty"`
}
ModelDefaultParameters contains default generation parameters for a model.
type ModelEndpoint ¶
type ModelEndpoint struct {
Name string `json:"name"`
ContextLength float64 `json:"context_length"`
Pricing ModelEndpointPricing `json:"pricing"`
ProviderName string `json:"provider_name"`
Quantization *string `json:"quantization"`
MaxCompletionTokens *float64 `json:"max_completion_tokens"`
MaxPromptTokens *float64 `json:"max_prompt_tokens"`
SupportedParameters []string `json:"supported_parameters"`
Status float64 `json:"status"`
UptimeLast30m *float64 `json:"uptime_last_30m"`
}
ModelEndpoint represents a single endpoint for a model.
type ModelEndpointPricing ¶
type ModelEndpointPricing struct {
Request string `json:"request"`
Image string `json:"image"`
Prompt string `json:"prompt"`
Completion string `json:"completion"`
}
ModelEndpointPricing contains pricing information for a specific endpoint.
type ModelEndpointsArchitecture ¶
type ModelEndpointsArchitecture struct {
Tokenizer *string `json:"tokenizer"`
InstructType *string `json:"instruct_type"`
InputModalities []string `json:"input_modalities"`
OutputModalities []string `json:"output_modalities"`
}
ModelEndpointsArchitecture contains architecture information for a model's endpoints.
type ModelEndpointsData ¶
type ModelEndpointsData struct {
ID string `json:"id"`
Name string `json:"name"`
Created float64 `json:"created"`
Description string `json:"description"`
Architecture ModelEndpointsArchitecture `json:"architecture"`
Endpoints []ModelEndpoint `json:"endpoints"`
}
ModelEndpointsData contains details about a model and its endpoints.
type ModelEndpointsResponse ¶
type ModelEndpointsResponse struct {
Data ModelEndpointsData `json:"data"`
}
ModelEndpointsResponse represents the response from the model endpoints endpoint.
type ModelPerRequestLimits ¶
type ModelPerRequestLimits struct {
}
ModelPerRequestLimits contains per-request limits for a model.
type ModelPricing ¶
type ModelPricing struct {
Prompt string `json:"prompt"`
Completion string `json:"completion"`
Image string `json:"image"`
Request string `json:"request"`
InputCacheRead *string `json:"input_cache_read"`
InputCacheWrite *string `json:"input_cache_write"`
WebSearch string `json:"web_search"`
InternalReasoning string `json:"internal_reasoning"`
}
ModelPricing contains pricing information for a model.
type ModelTopProvider ¶
type ModelTopProvider struct {
ContextLength *float64 `json:"context_length"`
MaxCompletionTokens *float64 `json:"max_completion_tokens"`
IsModerated bool `json:"is_moderated"`
}
ModelTopProvider contains information about the top provider for a model.
type ModelsResponse ¶
type ModelsResponse struct {
Data []Model `json:"data"`
}
ModelsResponse represents the response from the list models endpoint.
type PDFParserConfig ¶ added in v1.1.0
type PDFParserConfig struct {
// Engine specifies the PDF parsing engine to use.
// Options:
// - "pdf-text": Best for well-structured PDFs with clear text content (Free)
// - "mistral-ocr": Best for scanned documents or PDFs with images ($0.0004 per 1,000 pages)
// - "native": Only for models with native file support (charged as input tokens)
// If not specified, defaults to model's native support, then "pdf-text"
Engine string `json:"engine,omitempty"`
}
PDFParserConfig configures PDF file parsing behavior.
type Plugin ¶
type Plugin struct {
// ID is the plugin identifier (e.g., "web" for web search, "file-parser" for file parsing)
ID string `json:"id"`
// Engine specifies which search engine to use ("native", "exa", or undefined for auto)
Engine string `json:"engine,omitempty"`
// MaxResults specifies the maximum number of search results (defaults to 5)
MaxResults int `json:"max_results,omitempty"`
// SearchPrompt customizes the prompt used to attach search results
SearchPrompt string `json:"search_prompt,omitempty"`
// PDF contains configuration for PDF file parsing (when ID is "file-parser")
PDF *PDFParserConfig `json:"pdf,omitempty"`
}
Plugin represents a plugin configuration for enhancing model responses.
func CreateFileParserPlugin ¶ added in v1.1.0
CreateFileParserPlugin creates a file parser plugin configuration. The engine parameter can be:
- "pdf-text": Best for well-structured PDFs with clear text content (Free)
- "mistral-ocr": Best for scanned documents or PDFs with images ($0.0004 per 1,000 pages)
- "native": Only for models with native file support (charged as input tokens)
- "" (empty): Defaults to model's native support, then "pdf-text"
func NewWebPlugin ¶
func NewWebPlugin() Plugin
NewWebPlugin creates a new web search plugin configuration. By default, uses automatic engine selection and 5 max results.
func NewWebPluginWithOptions ¶
func NewWebPluginWithOptions(engine WebSearchEngine, maxResults int, searchPrompt string) Plugin
NewWebPluginWithOptions creates a web search plugin with custom options.
type Provider ¶
type Provider struct {
// Order specifies provider slugs to try in order (e.g. ["anthropic", "openai"])
Order []string `json:"order,omitempty"`
// RequireParameters only uses providers that support all parameters in the request
RequireParameters *bool `json:"require_parameters,omitempty"`
// DataCollection controls whether to use providers that may store data ("allow" or "deny")
DataCollection string `json:"data_collection,omitempty"`
// AllowFallbacks allows backup providers when the primary is unavailable
AllowFallbacks *bool `json:"allow_fallbacks,omitempty"`
// Ignore specifies provider slugs to skip for this request
Ignore []string `json:"ignore,omitempty"`
// Quantizations filters providers by quantization levels (e.g. ["int4", "int8"])
Quantizations []string `json:"quantizations,omitempty"`
// ZDR restricts routing to only Zero Data Retention endpoints
ZDR *bool `json:"zdr,omitempty"`
// Only specifies provider slugs to allow for this request
Only []string `json:"only,omitempty"`
// Sort providers by "price", "throughput", or "latency"
Sort string `json:"sort,omitempty"`
// MaxPrice specifies maximum pricing constraints for the request
MaxPrice *MaxPrice `json:"max_price,omitempty"`
// Deprecated: Use Ignore instead
IgnoreProviders []string `json:"-"`
// Deprecated: Use Quantizations instead
QuantizationFallback map[string]string `json:"-"`
// Internal provider parameters
ProviderParams map[string]interface{} `json:"-"`
}
Provider represents provider-specific parameters for routing requests.
type ProviderInfo ¶
type ProviderInfo struct {
Name string `json:"name"`
Slug string `json:"slug"`
PrivacyPolicyURL *string `json:"privacy_policy_url"`
TermsOfServiceURL *string `json:"terms_of_service_url"`
StatusPageURL *string `json:"status_page_url"`
}
ProviderInfo represents information about a provider available on OpenRouter.
type ProvidersResponse ¶
type ProvidersResponse struct {
Data []ProviderInfo `json:"data"`
}
ProvidersResponse represents the response from the list providers endpoint.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter provides rate limiting functionality.
func NewRateLimiter ¶
func NewRateLimiter(requestsPerSecond float64, burst int) *RateLimiter
NewRateLimiter creates a new rate limiter.
type RequestConfig ¶
type RequestConfig interface {
*ChatCompletionRequest | *CompletionRequest
}
RequestConfig is an interface that both ChatCompletionRequest and CompletionRequest satisfy. It provides access to common fields for generic option functions.
type RequestError ¶
RequestError represents an error returned by the OpenRouter API.
func IsRequestError ¶
func IsRequestError(err error) (*RequestError, bool)
IsRequestError checks if an error is a RequestError and returns it.
func (*RequestError) Error ¶
func (e *RequestError) Error() string
Error implements the error interface.
func (*RequestError) IsAuthenticationError ¶
func (e *RequestError) IsAuthenticationError() bool
IsAuthenticationError returns true if the error is an authentication error.
func (*RequestError) IsNotFoundError ¶
func (e *RequestError) IsNotFoundError() bool
IsNotFoundError returns true if the error is a not found error.
func (*RequestError) IsPermissionError ¶
func (e *RequestError) IsPermissionError() bool
IsPermissionError returns true if the error is a permission error.
func (*RequestError) IsRateLimitError ¶
func (e *RequestError) IsRateLimitError() bool
IsRateLimitError returns true if the error is a rate limit error.
func (*RequestError) IsServerError ¶
func (e *RequestError) IsServerError() bool
IsServerError returns true if the error is a server error.
type RequestWithProvider ¶
type RequestWithProvider interface {
*ChatCompletionRequest | *CompletionRequest
}
RequestWithProvider is a type constraint for requests that have provider settings. This constraint allows generic functions to work with both ChatCompletionRequest and CompletionRequest in a type-safe manner.
type ResponseFormat ¶
type ResponseFormat struct {
Type string `json:"type"`
JSONSchema *JSONSchema `json:"json_schema,omitempty"`
}
ResponseFormat specifies the format of the response.
type RetryConfig ¶
type RetryConfig struct {
MaxRetries int
InitialDelay time.Duration
MaxDelay time.Duration
Multiplier float64
Jitter bool
RetryableError func(error) bool
}
RetryConfig configures retry behavior for API requests.
func DefaultRetryConfig ¶
func DefaultRetryConfig() *RetryConfig
DefaultRetryConfig returns the default retry configuration.
type Stream ¶
type Stream[T any] struct { // contains filtered or unexported fields }
Stream represents a generic streaming response wrapper.
type StreamError ¶
StreamError represents an error that occurs during streaming.
func IsStreamError ¶
func IsStreamError(err error) (*StreamError, bool)
IsStreamError checks if an error is a StreamError and returns it.
func (*StreamError) Error ¶
func (e *StreamError) Error() string
Error implements the error interface.
func (*StreamError) Unwrap ¶
func (e *StreamError) Unwrap() error
Unwrap returns the underlying error.
type StreamEvent ¶
StreamEvent represents a server-sent event for streaming responses.
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"`
Function FunctionCall `json:"function"`
}
ToolCall represents a tool call made by the model.
type TopLogProb ¶
type TopLogProb struct {
Token string `json:"token"`
LogProb float64 `json:"logprob"`
Bytes []int `json:"bytes,omitempty"`
}
TopLogProb represents top log probability information.
type URLCitation ¶
type URLCitation struct {
// URL of the cited source
URL string `json:"url"`
// Title of the web search result
Title string `json:"title"`
// Content of the web search result
Content string `json:"content,omitempty"`
// StartIndex is the index of the first character of the citation in the message
StartIndex int `json:"start_index"`
// EndIndex is the index of the last character of the citation in the message
EndIndex int `json:"end_index"`
}
URLCitation represents a URL citation in a message annotation.
func ParseAnnotations ¶
func ParseAnnotations(annotations []Annotation) []URLCitation
ParseAnnotations extracts URL citations from message annotations.
type UpdateKeyRequest ¶
type UpdateKeyRequest struct {
// Name is the new name/label for the API key
Name *string `json:"name,omitempty"`
// Disabled controls whether the API key is disabled
Disabled *bool `json:"disabled,omitempty"`
// Limit is the new credit limit for the API key
Limit *float64 `json:"limit,omitempty"`
// IncludeBYOKInLimit controls whether BYOK usage counts toward the limit
IncludeBYOKInLimit *bool `json:"include_byok_in_limit,omitempty"`
}
UpdateKeyRequest represents a request to update an existing API key. All fields are optional - only include fields you want to update.
type UpdateKeyResponse ¶
type UpdateKeyResponse struct {
Data APIKey `json:"data"`
}
UpdateKeyResponse represents the response from updating an API key.
type Usage ¶
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
}
Usage represents token usage information.
type ValidationError ¶
ValidationError represents a validation error for request parameters.
func IsValidationError ¶
func IsValidationError(err error) (*ValidationError, bool)
IsValidationError checks if an error is a ValidationError and returns it.
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
Error implements the error interface.
type WebSearchContextSize ¶
type WebSearchContextSize string
WebSearchContextSize represents the amount of search context to retrieve.
const ( // WebSearchContextLow provides minimal search context WebSearchContextLow WebSearchContextSize = "low" // WebSearchContextMedium provides moderate search context WebSearchContextMedium WebSearchContextSize = "medium" // WebSearchContextHigh provides extensive search context WebSearchContextHigh WebSearchContextSize = "high" )
type WebSearchEngine ¶
type WebSearchEngine string
WebSearchEngine represents the search engine options for the web plugin.
const ( // WebSearchEngineNative uses the model provider's built-in web search WebSearchEngineNative WebSearchEngine = "native" // WebSearchEngineExa uses Exa's search API for web results WebSearchEngineExa WebSearchEngine = "exa" // WebSearchEngineAuto automatically selects the best available engine WebSearchEngineAuto WebSearchEngine = "" )
type WebSearchOptions ¶
type WebSearchOptions struct {
// SearchContextSize determines the amount of search context ("low", "medium", or "high")
SearchContextSize string `json:"search_context_size,omitempty"`
}
WebSearchOptions configures native web search behavior for supported models.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
openrouter-test
command
|
|
|
examples
|
|
|
activity
command
|
|
|
advanced
command
|
|
|
app-attribution
command
|
|
|
audio-inputs
command
|
|
|
basic
command
|
|
|
create-key
command
|
|
|
embeddings
command
|
|
|
get-credits
command
|
|
|
image-inputs
command
|
|
|
key
command
|
|
|
list-keys
command
|
|
|
list-models
command
|
|
|
list-providers
command
|
|
|
model-endpoints
command
|
|
|
pdf-inputs
command
|
|
|
streaming
command
|
|
|
structured-output
command
|
|
|
tool-calling
command
Package main demonstrates tool calling with the OpenRouter API.
|
Package main demonstrates tool calling with the OpenRouter API. |
|
transforms
command
Package main demonstrates the use of message transforms in the OpenRouter Go client.
|
Package main demonstrates the use of message transforms in the OpenRouter Go client. |
|
web_search
command
|
|
|
internal
|
|
|
sse
Package sse provides Server-Sent Events parsing functionality.
|
Package sse provides Server-Sent Events parsing functionality. |