Documentation
¶
Overview ¶
Package litellm provides a unified interface for accessing multiple Large Language Model (LLM) platforms.
Design Philosophy ¶
LiteLLM is designed with simplicity and elegance in mind:
- Single Entry Point: Only litellm.New() - no confusing choice between multiple APIs
- Auto-Resolution: Models automatically resolve to correct providers (gpt-4o → OpenAI, claude → Anthropic)
- Type-Safe Configuration: WithOpenAI(), WithAnthropic() instead of error-prone string-based config
- Zero Configuration: Works immediately with environment variables
- Provider-Agnostic: Same code works across all AI providers
Quick Start ¶
The simplest way to get started is using Quick():
response, err := litellm.Quick("gemini-3.0-pro", "Hello, LiteLLM!")
if err != nil {
log.Fatal(err)
}
fmt.Println(response.Content)
Full Example ¶
For production use, create a client with explicit configuration:
client, err := litellm.New(
litellm.WithOpenAI(os.Getenv("OPENAI_API_KEY")),
litellm.WithAnthropic(os.Getenv("ANTHROPIC_API_KEY")),
litellm.WithDefaults(2048, 0.7),
litellm.WithRetries(3, 1*time.Second),
)
if err != nil {
log.Fatal(err)
}
response, err := client.Chat(context.Background(), &litellm.Request{
Model: "gpt-5.1-mini",
Messages: []litellm.Message{
{Role: "user", Content: "Explain quantum computing"},
},
MaxTokens: litellm.IntPtr(500),
Temperature: litellm.Float64Ptr(0.8),
})
Streaming ¶
Real-time streaming responses:
stream, err := client.Stream(ctx, &litellm.Request{
Model: "claude-4.5-sonnet",
Messages: []litellm.Message{
{Role: "user", Content: "Write a story"},
},
})
if err != nil {
log.Fatal(err)
}
defer stream.Close()
for {
chunk, err := stream.Next()
if err != nil || chunk.Done {
break
}
fmt.Print(chunk.Content)
}
Function Calling ¶
Unified tool calling across providers:
tools := []litellm.Tool{
{
Type: "function",
Function: litellm.FunctionDef{
Name: "get_weather",
Description: "Get weather information",
Parameters: schema,
},
},
}
response, err := client.Chat(ctx, &litellm.Request{
Model: "gpt-5.1",
Messages: messages,
Tools: tools,
ToolChoice: "auto",
})
Structured Outputs ¶
JSON Schema validation for reliable responses:
response, err := client.Chat(ctx, &litellm.Request{
Model: "gpt-4o",
Messages: messages,
ResponseFormat: litellm.NewResponseFormatJSONSchema(
"person",
"A person's profile",
schema,
true, // strict mode
),
})
Reasoning Models ¶
Support for OpenAI o-series and other reasoning models:
response, err := client.Chat(ctx, &litellm.Request{
Model: "gpt-5.1",
Messages: messages,
ReasoningEffort: "medium",
ReasoningSummary: "detailed",
MaxTokens: litellm.IntPtr(1000),
})
if response.Reasoning != nil {
fmt.Printf("Reasoning: %s\n", response.Reasoning.Summary)
}
Supported Providers ¶
- OpenAI: GPT-5, GPT-4o, o-series reasoning models
- Anthropic: Claude 4/4.5 family
- Google Gemini: Gemini 2.5/3.0 Pro/Flash
- DeepSeek: Chat and Reasoner models
- Qwen: Alibaba's Qwen3-Coder family
- GLM: ZhiPu AI's GLM-4.6 family
- OpenRouter: 200+ models from multiple providers
Custom Providers ¶
Extend with your own providers:
type MyProvider struct {
// implement litellm.Provider interface
}
litellm.RegisterProvider("myprovider", NewMyProvider)
client, err := litellm.New(
litellm.WithProviderConfig("myprovider", config),
)
Error Handling ¶
Structured error types with retry information:
response, err := client.Chat(ctx, req)
if err != nil {
if litellm.IsRateLimitError(err) {
retryAfter := litellm.GetRetryAfter(err)
log.Printf("Rate limited, retry after %d seconds", retryAfter)
} else if litellm.IsRetryableError(err) {
log.Printf("Retryable error: %v", err)
} else {
log.Printf("Permanent error: %v", err)
}
}
Environment Variables ¶
Auto-discovery uses these environment variables:
OPENAI_API_KEY - OpenAI API key ANTHROPIC_API_KEY - Anthropic API key GEMINI_API_KEY - Google Gemini API key DEEPSEEK_API_KEY - DeepSeek API key QWEN_API_KEY - Alibaba Qwen API key GLM_API_KEY - ZhiPu GLM API key OPENROUTER_API_KEY - OpenRouter API key
Resilience Configuration ¶
Optional retry mechanism with exponential backoff:
client, err := litellm.New(
litellm.WithOpenAI(apiKey),
litellm.WithRetries(3, 1*time.Second),
litellm.WithTimeout(60*time.Second),
)
Thread Safety ¶
The Client is safe for concurrent use. However, StreamReader instances are NOT thread-safe and should be used by a single goroutine at a time. Always call defer stream.Close() to prevent resource leaks.
Best Practices ¶
1. Reuse Client instances - they maintain connection pools 2. Always defer stream.Close() when using streaming 3. Use context for cancellation and timeouts 4. Handle errors with type-specific checks 5. Use WithRetries() for production resilience
For more examples, see https://github.com/voocel/litellm/tree/main/examples
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 ( ContextKeyRequestID contextKey = "request_id" ContextKeyRetryCount contextKey = "retry_count" ContextKeyProvider contextKey = "provider" )
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
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"`
ContextWindow int `json:"context_window,omitempty"`
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
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 0 (no retry)
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.
IMPORTANT: Always call Close() to prevent resource leaks. Use defer immediately after creating the stream:
stream, err := client.Stream(ctx, req)
if err != nil {
return err
}
defer stream.Close() // Must call to release resources
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