Documentation
¶
Index ¶
- Constants
- Variables
- func BoolPtr(v bool) *bool
- func Float64Ptr(v float64) *float64
- func GetRetryAfter(err error) int
- func HasChatCapability(p any) bool
- func HasModelCapability(p any) bool
- func HasStreamCapability(p any) bool
- func IntPtr(v int) *int
- func IsAuthError(err error) bool
- func IsModelError(err error) bool
- func IsNetworkError(err error) bool
- func IsProviderRegistered(name string) bool
- func IsRateLimitError(err error) bool
- func IsRetryableError(err error) bool
- func IsValidationError(err error) bool
- func ListRegisteredProviders() []string
- func RegisterProvider(name string, factory ProviderFactory) error
- func SupportsCapability(p Provider, model string, capability ModelCapability) bool
- func WrapError(err error, provider string) error
- type CacheControl
- type ChatProvider
- type Client
- type ClientOption
- func WithAnthropic(apiKey string, baseURL ...string) ClientOption
- func WithDeepSeek(apiKey string, baseURL ...string) ClientOption
- func WithDefaults(maxTokens int, temperature float64) ClientOption
- func WithGLM(apiKey string, baseURL ...string) ClientOption
- func WithGemini(apiKey string, baseURL ...string) ClientOption
- func WithOpenAI(apiKey string, baseURL ...string) ClientOption
- func WithOpenRouter(apiKey string, baseURL ...string) ClientOption
- func WithProvider(name string, provider Provider) ClientOption
- func WithProviderConfig(name string, config ProviderConfig) ClientOption
- func WithQwen(apiKey string, baseURL ...string) ClientOption
- func WithResilience(config ResilienceConfig) ClientOption
- func WithRetries(maxRetries int, initialDelay time.Duration) ClientOption
- func WithRouter(router Router) ClientOption
- func WithTimeout(timeout time.Duration) ClientOption
- type Config
- type CustomRouterFunc
- type DefaultConfig
- type ErrorType
- type FallbackStrategy
- type FunctionCall
- type FunctionDef
- type JSONSchema
- type LiteLLMError
- func NewAuthError(provider, message string) *LiteLLMError
- func NewError(errorType ErrorType, message string) *LiteLLMError
- func NewErrorWithCause(errorType ErrorType, message string, cause error) *LiteLLMError
- func NewHTTPError(provider string, statusCode int, message string) *LiteLLMError
- func NewModelError(provider, model, message string) *LiteLLMError
- func NewNetworkError(provider, message string, cause error) *LiteLLMError
- func NewProviderError(provider string, errorType ErrorType, message string) *LiteLLMError
- func NewRateLimitError(provider, message string, retryAfter int) *LiteLLMError
- func NewTimeoutError(provider, message string) *LiteLLMError
- func NewValidationError(provider, message string) *LiteLLMError
- type Message
- type ModelCapability
- type ModelInfo
- type ModelProvider
- type Option
- type Provider
- type ProviderConfig
- type ProviderFactory
- type ReasoningChunk
- type ReasoningData
- type Request
- type ResilienceConfig
- type ResilientHTTPClient
- type Response
- type ResponseFormat
- type RouteStrategy
- type Router
- type SmartRouter
- type StreamChunk
- type StreamProvider
- type StreamReader
- type Tool
- type ToolCall
- type ToolCallDelta
- type Usage
Constants ¶
const ( CacheTypeEphemeral = "ephemeral" CacheTypePersistent = "persistent" )
Cache control types
const ( ChunkTypeContent = "content" ChunkTypeToolCallDelta = "tool_call_delta" ChunkTypeReasoning = "reasoning" )
Chunk types for streaming
const ( ResponseFormatText = "text" ResponseFormatJSONObject = "json_object" ResponseFormatJSONSchema = "json_schema" )
Response format types
const ( ContextKeyRequestID contextKey = "request_id" ContextKeyRetryCount contextKey = "retry_count" ContextKeyProvider contextKey = "provider" )
Variables ¶
var DefaultRouter = NewAutoRouter().WithFallback(FallbackNone)
Default router instance (By default, do not downgrade to avoid misrouting)
Functions ¶
func Float64Ptr ¶
Float64Ptr returns a pointer to a float64 value
func GetRetryAfter ¶ added in v1.5.0
GetRetryAfter extracts retry-after duration from rate limit errors
func HasChatCapability ¶ added in v1.5.0
HasChatCapability checks if provider supports chat
func HasModelCapability ¶ added in v1.5.0
HasModelCapability checks if provider supports model information
func HasStreamCapability ¶ added in v1.5.0
HasStreamCapability checks if provider supports streaming
func IsAuthError ¶ added in v1.5.0
IsAuthError checks if error is authentication related
func IsModelError ¶ added in v1.5.0
IsModelError checks if error is model related
func IsNetworkError ¶ added in v1.5.0
IsNetworkError checks if error is network related
func IsProviderRegistered ¶ added in v1.5.0
IsProviderRegistered checks if a provider is registered (built-in or custom)
func IsRateLimitError ¶ added in v1.5.0
IsRateLimitError checks if error is rate limit related
func IsRetryableError ¶ added in v1.5.0
IsRetryableError checks if an error is retryable
func IsValidationError ¶ added in v1.5.0
IsValidationError checks if error is validation related
func ListRegisteredProviders ¶ added in v1.5.0
func ListRegisteredProviders() []string
ListRegisteredProviders returns all registered provider names
func RegisterProvider ¶
func RegisterProvider(name string, factory ProviderFactory) error
RegisterProvider registers a custom provider factory Returns an error if the name is empty or factory is nil
func SupportsCapability ¶ added in v1.5.0
func SupportsCapability(p Provider, model string, capability ModelCapability) bool
SupportsCapability checks if provider supports a specific model capability
Types ¶
type CacheControl ¶ added in v1.5.0
type CacheControl struct {
Type string `json:"type"` // "ephemeral" or "persistent"
TTL *int `json:"ttl,omitempty"` // Time to live in seconds (optional)
}
CacheControl defines prompt caching behavior
func NewCacheControl ¶ added in v1.5.0
func NewCacheControl(cacheType string, ttlSeconds ...int) *CacheControl
NewCacheControl creates a cache control with specified type and optional TTL
func NewEphemeralCache ¶ added in v1.5.0
func NewEphemeralCache() *CacheControl
NewEphemeralCache creates an ephemeral cache control (default 5 minutes)
func NewPersistentCache ¶ added in v1.5.0
func NewPersistentCache(ttlSeconds int) *CacheControl
NewPersistentCache creates a persistent cache control with custom TTL
type ChatProvider ¶ added in v1.5.0
ChatProvider defines the basic chat completion capability
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client is the main LLM client
func New ¶
func New(opts ...ClientOption) (*Client, error)
New creates a new LiteLLM client with optional configuration
func (*Client) AddProvider ¶
AddProvider adds a provider to the client
type ClientOption ¶
ClientOption defines options for configuring the client
func WithAnthropic ¶
func WithAnthropic(apiKey string, baseURL ...string) ClientOption
WithAnthropic adds Anthropic provider with custom configuration
func WithDeepSeek ¶ added in v1.1.0
func WithDeepSeek(apiKey string, baseURL ...string) ClientOption
WithDeepSeek adds DeepSeek provider with custom configuration
func WithDefaults ¶
func WithDefaults(maxTokens int, temperature float64) ClientOption
WithDefaults sets default configuration values
func WithGLM ¶ added in v1.2.0
func WithGLM(apiKey string, baseURL ...string) ClientOption
WithGLM adds GLM provider with custom configuration
func WithGemini ¶
func WithGemini(apiKey string, baseURL ...string) ClientOption
WithGemini adds Gemini provider with custom configuration
func WithOpenAI ¶
func WithOpenAI(apiKey string, baseURL ...string) ClientOption
WithOpenAI adds OpenAI provider with custom configuration
func WithOpenRouter ¶ added in v1.1.0
func WithOpenRouter(apiKey string, baseURL ...string) ClientOption
WithOpenRouter adds OpenRouter provider with custom configuration
func WithProvider ¶
func WithProvider(name string, provider Provider) ClientOption
WithProvider adds a custom provider
func WithProviderConfig ¶
func WithProviderConfig(name string, config ProviderConfig) ClientOption
WithProviderConfig adds a provider using ProviderConfig
func WithQwen ¶ added in v1.1.0
func WithQwen(apiKey string, baseURL ...string) ClientOption
WithQwen adds Qwen provider with custom configuration
func WithResilience ¶ added in v1.2.2
func WithResilience(config ResilienceConfig) ClientOption
WithResilience sets default resilience configuration
func WithRetries ¶ added in v1.2.2
func WithRetries(maxRetries int, initialDelay time.Duration) ClientOption
WithRetries sets retry configuration for all providers
func WithRouter ¶ added in v1.5.0
func WithRouter(router Router) ClientOption
WithRouter sets a custom router for provider selection
func WithTimeout ¶ added in v1.2.2
func WithTimeout(timeout time.Duration) ClientOption
WithTimeout sets request timeout for all providers
type Config ¶ added in v1.5.0
type Config struct {
MaxTokens int `json:"max_tokens"`
Temperature float64 `json:"temperature"`
Timeout time.Duration `json:"timeout"`
Retries int `json:"retries"`
Extra map[string]any `json:"extra,omitempty"`
}
Config holds client configuration
type CustomRouterFunc ¶ added in v1.5.0
CustomRouterFunc allows users to provide custom routing logic
type DefaultConfig ¶
type DefaultConfig struct {
MaxTokens int `json:"max_tokens"`
Temperature float64 `json:"temperature"`
Resilience ResilienceConfig `json:"resilience"`
}
DefaultConfig holds default configuration values
type ErrorType ¶ added in v1.5.0
type ErrorType string
ErrorType represents different categories of errors
const ( ErrorTypeAuth ErrorType = "auth" // Authentication/authorization errors ErrorTypeRateLimit ErrorType = "rate_limit" // Rate limiting errors ErrorTypeNetwork ErrorType = "network" // Network connectivity errors ErrorTypeValidation ErrorType = "validation" // Request validation errors ErrorTypeProvider ErrorType = "provider" // Provider-specific errors ErrorTypeTimeout ErrorType = "timeout" // Timeout errors ErrorTypeQuota ErrorType = "quota" // Quota/billing errors ErrorTypeModel ErrorType = "model" // Model not found/supported errors ErrorTypeInternal ErrorType = "internal" // Internal library errors )
type FallbackStrategy ¶ added in v1.5.0
type FallbackStrategy string
FallbackStrategy defines what to do when primary routing fails
const ( FallbackNone FallbackStrategy = "none" // Fail immediately FallbackFirst FallbackStrategy = "first" // Use first available provider FallbackAny FallbackStrategy = "any" // Try any provider that supports the capability FallbackBest FallbackStrategy = "best" // Use provider with best capability match )
type FunctionCall ¶
type FunctionCall struct {
Name string `json:"name"`
Arguments string `json:"arguments"` // JSON string
}
FunctionCall represents the function call details
type FunctionDef ¶ added in v1.5.0
type FunctionDef struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters any `json:"parameters"`
}
FunctionDef represents a function definition
type JSONSchema ¶ added in v1.2.1
type JSONSchema struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Schema any `json:"schema"`
Strict *bool `json:"strict,omitempty"`
}
JSONSchema defines structured JSON output schema
type LiteLLMError ¶ added in v1.5.0
type LiteLLMError struct {
Type ErrorType `json:"type"`
Code string `json:"code,omitempty"`
Message string `json:"message"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
Cause error `json:"-"` // Original error, not serialized
// HTTP details if applicable
StatusCode int `json:"status_code,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
// Retry information
Retryable bool `json:"retryable"`
RetryAfter int `json:"retry_after,omitempty"` // seconds
}
LiteLLMError represents a structured error with categorization
func NewAuthError ¶ added in v1.5.0
func NewAuthError(provider, message string) *LiteLLMError
NewAuthError creates an authentication error
func NewError ¶ added in v1.5.0
func NewError(errorType ErrorType, message string) *LiteLLMError
NewError creates a new LiteLLMError
func NewErrorWithCause ¶ added in v1.5.0
func NewErrorWithCause(errorType ErrorType, message string, cause error) *LiteLLMError
NewErrorWithCause creates a new LiteLLMError with an underlying cause
func NewHTTPError ¶ added in v1.5.0
func NewHTTPError(provider string, statusCode int, message string) *LiteLLMError
NewHTTPError creates an error from HTTP response
func NewModelError ¶ added in v1.5.0
func NewModelError(provider, model, message string) *LiteLLMError
NewModelError creates a model-related error
func NewNetworkError ¶ added in v1.5.0
func NewNetworkError(provider, message string, cause error) *LiteLLMError
NewNetworkError creates a network error
func NewProviderError ¶ added in v1.5.0
func NewProviderError(provider string, errorType ErrorType, message string) *LiteLLMError
NewProviderError creates a provider-specific error
func NewRateLimitError ¶ added in v1.5.0
func NewRateLimitError(provider, message string, retryAfter int) *LiteLLMError
NewRateLimitError creates a rate limit error
func NewTimeoutError ¶ added in v1.5.0
func NewTimeoutError(provider, message string) *LiteLLMError
NewTimeoutError creates a timeout error
func NewValidationError ¶ added in v1.5.0
func NewValidationError(provider, message string) *LiteLLMError
NewValidationError creates a validation error
func (*LiteLLMError) Error ¶ added in v1.5.0
func (e *LiteLLMError) Error() string
Error implements the error interface
func (*LiteLLMError) Is ¶ added in v1.5.0
func (e *LiteLLMError) Is(target error) bool
Is checks if the error matches a specific type
func (*LiteLLMError) IsRetryable ¶ added in v1.5.0
func (e *LiteLLMError) IsRetryable() bool
IsRetryable returns whether this error can be retried
func (*LiteLLMError) Unwrap ¶ added in v1.5.0
func (e *LiteLLMError) Unwrap() error
Unwrap returns the underlying error
type Message ¶
type Message struct {
Role string `json:"role"` // user, assistant, system, tool
Content string `json:"content"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
CacheControl *CacheControl `json:"cache_control,omitempty"`
}
Message represents a conversation message
type ModelCapability ¶
type ModelCapability string
ModelCapability represents what a model can do
const ( CapabilityChat ModelCapability = "chat" CapabilityFunctionCall ModelCapability = "function_call" CapabilityVision ModelCapability = "vision" CapabilityReasoning ModelCapability = "reasoning" CapabilityCode ModelCapability = "code" )
type ModelInfo ¶
type ModelInfo struct {
ID string `json:"id"`
Name string `json:"name"`
Provider string `json:"provider"`
MaxTokens int `json:"max_tokens"`
Capabilities []ModelCapability `json:"capabilities"`
}
ModelInfo contains information about a model
type ModelProvider ¶ added in v1.5.0
ModelProvider defines model information capability
type Option ¶ added in v1.5.0
type Option func(*Client)
Option is a functional option for configuring the client
type Provider ¶
type Provider interface {
ChatProvider
StreamProvider
ModelProvider
// Basic provider info
Name() string
Validate() error
}
Provider combines all capabilities through interface composition Implementations can choose which interfaces to support
type ProviderConfig ¶
type ProviderConfig struct {
APIKey string `json:"api_key"`
BaseURL string `json:"base_url,omitempty"`
// Resilience configuration integrated directly
Resilience ResilienceConfig `json:"resilience,omitempty"`
// Provider-specific extras
Extra map[string]any `json:"extra,omitempty"`
}
ProviderConfig contains provider-specific configuration
type ProviderFactory ¶
type ProviderFactory func(config ProviderConfig) Provider
ProviderFactory is a function that creates a provider instance
type ReasoningChunk ¶
type ReasoningChunk struct {
Content string `json:"content,omitempty"`
Summary string `json:"summary,omitempty"`
}
ReasoningChunk represents incremental reasoning data
type ReasoningData ¶
type ReasoningData struct {
Content string `json:"content,omitempty"` // Full reasoning content
Summary string `json:"summary,omitempty"` // Reasoning summary
TokensUsed int `json:"tokens_used,omitempty"`
}
ReasoningData contains reasoning information for advanced models
type Request ¶
type Request struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
MaxTokens *int `json:"max_tokens,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
Stream bool `json:"stream,omitempty"`
Tools []Tool `json:"tools,omitempty"`
ToolChoice any `json:"tool_choice,omitempty"`
// Response format for structured output
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
// Stop sequences - custom text sequences that will cause the model to stop generating
// OpenAI: uses "stop" parameter (string or array, up to 4 sequences)
// Anthropic: uses "stop_sequences" parameter (array of strings)
Stop []string `json:"stop,omitempty"`
// Reasoning parameters for advanced models
ReasoningEffort string `json:"reasoning_effort,omitempty"`
ReasoningSummary string `json:"reasoning_summary,omitempty"`
UseResponsesAPI bool `json:"use_responses_api,omitempty"`
// Prompt caching control
CacheControl *CacheControl `json:"cache_control,omitempty"`
// Provider-specific extensions
Extra map[string]any `json:"extra,omitempty"`
}
Request represents a completion request
type ResilienceConfig ¶ added in v1.2.2
type ResilienceConfig struct {
MaxRetries int `json:"max_retries"` // Maximum retry attempts, default 3
InitialDelay time.Duration `json:"initial_delay"` // Initial delay, default 1 second
MaxDelay time.Duration `json:"max_delay"` // Maximum delay, default 30 seconds
Multiplier float64 `json:"multiplier"` // Backoff multiplier, default 2.0
Jitter bool `json:"jitter"` // Whether to add jitter, default true
RequestTimeout time.Duration `json:"request_timeout"` // Single request timeout, default 30 seconds
ConnectTimeout time.Duration `json:"connect_timeout"` // Connection timeout, default 10 seconds
}
ResilienceConfig holds network resilience configuration
func DefaultResilienceConfig ¶ added in v1.2.2
func DefaultResilienceConfig() ResilienceConfig
DefaultResilienceConfig returns default resilience configuration
type ResilientHTTPClient ¶ added in v1.2.2
type ResilientHTTPClient struct {
// contains filtered or unexported fields
}
ResilientHTTPClient wraps http.Client with retry logic
func NewResilientHTTPClient ¶ added in v1.2.2
func NewResilientHTTPClient(config ResilienceConfig) *ResilientHTTPClient
NewResilientHTTPClient creates a new resilient HTTP client
type Response ¶
type Response struct {
Content string `json:"content"`
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
Usage Usage `json:"usage"`
Model string `json:"model"`
Provider string `json:"provider"`
FinishReason string `json:"finish_reason,omitempty"`
Reasoning *ReasoningData `json:"reasoning,omitempty"`
}
Response represents a completion response
type ResponseFormat ¶ added in v1.2.1
type ResponseFormat struct {
Type string `json:"type"` // "text", "json_object", "json_schema"
JSONSchema *JSONSchema `json:"json_schema,omitempty"`
}
ResponseFormat defines the response output format
func NewResponseFormatJSONObject ¶ added in v1.2.1
func NewResponseFormatJSONObject() *ResponseFormat
NewResponseFormatJSONObject creates a JSON object response format
func NewResponseFormatJSONSchema ¶ added in v1.2.1
func NewResponseFormatJSONSchema(name, description string, schema any, strict bool) *ResponseFormat
NewResponseFormatJSONSchema creates a JSON schema response format
func NewResponseFormatText ¶ added in v1.2.1
func NewResponseFormatText() *ResponseFormat
NewResponseFormatText creates a text response format
type RouteStrategy ¶ added in v1.5.0
type RouteStrategy string
RouteStrategy defines different routing strategies
const ( StrategyAuto RouteStrategy = "auto" // Intelligent routing based on context StrategyExact RouteStrategy = "exact" // Exact model match required StrategyFirst RouteStrategy = "first" // Use first available provider StrategyRoundRobin RouteStrategy = "round_robin" // Round-robin selection )
type Router ¶ added in v1.5.0
Router interface defines how to select a provider for a given model
func RouteByProviderName ¶ added in v1.5.0
RouteByProviderName creates a router that selects provider by name
func RouteToProvider ¶ added in v1.5.0
RouteToProvider creates a simple router that always returns a specific provider
type SmartRouter ¶ added in v1.5.0
type SmartRouter struct {
// contains filtered or unexported fields
}
SmartRouter implements intelligent routing logic
func NewAutoRouter ¶ added in v1.5.0
func NewAutoRouter() *SmartRouter
NewAutoRouter creates a router with intelligent automatic routing
func NewExactRouter ¶ added in v1.5.0
func NewExactRouter() *SmartRouter
NewExactRouter creates a router that requires exact model matches
func NewFirstRouter ¶ added in v1.5.0
func NewFirstRouter() *SmartRouter
NewFirstRouter creates a router that uses the first matching provider
func NewRoundRobinRouter ¶ added in v1.5.0
func NewRoundRobinRouter() *SmartRouter
NewRoundRobinRouter creates a router that distributes requests round-robin
func NewSmartRouter ¶ added in v1.5.0
func NewSmartRouter(strategy RouteStrategy) *SmartRouter
NewSmartRouter creates a new smart router
func (*SmartRouter) Route ¶ added in v1.5.0
func (r *SmartRouter) Route(model string, availableProviders []Provider) (Provider, error)
Route implements the Router interface
func (*SmartRouter) WithFallback ¶ added in v1.5.0
func (r *SmartRouter) WithFallback(fallback FallbackStrategy) *SmartRouter
WithFallback sets the fallback strategy
type StreamChunk ¶
type StreamChunk struct {
Type string `json:"type"`
Content string `json:"content,omitempty"`
ToolCallDelta *ToolCallDelta `json:"tool_call_delta,omitempty"`
Reasoning *ReasoningChunk `json:"reasoning,omitempty"`
FinishReason string `json:"finish_reason,omitempty"`
Done bool `json:"done"`
Provider string `json:"provider"`
Model string `json:"model,omitempty"`
Usage *Usage `json:"usage,omitempty"`
}
StreamChunk represents a single chunk in streaming response
type StreamProvider ¶ added in v1.5.0
type StreamProvider interface {
Stream(ctx context.Context, req *Request) (StreamReader, error)
}
StreamProvider defines streaming capability
type StreamReader ¶
type StreamReader interface {
// Next returns the next chunk or io.EOF when done
Next() (*StreamChunk, error)
// Close closes the stream
Close() error
}
StreamReader provides a unified interface for reading streaming responses
Thread Safety: StreamReader is NOT thread-safe. Do not call Next() or Close() concurrently from multiple goroutines. Each StreamReader instance should be used by a single goroutine at a time.
type Tool ¶
type Tool struct {
Type string `json:"type"` // "function"
Function FunctionDef `json:"function"`
}
Tool represents a function tool definition
type ToolCall ¶
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"` // "function"
Function FunctionCall `json:"function"`
}
ToolCall represents a function call from the model
type ToolCallDelta ¶
type ToolCallDelta struct {
Index int `json:"index"`
ID string `json:"id,omitempty"`
Type string `json:"type,omitempty"`
FunctionName string `json:"function_name,omitempty"`
ArgumentsDelta string `json:"arguments_delta,omitempty"`
}
ToolCallDelta represents incremental tool call data
type Usage ¶
type Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
ReasoningTokens int `json:"reasoning_tokens,omitempty"`
// Cache-related token statistics
CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"` // Tokens written to cache
CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"` // Tokens read from cache
}
Usage represents token usage statistics