Documentation
¶
Index ¶
- Constants
- func GenerateSchema(v any) (map[string]any, error)
- type APIError
- type CacheControl
- type ChatCompletionChoiceLogprobs
- type ChatCompletionMessage
- type ChatCompletionMessagePart
- type ChatCompletionMessageRole
- type ChatCompletionRequest
- type ChatCompletionResponse
- type ChatCompletionStream
- type ChatCompletionStreamChoice
- type ChatCompletionStreamChoiceDelta
- type ChatCompletionStreamChoiceLogprobs
- type ChatCompletionStreamResponse
- type ChatCompletionTokenLogprob
- type ChatCompletionTokenLogprobTopLogprob
- type Choice
- type Client
- func (c *Client) CheckCredits(ctx context.Context) (*KeyData, error)
- func (c *Client) CreateChatCompletion(ctx context.Context, r ChatCompletionRequest) (*ChatCompletionResponse, error)
- func (c *Client) CreateChatCompletionStream(ctx context.Context, r ChatCompletionRequest) (*ChatCompletionStream, error)
- func (c *Client) GetGeneration(ctx context.Context, id string) (*Generation, error)
- func (c *Client) ListModels(ctx context.Context) (*ModelsList, error)
- type ClientConfig
- type ErrorResponse
- type File
- type FileParserConfig
- type Function
- type Generation
- type GenerationResponse
- type ImageURL
- type JSONSchema
- type KeyCheckResponse
- type KeyData
- type Model
- type ModelsList
- type PDFEngine
- type PDFPlugin
- type Plugin
- type PluginID
- type Prediction
- type Pricing
- type Provider
- type ProviderError
- type ReasoningDetail
- type ReasoningParams
- type RequestError
- type ResponseFormat
- type SearchContextSize
- type StreamOptions
- type StreamReader
- type TokensDetails
- type Tool
- type ToolCall
- type Usage
- type UsageParams
- type WebSearchOptions
Constants ¶
const ( RoleUser = "user" RoleAssistant = "assistant" RoleSystem = "system" RoleTool = "tool" )
Variables ¶
This section is empty.
Functions ¶
Types ¶
type APIError ¶
type APIError struct { Message string `json:"message"` Code any `json:"code"` Metadata map[string]any `json:"metadata,omitempty"` ProviderError *ProviderError `json:"provider_error,omitempty"` }
APIError is a wrapper for the error response from the OpenRouter API.
type CacheControl ¶
type CacheControl struct {
Type string `json:"type"` // e.g. "ephemeral"
}
CacheControl is for controlling caching of message parts.
type ChatCompletionChoiceLogprobs ¶
type ChatCompletionChoiceLogprobs struct { Content []ChatCompletionTokenLogprob `json:"content,omitempty"` Refusal []ChatCompletionTokenLogprob `json:"refusal,omitempty"` }
ChatCompletionChoiceLogprobs contains token-level logprob information for non-stream responses.
type ChatCompletionMessage ¶
type ChatCompletionMessage struct { Role ChatCompletionMessageRole `json:"role"` Content string `json:"content,omitempty"` MultiContent []ChatCompletionMessagePart `json:"-"` // Will be marshalled to content Name string `json:"name,omitempty"` ToolCalls []ToolCall `json:"tool_calls,omitempty"` ToolCallID string `json:"tool_call_id,omitempty"` // For response messages Reasoning string `json:"reasoning,omitempty"` ReasoningDetails []ReasoningDetail `json:"reasoning_details,omitempty"` }
ChatCompletionMessage is a message in a chat completion request.
func (*ChatCompletionMessage) MarshalJSON ¶
func (m *ChatCompletionMessage) MarshalJSON() ([]byte, error)
MarshalJSON handles marshalling the Content or MultiContent field.
type ChatCompletionMessagePart ¶
type ChatCompletionMessagePart struct { Type string `json:"type"` Text string `json:"text,omitempty"` ImageURL *ImageURL `json:"image_url,omitempty"` File *File `json:"file,omitempty"` // OpenRouter specific CacheControl *CacheControl `json:"cache_control,omitempty"` }
ChatCompletionMessagePart is a part of a multi-part message.
type ChatCompletionMessageRole ¶
type ChatCompletionMessageRole string
type ChatCompletionRequest ¶
type ChatCompletionRequest struct { Model string `json:"model"` Messages []ChatCompletionMessage `json:"messages,omitempty"` Temperature float64 `json:"temperature,omitempty"` TopP float64 `json:"top_p,omitempty"` N int `json:"n,omitempty"` Stream bool `json:"stream,omitempty"` StreamOptions *StreamOptions `json:"stream_options,omitempty"` Stop []string `json:"stop,omitempty"` MaxTokens int `json:"max_tokens,omitempty"` PresencePenalty float64 `json:"presence_penalty,omitempty"` FrequencyPenalty float64 `json:"frequency_penalty,omitempty"` LogitBias map[string]int `json:"logit_bias,omitempty"` User string `json:"user,omitempty"` Seed *int `json:"seed,omitempty"` Tools []Tool `json:"tools,omitempty"` ToolChoice any `json:"tool_choice,omitempty"` LogProbs *bool `json:"logprobs,omitempty"` ResponseFormat *ResponseFormat `json:"response_format,omitempty"` TopK *float64 `json:"top_k,omitempty"` RepetitionPenalty *float64 `json:"repetition_penalty,omitempty"` TopLogProbs *int `json:"top_logprobs,omitempty"` MinP *float64 `json:"min_p,omitempty"` TopA *float64 `json:"top_a,omitempty"` Prediction *Prediction `json:"prediction,omitempty"` // OpenRouter-specific fields Models []string `json:"models,omitempty"` Route string `json:"route,omitempty"` Transforms []string `json:"transforms,omitempty"` Reasoning *ReasoningParams `json:"reasoning,omitempty"` Usage *UsageParams `json:"usage,omitempty"` ExtraBody map[string]any `json:"-"` Plugins []Plugin `json:"plugins,omitempty"` // Tool calling behavior ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"` }
ChatCompletionRequest is a request to create a chat completion.
func (ChatCompletionRequest) MarshalJSON ¶
func (r ChatCompletionRequest) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler.
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 is a response to a chat completion request.
type ChatCompletionStream ¶
type ChatCompletionStream struct {
*StreamReader
}
ChatCompletionStream is a stream of chat completion responses.
func (*ChatCompletionStream) Recv ¶
func (s *ChatCompletionStream) Recv() (response ChatCompletionStreamResponse, err error)
Recv reads a response from the stream.
type ChatCompletionStreamChoice ¶
type ChatCompletionStreamChoice struct { Index int `json:"index"` Delta ChatCompletionMessage `json:"delta"` FinishReason string `json:"finish_reason"` NativeFinishReason string `json:"native_finish_reason,omitempty"` Logprobs *ChatCompletionStreamChoiceLogprobs `json:"logprobs,omitempty"` }
ChatCompletionStreamChoice is a choice in a chat completion stream response.
type ChatCompletionStreamChoiceDelta ¶
type ChatCompletionStreamChoiceDelta struct { Token string `json:"token"` LogProb float64 `json:"logprob"` Bytes []byte `json:"bytes,omitempty"` }
ChatCompletionStreamChoiceDelta represents an incremental token logprob record.
type ChatCompletionStreamChoiceLogprobs ¶
type ChatCompletionStreamChoiceLogprobs struct { Content []ChatCompletionStreamChoiceDelta `json:"content,omitempty"` Refusal []ChatCompletionStreamChoiceDelta `json:"refusal,omitempty"` }
ChatCompletionStreamChoiceLogprobs contains partial token-level logprob deltas.
type ChatCompletionStreamResponse ¶
type ChatCompletionStreamResponse struct { ID string `json:"id"` Object string `json:"object"` Created int64 `json:"created"` Model string `json:"model"` Choices []ChatCompletionStreamChoice `json:"choices"` SystemFingerprint string `json:"system_fingerprint,omitempty"` Usage *Usage `json:"usage,omitempty"` }
ChatCompletionStreamResponse is a response to a chat completion stream request.
type ChatCompletionTokenLogprob ¶
type ChatCompletionTokenLogprob struct { Token string `json:"token"` LogProb float64 `json:"logprob"` Bytes []byte `json:"bytes,omitempty"` TopLogProbs []ChatCompletionTokenLogprobTopLogprob `json:"top_logprobs,omitempty"` }
ChatCompletionTokenLogprob represents a single token and logprob details.
type ChatCompletionTokenLogprobTopLogprob ¶
type ChatCompletionTokenLogprobTopLogprob struct { Token string `json:"token"` LogProb float64 `json:"logprob"` Bytes []byte `json:"bytes,omitempty"` }
ChatCompletionTokenLogprobTopLogprob represents an alternative token candidate.
type Choice ¶
type Choice struct { Index int `json:"index"` Message ChatCompletionMessage `json:"message"` FinishReason string `json:"finish_reason"` NativeFinishReason string `json:"native_finish_reason,omitempty"` Logprobs *ChatCompletionChoiceLogprobs `json:"logprobs,omitempty"` }
Choice is a choice in a chat completion response.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is a client for the OpenRouter API.
func NewClientWithConfig ¶
func NewClientWithConfig(config ClientConfig) *Client
NewClientWithConfig creates a new OpenRouter API client with a custom configuration.
func (*Client) CheckCredits ¶
CheckCredits retrieves the rate limit and credits remaining for the current API key.
func (*Client) CreateChatCompletion ¶
func (c *Client) CreateChatCompletion(ctx context.Context, r ChatCompletionRequest) (*ChatCompletionResponse, error)
CreateChatCompletion creates a chat completion.
func (*Client) CreateChatCompletionStream ¶
func (c *Client) CreateChatCompletionStream(ctx context.Context, r ChatCompletionRequest) (*ChatCompletionStream, error)
CreateChatCompletionStream creates a chat completion stream.
func (*Client) GetGeneration ¶
GetGeneration retrieves the full generation information for a given ID. This is useful for getting precise token counts and cost for a request.
func (*Client) ListModels ¶
func (c *Client) ListModels(ctx context.Context) (*ModelsList, error)
ListModels retrieves the list of available models from OpenRouter.
type ClientConfig ¶
type ClientConfig struct { AuthToken string BaseURL string OrgID string HTTPClient *http.Client SiteURL string // The URL of your app or site. SiteName string // The name of your app or site. // Deprecated: use AuthToken instead. APIKey string }
ClientConfig is a configuration of a client.
func DefaultConfig ¶
func DefaultConfig(authToken string) ClientConfig
DefaultConfig returns a default configuration for the OpenRouter API client.
func (ClientConfig) String ¶
func (ClientConfig) String() string
type ErrorResponse ¶
type ErrorResponse struct {
Error *APIError `json:"error,omitempty"`
}
ErrorResponse is the response from the OpenRouter API when an error occurs.
type File ¶
type File struct { Filename string `json:"filename"` FileData string `json:"file_data"` // base64 encoded }
File is a file attachment. OpenRouter specific.
type FileParserConfig ¶
type FileParserConfig struct {
PDF *PDFPlugin `json:"pdf,omitempty"`
}
FileParserConfig configures the file-parser plugin.
type Function ¶
type Function struct { Name string `json:"name"` Description string `json:"description,omitempty"` Parameters any `json:"parameters,omitempty"` Arguments string `json:"arguments,omitempty"` // For tool call responses }
Function is a function the model can call.
type Generation ¶
type Generation struct { ID string `json:"id"` Model string `json:"model"` CreatedAt string `json:"created_at"` PromptTokens int `json:"tokens_prompt"` CompletionTokens int `json:"tokens_completion"` NativePromptTokens int `json:"native_tokens_prompt"` NativeCompletionTokens int `json:"native_tokens_completion"` FinishReason string `json:"finish_reason"` NativeFinishReason string `json:"native_finish_reason"` TotalCost float64 `json:"total_cost"` }
Generation contains the detailed statistics for a single generation.
type GenerationResponse ¶
type GenerationResponse struct {
Data Generation `json:"data"`
}
GenerationResponse is the top-level response from the /generation endpoint.
type JSONSchema ¶
type JSONSchema struct { Name string `json:"name"` Strict bool `json:"strict"` Schema any `json:"schema"` }
JSONSchema is the schema for the JSON response format.
type KeyCheckResponse ¶
type KeyCheckResponse struct {
Data KeyData `json:"data"`
}
KeyCheckResponse is the response from the /auth/key endpoint.
type KeyData ¶
type KeyData struct { Label string `json:"label"` Usage float64 `json:"usage"` Limit float64 `json:"limit"` IsFreeTier bool `json:"is_free_tier"` }
KeyData contains the details for an API key.
type Model ¶
type Model struct { ID string `json:"id"` Name string `json:"name"` Description string `json:"description"` ContextSize int `json:"context_length"` Architecture any `json:"architecture"` TopProvider any `json:"top_provider"` Pricing Pricing `json:"pricing"` }
Model represents a single model from the /models endpoint. The schema is inferred from common API patterns.
type ModelsList ¶
type ModelsList struct {
Data []Model `json:"data"`
}
ModelsList is a response from the /models endpoint.
type PDFPlugin ¶
type PDFPlugin struct {
Engine string `json:"engine"`
}
PDFPlugin config for file-parser PDF processing.
type Prediction ¶
Prediction is the predicted output for latency optimization.
type Pricing ¶
type Pricing struct { Prompt string `json:"prompt"` Completion string `json:"completion"` Request string `json:"request"` Image string `json:"image"` }
Pricing represents the pricing information for a model.
type ProviderError ¶
ProviderError provides provider-specific error details (if available).
func (*ProviderError) Message ¶
func (e *ProviderError) Message() any
type ReasoningDetail ¶
type ReasoningDetail struct { Type string `json:"type"` Summary string `json:"summary,omitempty"` Encrypted string `json:"encrypted,omitempty"` Text string `json:"text,omitempty"` Signature string `json:"signature,omitempty"` }
ReasoningDetail is a detail about the reasoning process.
type ReasoningParams ¶
type ReasoningParams struct { Exclude bool `json:"exclude,omitempty"` MaxTokens int `json:"max_tokens,omitempty"` Effort string `json:"effort,omitempty"` // Can be "high", "medium", "low" }
ReasoningParams specifies parameters for reasoning token generation. One of MaxTokens or Effort should be specified.
type RequestError ¶
RequestError provides information about generic request errors.
func (*RequestError) Error ¶
func (e *RequestError) Error() string
func (*RequestError) Unwrap ¶
func (e *RequestError) Unwrap() error
type ResponseFormat ¶
type ResponseFormat struct { Type string `json:"type"` JSONSchema *JSONSchema `json:"json_schema,omitempty"` }
ResponseFormat is the format of the response.
type SearchContextSize ¶
type SearchContextSize string
const ( SearchContextSizeLow SearchContextSize = "low" SearchContextSizeMedium SearchContextSize = "medium" SearchContextSizeHigh SearchContextSize = "high" )
type StreamOptions ¶
type StreamOptions struct { // If set, an extra chunk will be sent before the [DONE] message with aggregated usage. IncludeUsage bool `json:"include_usage,omitempty"` }
StreamOptions provides additional control for streaming responses.
type StreamReader ¶
type StreamReader struct {
// contains filtered or unexported fields
}
func (*StreamReader) Close ¶
func (s *StreamReader) Close()
func (*StreamReader) Recv ¶
func (s *StreamReader) Recv() ([]byte, error)
type TokensDetails ¶
type TokensDetails struct { CachedTokens int `json:"cached_tokens,omitempty"` ReasoningTokens int `json:"reasoning_tokens,omitempty"` }
TokensDetails provides more detail on token usage.
type ToolCall ¶
type ToolCall struct { Index int `json:"index,omitempty"` ID string `json:"id,omitempty"` Type string `json:"type,omitempty"` Function Function `json:"function,omitempty"` }
ToolCall is a call to a tool.
type Usage ¶
type Usage struct { PromptTokens int `json:"prompt_tokens"` CompletionTokens int `json:"completion_tokens"` TotalTokens int `json:"total_tokens"` Cost float64 `json:"cost,omitempty"` PromptTokensDetails *TokensDetails `json:"prompt_tokens_details,omitempty"` CompletionTokensDetails *TokensDetails `json:"completion_tokens_details,omitempty"` }
Usage is the usage of the model.
type UsageParams ¶
type UsageParams struct {
Include bool `json:"include"`
}
UsageParams is for OpenRouter's usage accounting feature.
type WebSearchOptions ¶
type WebSearchOptions struct {
SearchContextSize SearchContextSize `json:"search_context_size"`
}
WebSearchOptions config for the web search plugin.
Source Files
¶
Directories
¶
Path | Synopsis |
---|---|
examples
|
|
chat
command
|
|
chat_caching
command
|
|
chat_caching_openai
command
|
|
chat_deepseek_thinking
command
|
|
chat_extra_body
command
|
|
chat_file_attachment
command
|
|
chat_reasoning
command
|
|
chat_stream
command
|
|
chat_vision
command
|
|
check_credits
command
|
|
get_generation
command
|
|
list_models
command
|
|
logprobs
command
|
|
plugins/file_parser_pdf
command
|
|
plugins/web_search
command
|
|
stream_cancel
command
|
|
stream_include_usage
command
|
|
structured_output
command
|
|
tool_call_loop
command
|