Documentation
¶
Overview ¶
Package openrouter provides Go bindings for the OpenRouter API.
Package openrouter provides Go bindings for the OpenRouter API.
Package openrouter provides Go bindings for the OpenRouter API.
Package openrouter provides Go bindings for the OpenRouter API.
Index ¶
- Constants
- Variables
- func AverageEmbeddings(embeddings [][]float64) []float64
- func ChunkTexts(texts []string, config ChunkConfig) ([][]TextChunk, error)
- func ConcatenateChatStreamResponses(responses []ChatCompletionResponse) string
- func ConcatenateCompletionStreamResponses(responses []CompletionResponse) string
- func ConvertToolResultToMCP(result MCPToolResult) string
- func CosineSimilarity(a, b []float64) float64
- 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 EstimateTokens(text string) int
- func EstimateTokensFromWords(text string) int
- func ReadTextFile(filePath string) (string, error)
- func ReadTextFileWithFilename(filePath string) (content string, filename string, err error)
- func RetryWithBackoff(ctx context.Context, config *RetryConfig, fn func() error) error
- func ValidateTextContent(content string) error
- func WeightedAverageEmbeddings(embeddings [][]float64, weights []float64) []float64
- 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 WithUser(user string) ChatCompletionOption
- func WithWebSearchOptions(options *WebSearchOptions) ChatCompletionOption
- func WithZDR(enabled bool) ChatCompletionOption
- type ChatCompletionRequest
- type ChatCompletionResponse
- type ChatStream
- type Choice
- type ChunkConfig
- type ChunkEmbedding
- type ChunkStrategy
- type ChunkedEmbeddingResult
- 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) CreateChunkedEmbedding(ctx context.Context, text string, model string, config ChunkConfig, ...) (*ChunkedEmbeddingResult, error)
- func (c *Client) CreateChunkedEmbeddings(ctx context.Context, texts []string, model string, config ChunkConfig, ...) ([]*ChunkedEmbeddingResult, 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) CreateResponse(ctx context.Context, input interface{}, opts ...ResponsesOption) (*ResponsesResponse, error)
- func (c *Client) CreateResponseStream(ctx context.Context, input interface{}, opts ...ResponsesOption) (*ResponsesStream, 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 WithCompletionUser(user 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) AddTextContent(content string, label string) *ContentBuilder
- func (cb *ContentBuilder) AddTextFile(filePath string) (*ContentBuilder, error)
- func (cb *ContentBuilder) AddTextFileWithLabel(filePath string, label string) (*ContentBuilder, error)
- 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 MCPContent
- type MCPInputSchema
- type MCPTool
- type MCPToolResult
- 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
- func CreateUserMessageWithTextContent(text string, content string, filename string) Message
- func CreateUserMessageWithTextFile(text string, filePath string) (Message, error)
- func CreateUserMessageWithTextFiles(text string, filePaths ...string) (Message, error)
- 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 RequestOption
- type RequestWithProvider
- type ResponseFormat
- type ResponsesAnnotation
- type ResponsesInputContent
- type ResponsesInputItem
- func CreateResponsesAssistantMessage(text string) ResponsesInputItem
- func CreateResponsesFunctionOutput(callID, output string) ResponsesInputItem
- func CreateResponsesMessage(role, text string) ResponsesInputItem
- func CreateResponsesSystemMessage(text string) ResponsesInputItem
- func CreateResponsesUserMessage(text string) ResponsesInputItem
- type ResponsesOption
- func WithResponsesInput(input any) ResponsesOption
- func WithResponsesMaxOutputTokens(tokens int) ResponsesOption
- func WithResponsesMetadata(metadata map[string]interface{}) ResponsesOption
- func WithResponsesModel(model string) ResponsesOption
- func WithResponsesPlugins(plugins ...Plugin) ResponsesOption
- func WithResponsesReasoning(ptr *ResponsesReasoning) ResponsesOption
- func WithResponsesReasoningEffort(effort string) ResponsesOption
- func WithResponsesTemperature(temperature float64) ResponsesOption
- func WithResponsesToolChoice(toolChoice any) ResponsesOption
- func WithResponsesTools(tools ...ResponsesTool) ResponsesOption
- func WithResponsesTopP(topP float64) ResponsesOption
- func WithResponsesWebSearch(maxResults int) ResponsesOption
- type ResponsesOutput
- type ResponsesOutputContent
- type ResponsesReasoning
- type ResponsesRequest
- type ResponsesResponse
- type ResponsesStream
- type ResponsesTool
- type ResponsesUsage
- type RetryConfig
- type Stream
- type StreamError
- type StreamEvent
- type TextChunk
- type Tool
- type ToolCall
- type TopLogProb
- type URLCitation
- type UpdateKeyRequest
- type UpdateKeyResponse
- type Usage
- type ValidationError
- type WebSearchContextSize
- type WebSearchEngine
- type WebSearchOptions
Constants ¶
const ( // ReasoningEffortMinimal indicates minimal reasoning effort for simple queries. ReasoningEffortMinimal = "minimal" // ReasoningEffortLow indicates low reasoning effort for straightforward tasks. ReasoningEffortLow = "low" // ReasoningEffortMedium indicates medium reasoning effort for moderate complexity. ReasoningEffortMedium = "medium" // ReasoningEffortHigh indicates high reasoning effort for complex problems. ReasoningEffortHigh = "high" )
Reasoning effort level constants for the Responses API.
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.
var ( // ErrNoResponsesInput is returned when no input is provided. ErrNoResponsesInput = &ValidationError{ Field: "input", Message: "input is required", } )
Predefined validation errors for Responses API.
Functions ¶
func AverageEmbeddings ¶ added in v1.4.2
AverageEmbeddings computes the element-wise average of multiple embeddings. Useful for combining chunk embeddings into a single document embedding.
func ChunkTexts ¶ added in v1.4.2
func ChunkTexts(texts []string, config ChunkConfig) ([][]TextChunk, error)
ChunkTexts splits multiple texts into chunks.
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 ConvertToolResultToMCP ¶ added in v1.3.0
func ConvertToolResultToMCP(result MCPToolResult) string
ConvertToolResultToMCP converts an MCP tool result to a string suitable for use as tool response content in chat completions.
func CosineSimilarity ¶ added in v1.4.2
CosineSimilarity computes the cosine similarity between two embedding vectors. Returns a value between -1 and 1, where 1 means identical direction.
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 EstimateTokens ¶ added in v1.4.2
EstimateTokens estimates the token count for text using character-based heuristics. Uses approximately 4 characters per token for English text.
func EstimateTokensFromWords ¶ added in v1.4.2
EstimateTokensFromWords estimates token count based on word count. Uses approximately 1.3 tokens per word for English text.
func ReadTextFile ¶ added in v1.4.1
ReadTextFile reads a text file and returns its content as a string. It validates that the file contains valid UTF-8 text. Supported formats: .txt, .md, .json, .csv, .js, .py, .go, .java, .rs, .ts, .jsx, .tsx, .cpp, .c, .h, .rb, .php, .swift, .kt, .yaml, .yml, .toml, .xml, .ini
func ReadTextFileWithFilename ¶ added in v1.4.1
ReadTextFileWithFilename reads a text file and returns both the content and filename. This is useful when you want to include the filename in your message.
func RetryWithBackoff ¶
func RetryWithBackoff(ctx context.Context, config *RetryConfig, fn func() error) error
RetryWithBackoff executes a function with exponential backoff retry logic.
func ValidateTextContent ¶ added in v1.4.1
ValidateTextContent validates that the given content is valid UTF-8 text.
func WeightedAverageEmbeddings ¶ added in v1.4.2
WeightedAverageEmbeddings computes a weighted average of embeddings. weights should have the same length as embeddings.
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 WithUser ¶ added in v1.3.1
func WithUser(user string) ChatCompletionOption
WithUser sets a unique identifier for the end-user. This helps OpenRouter track users for analytics, improve caching by making it sticky to individual users, and provides user-level reporting in the activity feed.
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"`
User string `json:"user,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 ChunkConfig ¶ added in v1.4.2
type ChunkConfig struct {
// Strategy determines how text is split.
Strategy ChunkStrategy
// ChunkSize is the target size per chunk.
// For semantic strategies: target token count (units are merged to reach this).
// For size-based strategies: exact limit (tokens or characters).
ChunkSize int
// Overlap specifies units to overlap between chunks for context preservation.
// For semantic strategies: number of units (sentences/paragraphs) to repeat.
// For size-based strategies: number of tokens/characters to overlap.
Overlap int
// TrimWhitespace removes leading/trailing whitespace from chunks.
TrimWhitespace bool
// PreserveWords prevents splitting mid-word (for tokens/characters strategies).
PreserveWords bool
// SectionHeaders defines custom section delimiters for sections strategy.
// Default: ["#", "##", "###", "####", "#####", "######"] for markdown.
SectionHeaders []string
}
ChunkConfig configures text chunking behavior.
func DefaultChunkConfig ¶ added in v1.4.2
func DefaultChunkConfig() ChunkConfig
DefaultChunkConfig returns a sensible default configuration.
type ChunkEmbedding ¶ added in v1.4.2
type ChunkEmbedding struct {
// Chunk is the original text chunk with metadata.
Chunk TextChunk
// Embedding is the vector representation.
Embedding []float64
}
ChunkEmbedding contains the embedding for a single chunk.
type ChunkStrategy ¶ added in v1.4.2
type ChunkStrategy string
ChunkStrategy defines the strategy for chunking text. Strategies are ordered by semantic quality, with semantic strategies (sections, paragraphs, sentences) preferred over size-based strategies (tokens, characters).
const ( // ChunkBySections splits at markdown headers or document structure. // Best for structured documents with clear sections. ChunkBySections ChunkStrategy = "sections" // ChunkByParagraphs splits at paragraph boundaries (double newlines). // Good for prose and articles. ChunkByParagraphs ChunkStrategy = "paragraphs" // ChunkBySentences splits at sentence boundaries. // Fine-grained semantic chunking. ChunkBySentences ChunkStrategy = "sentences" // ChunkByTokens splits by estimated token count. ChunkByTokens ChunkStrategy = "tokens" // ChunkByCharacters splits by character count. ChunkByCharacters ChunkStrategy = "characters" )
type ChunkedEmbeddingResult ¶ added in v1.4.2
type ChunkedEmbeddingResult struct {
// Chunks contains the embedding for each chunk.
Chunks []ChunkEmbedding
// TotalTokensUsed is the sum of tokens used across all chunk embeddings.
TotalTokensUsed int
// Model is the embedding model used.
Model string
}
ChunkedEmbeddingResult contains embeddings for all chunks of a document.
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) CreateChunkedEmbedding ¶ added in v1.4.2
func (c *Client) CreateChunkedEmbedding(ctx context.Context, text string, model string, config ChunkConfig, opts ...EmbeddingOption) (*ChunkedEmbeddingResult, error)
CreateChunkedEmbedding creates embeddings for a long text by chunking it first.
func (*Client) CreateChunkedEmbeddings ¶ added in v1.4.2
func (c *Client) CreateChunkedEmbeddings(ctx context.Context, texts []string, model string, config ChunkConfig, opts ...EmbeddingOption) ([]*ChunkedEmbeddingResult, error)
CreateChunkedEmbeddings creates embeddings for multiple long texts by chunking each.
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) CreateResponse ¶ added in v1.4.0
func (c *Client) CreateResponse(ctx context.Context, input interface{}, opts ...ResponsesOption) (*ResponsesResponse, error)
CreateResponse sends a request to the OpenRouter Responses API (beta). The input can be a simple string or a structured array of ResponsesInputItem.
Note: This API is in beta and may have breaking changes. Use with caution in production.
Example with simple string input:
resp, err := client.CreateResponse(ctx, "Hello, world!",
openrouter.WithResponsesModel("openai/o4-mini"),
openrouter.WithResponsesMaxOutputTokens(100),
)
Example with structured input:
input := []openrouter.ResponsesInputItem{
openrouter.CreateResponsesUserMessage("Hello!"),
}
resp, err := client.CreateResponse(ctx, input,
openrouter.WithResponsesModel("openai/o4-mini"),
)
func (*Client) CreateResponseStream ¶ added in v1.4.0
func (c *Client) CreateResponseStream(ctx context.Context, input interface{}, opts ...ResponsesOption) (*ResponsesStream, error)
CreateResponseStream sends a streaming request to the OpenRouter Responses API (beta). Returns a stream that can be used to receive response events as they arrive.
Note: This API is in beta and may have breaking changes. Use with caution in production.
Example:
stream, err := client.CreateResponseStream(ctx, "Tell me a story",
openrouter.WithResponsesModel("openai/o4-mini"),
)
if err != nil {
log.Fatal(err)
}
defer stream.Close()
for event := range stream.Events() {
// Process streaming event
fmt.Print(event.GetTextContent())
}
if err := stream.Err(); err != nil {
log.Printf("Stream error: %v", err)
}
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 WithCompletionUser ¶ added in v1.3.1
func WithCompletionUser(user string) CompletionOption
WithCompletionUser sets a unique identifier for the end-user in completion requests. This helps OpenRouter track users for analytics, improve caching by making it sticky to individual users, and provides user-level reporting in the activity feed.
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"`
User string `json:"user,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) AddTextContent ¶ added in v1.4.1
func (cb *ContentBuilder) AddTextContent(content string, label string) *ContentBuilder
AddTextContent adds raw text content with an optional label.
func (*ContentBuilder) AddTextFile ¶ added in v1.4.1
func (cb *ContentBuilder) AddTextFile(filePath string) (*ContentBuilder, error)
AddTextFile reads a text file and adds its content to the message. The content is formatted with a filename header for context.
func (*ContentBuilder) AddTextFileWithLabel ¶ added in v1.4.1
func (cb *ContentBuilder) AddTextFileWithLabel(filePath string, label string) (*ContentBuilder, error)
AddTextFileWithLabel reads a text file and adds its content with a custom label.
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
// SupportedParameters filters models by supported parameter (e.g. "tools", "temperature").
SupportedParameters string
// UseRSS returns an RSS feed instead of JSON when set to "true".
UseRSS string
// UseRSSChatLinks includes chat links in the RSS feed when set to "true".
UseRSSChatLinks 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 MCPContent ¶ added in v1.3.0
type MCPContent struct {
// Type is the content type (e.g., "text", "image", "resource")
Type string `json:"type"`
// Text is the text content (when Type is "text")
Text string `json:"text,omitempty"`
// Data is base64-encoded data (when Type is "image" or "resource")
Data string `json:"data,omitempty"`
// MimeType is the MIME type for binary content
MimeType string `json:"mimeType,omitempty"`
}
MCPContent represents content in an MCP response.
type MCPInputSchema ¶ added in v1.3.0
type MCPInputSchema struct {
// Type is typically "object" for MCP tool schemas
Type string `json:"type,omitempty"`
// Properties defines the tool's input parameters
Properties map[string]interface{} `json:"properties,omitempty"`
// Required lists parameter names that must be provided
Required []string `json:"required,omitempty"`
// AdditionalProperties controls whether extra properties are allowed
AdditionalProperties *bool `json:"additionalProperties,omitempty"`
}
MCPInputSchema represents the input schema for an MCP tool. It follows JSON Schema Draft 7 format.
type MCPTool ¶ added in v1.3.0
type MCPTool struct {
// Name is the unique identifier for the tool
Name string `json:"name"`
// Description explains what the tool does
Description string `json:"description,omitempty"`
// InputSchema defines the expected input parameters using JSON Schema
InputSchema *MCPInputSchema `json:"inputSchema,omitempty"`
}
MCPTool represents a tool in MCP (Model Context Protocol) format. This format is used by MCP servers and clients for tool definitions.
func ParseMCPToolFromJSON ¶ added in v1.3.0
ParseMCPToolFromJSON parses an MCP tool from JSON data. This is useful when receiving tool definitions from an MCP server.
func ParseMCPToolsFromJSON ¶ added in v1.3.0
ParseMCPToolsFromJSON parses multiple MCP tools from JSON data.
type MCPToolResult ¶ added in v1.3.0
type MCPToolResult struct {
// Content contains the tool execution result(s)
Content []MCPContent `json:"content"`
// IsError indicates if the tool execution failed
IsError bool `json:"isError,omitempty"`
}
MCPToolResult represents the result of an MCP tool execution.
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).
func CreateUserMessageWithTextContent ¶ added in v1.4.1
CreateUserMessageWithTextContent creates a user message with inline text content. Unlike CreateUserMessageWithTextFile, this doesn't read from a file but formats the content with an optional filename for context.
func CreateUserMessageWithTextFile ¶ added in v1.4.1
CreateUserMessageWithTextFile creates a user message with text and content from a text file. The file content is included inline as text, not base64-encoded. Example:
msg, err := CreateUserMessageWithTextFile(
"Review this code for bugs:",
"/path/to/code.py",
)
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 RequestOption ¶ added in v1.4.0
type RequestOption[T any] func(T)
RequestOption is a generic functional option type for configuring requests.
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 ResponsesAnnotation ¶ added in v1.4.0
type ResponsesAnnotation struct {
// Type specifies the annotation type (e.g., "url_citation").
Type string `json:"type"`
// URL is the cited URL (for "url_citation" type).
URL string `json:"url,omitempty"`
// StartIndex is the start position of the citation in the text.
StartIndex int `json:"start_index,omitempty"`
// EndIndex is the end position of the citation in the text.
EndIndex int `json:"end_index,omitempty"`
}
ResponsesAnnotation represents an annotation in the output content.
type ResponsesInputContent ¶ added in v1.4.0
type ResponsesInputContent struct {
// Type specifies the content type: "input_text"
Type string `json:"type"`
// Text is the text content.
Text string `json:"text"`
}
ResponsesInputContent represents a content item in a message.
type ResponsesInputItem ¶ added in v1.4.0
type ResponsesInputItem struct {
// Type specifies the item type: "message" or "function_call_output"
Type string `json:"type"`
// ID is the unique identifier for this item (used in multi-turn conversations).
ID string `json:"id,omitempty"`
// Status indicates the completion status (e.g., "completed").
Status string `json:"status,omitempty"`
// Role is the message role: "user", "assistant", "system"
// Only used when Type is "message".
Role string `json:"role,omitempty"`
// Content is the message content array.
// Only used when Type is "message".
Content []ResponsesInputContent `json:"content,omitempty"`
// CallID is the ID of the function call being responded to.
// Only used when Type is "function_call_output".
CallID string `json:"call_id,omitempty"`
// Output is the result of the function call.
// Only used when Type is "function_call_output".
Output string `json:"output,omitempty"`
}
ResponsesInputItem represents an item in the structured input array. Used for multi-turn conversations and function call outputs.
func CreateResponsesAssistantMessage ¶ added in v1.4.0
func CreateResponsesAssistantMessage(text string) ResponsesInputItem
CreateResponsesAssistantMessage creates an assistant message input item.
func CreateResponsesFunctionOutput ¶ added in v1.4.0
func CreateResponsesFunctionOutput(callID, output string) ResponsesInputItem
CreateResponsesFunctionOutput creates a function call output item.
func CreateResponsesMessage ¶ added in v1.4.0
func CreateResponsesMessage(role, text string) ResponsesInputItem
CreateResponsesMessage creates a message input item with the specified role and text.
func CreateResponsesSystemMessage ¶ added in v1.4.0
func CreateResponsesSystemMessage(text string) ResponsesInputItem
CreateResponsesSystemMessage creates a system message input item.
func CreateResponsesUserMessage ¶ added in v1.4.0
func CreateResponsesUserMessage(text string) ResponsesInputItem
CreateResponsesUserMessage creates a user message input item.
type ResponsesOption ¶ added in v1.4.0
type ResponsesOption = RequestOption[*ResponsesRequest]
ResponsesOption is a functional option for configuring ResponsesRequest.
func WithResponsesInput ¶ added in v1.4.0
func WithResponsesInput(input any) ResponsesOption
WithResponsesInput sets the input for the Responses API request. Input can be a string for simple text, or []ResponsesInputItem for structured messages.
func WithResponsesMaxOutputTokens ¶ added in v1.4.0
func WithResponsesMaxOutputTokens(tokens int) ResponsesOption
WithResponsesMaxOutputTokens sets the maximum number of output tokens.
func WithResponsesMetadata ¶ added in v1.4.0
func WithResponsesMetadata(metadata map[string]interface{}) ResponsesOption
WithResponsesMetadata sets metadata headers for the request.
func WithResponsesModel ¶ added in v1.4.0
func WithResponsesModel(model string) ResponsesOption
WithResponsesModel sets the model for the Responses API request.
func WithResponsesPlugins ¶ added in v1.4.0
func WithResponsesPlugins(plugins ...Plugin) ResponsesOption
WithResponsesPlugins appends plugins to the request. This appends to any existing plugins to avoid overwriting plugins added by other options like WithResponsesWebSearch.
func WithResponsesReasoning ¶ added in v1.4.0
func WithResponsesReasoning(ptr *ResponsesReasoning) ResponsesOption
WithResponsesReasoning sets the reasoning configuration. If ptr is nil, r.Reasoning is left nil. Otherwise, a defensive copy is made.
func WithResponsesReasoningEffort ¶ added in v1.4.0
func WithResponsesReasoningEffort(effort string) ResponsesOption
WithResponsesReasoningEffort sets the reasoning effort level. Valid values: "minimal", "low", "medium", "high"
func WithResponsesTemperature ¶ added in v1.4.0
func WithResponsesTemperature(temperature float64) ResponsesOption
WithResponsesTemperature sets the temperature for sampling (0-2).
func WithResponsesToolChoice ¶ added in v1.4.0
func WithResponsesToolChoice(toolChoice any) ResponsesOption
WithResponsesToolChoice sets the tool choice strategy for ResponsesRequest.ToolChoice. Can be:
- "auto" - let the model decide whether to call tools
- "none" - disable tool calling
- A specific tool: map[string]any{"type": "function", "function": map[string]any{"name": "functionName"}}
func WithResponsesTools ¶ added in v1.4.0
func WithResponsesTools(tools ...ResponsesTool) ResponsesOption
WithResponsesTools sets the available tools/functions for the request. Uses ResponsesTool which has a flat structure expected by the Responses API.
func WithResponsesTopP ¶ added in v1.4.0
func WithResponsesTopP(topP float64) ResponsesOption
WithResponsesTopP sets the top_p value for nucleus sampling (0-1).
func WithResponsesWebSearch ¶ added in v1.4.0
func WithResponsesWebSearch(maxResults int) ResponsesOption
WithResponsesWebSearch enables web search with the specified maximum results. This is a convenience function that adds the web search plugin.
type ResponsesOutput ¶ added in v1.4.0
type ResponsesOutput struct {
// Type specifies the output type: "message" or "function_call"
Type string `json:"type"`
// ID is the unique identifier for this output item.
ID string `json:"id"`
// Status indicates the completion status.
Status string `json:"status,omitempty"`
// Role is the message role (for "message" type).
Role string `json:"role,omitempty"`
// Content is the message content array (for "message" type).
Content []ResponsesOutputContent `json:"content,omitempty"`
// CallID is the function call ID (for "function_call" type).
CallID string `json:"call_id,omitempty"`
// Name is the function name (for "function_call" type).
Name string `json:"name,omitempty"`
// Arguments is the JSON-encoded function arguments (for "function_call" type).
Arguments string `json:"arguments,omitempty"`
}
ResponsesOutput represents an output item in the response.
type ResponsesOutputContent ¶ added in v1.4.0
type ResponsesOutputContent struct {
// Type specifies the content type: "output_text" or "reasoning"
Type string `json:"type"`
// Text is the text content (for "output_text" type).
Text string `json:"text,omitempty"`
// Annotations contains URL citations and other annotations.
Annotations []ResponsesAnnotation `json:"annotations,omitempty"`
// EncryptedContent contains the encrypted reasoning chain (for "reasoning" type).
EncryptedContent string `json:"encrypted_content,omitempty"`
// Summary contains key reasoning steps as text (for "reasoning" type).
Summary []string `json:"summary,omitempty"`
}
ResponsesOutputContent represents a content item in the output.
type ResponsesReasoning ¶ added in v1.4.0
type ResponsesReasoning struct {
// Effort controls the computational intensity of reasoning.
// Valid values: "minimal", "low", "medium", "high"
Effort string `json:"effort"`
}
ResponsesReasoning configures reasoning capabilities for the Responses API.
type ResponsesRequest ¶ added in v1.4.0
type ResponsesRequest struct {
// Model is the model identifier (required).
// Example: "openai/o4-mini"
Model string `json:"model"`
// Input is the input to the model (required).
// Can be a string for simple text input, or []ResponsesInputItem for structured messages.
Input any `json:"input"`
// Stream enables streaming responses via Server-Sent Events.
Stream bool `json:"stream,omitempty"`
// MaxOutputTokens limits the number of tokens in the response.
MaxOutputTokens *int `json:"max_output_tokens,omitempty"`
// Temperature controls randomness in sampling (0-2).
Temperature *float64 `json:"temperature,omitempty"`
// TopP controls nucleus sampling (0-1).
TopP *float64 `json:"top_p,omitempty"`
// Reasoning configures reasoning capabilities.
Reasoning *ResponsesReasoning `json:"reasoning,omitempty"`
// Tools defines available functions the model can call.
// Uses ResponsesTool which has a flat structure (name, description, parameters at top level).
Tools []ResponsesTool `json:"tools,omitempty"`
// ToolChoice controls tool invocation behavior.
// Can be "auto", "none", or a specific tool specification.
ToolChoice any `json:"tool_choice,omitempty"`
// Plugins configures plugins like web search.
Plugins []Plugin `json:"plugins,omitempty"`
// Metadata is used for custom headers (not serialized to JSON).
Metadata map[string]interface{} `json:"-"`
}
ResponsesRequest represents a request to the OpenRouter Responses API.
WARNING: BETA API - EXPECT BREAKING CHANGES
This API is in beta and may have breaking changes at any time. Do not rely on this for production workloads. The API structure, parameters, and behavior may change without notice.
For stable production use, consider using ChatCompletionRequest instead.
Features: reasoning, tool calling, web search integration, and streaming.
func (*ResponsesRequest) GetMetadata ¶ added in v1.4.0
func (r *ResponsesRequest) GetMetadata() map[string]interface{}
GetMetadata returns the metadata map for header generation.
type ResponsesResponse ¶ added in v1.4.0
type ResponsesResponse struct {
// ID is the unique identifier for this response.
ID string `json:"id"`
// Object is the object type, always "response".
Object string `json:"object"`
// CreatedAt is the Unix timestamp when the response was created.
CreatedAt int64 `json:"created_at"`
// Model is the model that generated the response.
Model string `json:"model"`
// Output is the array of output items (messages, function calls, etc.).
Output []ResponsesOutput `json:"output"`
// Usage contains token usage information.
Usage ResponsesUsage `json:"usage"`
// Status indicates the completion status (e.g., "completed").
Status string `json:"status"`
// Metadata contains additional response metadata.
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ResponsesResponse represents a response from the OpenRouter Responses API.
func (*ResponsesResponse) GetAnnotations ¶ added in v1.4.0
func (r *ResponsesResponse) GetAnnotations() []ResponsesAnnotation
GetAnnotations returns all annotations from the response.
func (*ResponsesResponse) GetFunctionCalls ¶ added in v1.4.0
func (r *ResponsesResponse) GetFunctionCalls() []ResponsesOutput
GetFunctionCalls returns all function calls from the response.
func (*ResponsesResponse) GetReasoningSummary ¶ added in v1.4.0
func (r *ResponsesResponse) GetReasoningSummary() []string
GetReasoningSummary returns the reasoning summary if present.
func (*ResponsesResponse) GetTextContent ¶ added in v1.4.0
func (r *ResponsesResponse) GetTextContent() string
GetTextContent extracts the text content from a ResponsesResponse. Returns the first text content found in the output, or an empty string if none found.
type ResponsesStream ¶ added in v1.4.0
type ResponsesStream = Stream[ResponsesResponse]
ResponsesStream represents a streaming response from the Responses API.
type ResponsesTool ¶ added in v1.4.1
type ResponsesTool struct {
// Type specifies the tool type, always "function".
Type string `json:"type"`
// Name is the function name.
Name string `json:"name"`
// Description explains what the function does.
Description string `json:"description,omitempty"`
// Strict enables strict schema validation (set to null/nil for default behavior).
Strict *bool `json:"strict"`
// Parameters is the JSON Schema for the function parameters.
Parameters map[string]any `json:"parameters,omitempty"`
}
ResponsesTool represents a tool definition for the Responses API. This has a flat structure unlike the Chat Completions API which nests under "function".
func ConvertToolToResponsesTool ¶ added in v1.4.1
func ConvertToolToResponsesTool(tool Tool) ResponsesTool
ConvertToolToResponsesTool converts a Chat Completions Tool to a Responses API tool.
func ConvertToolsToResponsesTools ¶ added in v1.4.1
func ConvertToolsToResponsesTools(tools []Tool) []ResponsesTool
ConvertToolsToResponsesTools converts multiple Chat Completions Tools to Responses API tools.
func CreateResponsesTool ¶ added in v1.4.1
func CreateResponsesTool(name, description string, parameters map[string]any) ResponsesTool
CreateResponsesTool creates a ResponsesTool with the given parameters.
type ResponsesUsage ¶ added in v1.4.0
type ResponsesUsage struct {
// InputTokens is the number of tokens in the input.
InputTokens int `json:"input_tokens"`
// OutputTokens is the number of tokens in the output.
OutputTokens int `json:"output_tokens"`
// TotalTokens is the total number of tokens used.
TotalTokens int `json:"total_tokens"`
// ReasoningTokens is the number of tokens used for reasoning (if reasoning is enabled).
ReasoningTokens int `json:"reasoning_tokens,omitempty"`
}
ResponsesUsage contains token usage information for the Responses API.
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 TextChunk ¶ added in v1.4.2
type TextChunk struct {
// Text is the chunk content.
Text string
// Index is the zero-based index of this chunk.
Index int
// StartPos is the byte offset in the original text where this chunk starts.
StartPos int
// EndPos is the byte offset in the original text where this chunk ends.
EndPos int
}
TextChunk represents a single chunk of text with metadata.
type Tool ¶
Tool represents a tool/function that can be called.
func ConvertMCPTool ¶ added in v1.3.0
ConvertMCPTool converts an MCP tool to OpenRouter's Tool format. The OpenRouter format follows the OpenAI function calling specification.
func ConvertMCPTools ¶ added in v1.3.0
ConvertMCPTools converts a slice of MCP tools to OpenRouter Tool format.
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
¶
- activity_endpoint.go
- audio_utils.go
- chat.go
- chunking.go
- client.go
- completions.go
- credits_endpoint.go
- embeddings.go
- errors.go
- image_utils.go
- key_endpoint.go
- mcp.go
- model_endpoints.go
- models.go
- models_endpoint.go
- options.go
- pdf_utils.go
- providers_endpoint.go
- responses.go
- responses_models.go
- responses_options.go
- retry.go
- stream.go
- text_utils.go
- validation.go
- web_search.go
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
openrouter-test
command
|
|
|
examples
|
|
|
activity
command
|
|
|
advanced
command
|
|
|
app-attribution
command
|
|
|
audio-inputs
command
|
|
|
basic
command
|
|
|
create-key
command
|
|
|
embedding-chunking
command
Package main demonstrates text chunking and chunked embeddings.
|
Package main demonstrates text chunking and chunked embeddings. |
|
embeddings
command
|
|
|
get-credits
command
|
|
|
image-inputs
command
|
|
|
key
command
|
|
|
list-keys
command
|
|
|
list-models
command
|
|
|
list-providers
command
|
|
|
mcp-tools
command
Package main demonstrates using MCP tools with the OpenRouter API.
|
Package main demonstrates using MCP tools with the OpenRouter API. |
|
model-endpoints
command
|
|
|
pdf-inputs
command
|
|
|
responses
command
Responses API Example
|
Responses API Example |
|
streaming
command
|
|
|
structured-output
command
|
|
|
text-file-inputs
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. |