Documentation
¶
Overview ¶
Package litellm provides a small, explicit multi-provider LLM SDK core.
The root package owns the provider-agnostic domain model: Request, Response, Message, Block, Stream, Event, structured errors, warnings, hooks, and pricing helpers. Concrete providers live in provider-specific subpackages.
Quick Start ¶
Create a provider with its package-specific config, then bind a Client:
import (
"context"
"fmt"
"os"
"github.com/voocel/litellm"
"github.com/voocel/litellm/provider/anthropic"
)
provider, err := anthropic.New(anthropic.Config{
APIKey: os.Getenv("ANTHROPIC_API_KEY"),
})
if err != nil {
panic(err)
}
client, err := litellm.New(provider)
if err != nil {
panic(err)
}
maxTokens := 1024
resp, err := client.Chat(context.Background(), litellm.Request{
Model: "claude-sonnet-4-5",
MaxTokens: &maxTokens,
Messages: []litellm.Message{litellm.UserText("Explain AI in one sentence.")},
})
if err != nil {
panic(err)
}
fmt.Println(resp.Text())
Blocks ¶
Message and Response content is represented as ordered Blocks. This preserves the order of text, reasoning, tool use, tool results, cache markers, and opaque provider signatures across multi-turn agent workflows.
Streaming ¶
Providers stream typed Event values. Use a type switch for real-time handling or Collect to aggregate a stream into a Response: Stream is intended for single-goroutine consumption; do not call Next concurrently.
stream, err := client.Stream(ctx, req)
if err != nil {
panic(err)
}
defer stream.Close()
for {
event, err := stream.Next()
if err != nil {
panic(err)
}
switch e := event.(type) {
case litellm.ContentDelta:
fmt.Print(e.Text)
case litellm.DoneEvent:
return
}
}
Design ¶
The SDK is intentionally not a gateway, router, agent runtime, account system, or request scheduler. It binds one Client to one Provider and exposes explicit configuration and local validation.
Index ¶
- Constants
- Variables
- func Bool(v bool) *bool
- func BoolPtr(v bool) *bool
- func CaptureRawResponse(req *Request, resp *Response, raw []byte)
- func Float64Ptr(v float64) *float64
- func GetRetryAfter(err error) int
- func IntPtr(v int) *int
- func IsAuthError(err error) bool
- func IsContextOverflowError(err error) bool
- func IsModelError(err error) bool
- func IsNetworkError(err error) bool
- func IsOverloadedError(err error) bool
- func IsProviderError(err error) bool
- func IsRateLimitError(err error) bool
- func IsRetryableError(err error) bool
- func IsStreamIdleError(err error) bool
- func IsTimeoutError(err error) bool
- func IsValidationError(err error) bool
- func JSONRaw(v any) (json.RawMessage, error)
- func MustJSONRaw(v any) json.RawMessage
- func NormalizeToolUseID(id string) string
- func PortableThinkingEfforts() []string
- func StringPtr(v string) *string
- func WrapError(err error, provider string) error
- func WrapValidationError(provider string, err error) error
- type Annotation
- type Block
- type CacheCapabilities
- type CacheControl
- type CachePlacement
- type CachePolicy
- type CallMeta
- type Capabilities
- type CapabilityProvider
- type Client
- func (c *Client) Capabilities(model string) Capabilities
- func (c *Client) Chat(ctx context.Context, req Request) (*Response, error)
- func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error)
- func (c *Client) ProviderName() string
- func (c *Client) Stream(ctx context.Context, req Request) (Stream, error)
- func (c *Client) StreamText(ctx context.Context, req Request, fn func(string) error) (resp *Response, err error)
- func (c *Client) StreamWith(ctx context.Context, req Request, handler StreamHandler) (resp *Response, err error)
- type ClientOption
- func WithCaptureRawResponse(enabled bool) ClientOption
- func WithDefaults(defaults RequestDefaults) ClientOption
- func WithHook(h Hook) ClientOption
- func WithHooks(hooks ...Hook) ClientOption
- func WithMessageRepair(policies ...MessageRepairPolicy) ClientOption
- func WithStreamIdleTimeout(timeout time.Duration) ClientOption
- type ContentDelta
- type DoneEvent
- type ErrorEvent
- type ErrorType
- type Event
- type EventCollector
- type FinishReason
- type Hook
- type HookFuncs
- func (h HookFuncs) AfterResponse(ctx context.Context, meta CallMeta, resp *Response, err error)
- func (h HookFuncs) BeforeRequest(ctx context.Context, meta CallMeta, req *Request)
- func (h HookFuncs) OnStreamEnd(ctx context.Context, meta CallMeta, err error)
- func (h HookFuncs) OnStreamEvent(ctx context.Context, meta CallMeta, event Event)
- func (h HookFuncs) OnWarning(ctx context.Context, meta CallMeta, warning Warning)
- type ImageBlock
- 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 NewProviderErrorWithCause(provider string, errorType ErrorType, message string, cause error) *LiteLLMError
- func NewRateLimitError(provider, message string, retryAfter int) *LiteLLMError
- func NewTimeoutError(provider, message string) *LiteLLMError
- func NewValidationError(provider, message string) *LiteLLMError
- type MediaCapabilities
- type Message
- type MessageRepairPolicy
- type ModelInfo
- type ModelLister
- type Provider
- type ProviderEvent
- type ProviderFactory
- type ProviderOptions
- type ReasoningBlock
- type ReasoningCapabilities
- type ReasoningDelta
- type RefusalDelta
- type Registry
- type Request
- type RequestDefaults
- type Response
- type ResponseFormat
- type ResponseFormatType
- type Role
- type Schema
- type Stream
- type StreamHandler
- type StreamingCapabilities
- type StrictMode
- type StructuredCapabilities
- type Support
- type TextBlock
- type Thinking
- type ThinkingCapabilities
- type ThinkingMode
- type Tool
- type ToolCapabilities
- type ToolChoice
- type ToolReferenceBlock
- type ToolResultBlock
- type ToolUseAccumulator
- type ToolUseBlock
- type ToolUseDelta
- type ToolUseDone
- type ToolUseStart
- type Usage
- type UsageCapabilities
- type UsageEvent
- type Warning
- type WarningEvent
Constants ¶
const ( CacheTypeEphemeral = "ephemeral" CacheTTL5m = "5m" CacheTTL1h = "1h" )
Variables ¶
var ErrStreamIdle = errors.New("stream idle timeout")
Functions ¶
func CaptureRawResponse ¶ added in v1.8.0
func Float64Ptr ¶
func GetRetryAfter ¶ added in v1.5.0
func IsAuthError ¶ added in v1.5.0
func IsContextOverflowError ¶ added in v1.6.0
func IsModelError ¶ added in v1.5.0
func IsNetworkError ¶ added in v1.5.0
func IsOverloadedError ¶ added in v1.6.3
func IsProviderError ¶ added in v1.8.0
func IsRateLimitError ¶ added in v1.5.0
func IsRetryableError ¶ added in v1.5.0
func IsStreamIdleError ¶ added in v1.6.8
func IsTimeoutError ¶ added in v1.8.0
func IsValidationError ¶ added in v1.5.0
func MustJSONRaw ¶ added in v1.8.0
func MustJSONRaw(v any) json.RawMessage
func NormalizeToolUseID ¶ added in v1.8.0
func PortableThinkingEfforts ¶ added in v1.8.1
func PortableThinkingEfforts() []string
func WrapValidationError ¶ added in v1.8.0
Types ¶
type Annotation ¶ added in v1.8.0
type Annotation struct {
Type string
Text string
URL string
Extra json.RawMessage
}
type CacheCapabilities ¶ added in v1.8.1
type CacheControl ¶ added in v1.5.0
type CachePlacement ¶ added in v1.8.0
type CachePlacement string
const (
CachePlacementPrefix CachePlacement = "prefix"
)
type CachePolicy ¶ added in v1.8.0
type CachePolicy struct {
Retention string
Placement CachePlacement
}
type Capabilities ¶ added in v1.8.1
type Capabilities struct {
Provider string
Model string
Thinking ThinkingCapabilities
Reasoning ReasoningCapabilities
Tools ToolCapabilities
Structured StructuredCapabilities
Media MediaCapabilities
Cache CacheCapabilities
Streaming StreamingCapabilities
Usage UsageCapabilities
}
func GetCapabilities ¶ added in v1.8.1
func GetCapabilities(provider Provider, model string) Capabilities
type CapabilityProvider ¶ added in v1.8.1
type CapabilityProvider interface {
Capabilities(model string) Capabilities
}
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func (*Client) Capabilities ¶ added in v1.8.1
func (c *Client) Capabilities(model string) Capabilities
func (*Client) ListModels ¶ added in v1.5.5
func (*Client) ProviderName ¶ added in v1.5.7
func (*Client) StreamText ¶ added in v1.8.0
func (c *Client) StreamText(ctx context.Context, req Request, fn func(string) error) (resp *Response, err error)
StreamText opens a stream for req and invokes fn for each text content delta, returning the aggregated Response. It is the simplest way to stream answer text to a UI or writer. It creates and closes the stream for you; use Client.Stream directly when you need the raw event stream.
func (*Client) StreamWith ¶ added in v1.8.0
func (c *Client) StreamWith(ctx context.Context, req Request, handler StreamHandler) (resp *Response, err error)
StreamWith opens a stream for req and dispatches its deltas to handler's callbacks, returning the aggregated Response. Use it to stream reasoning and answer text separately without a type switch. For full event fidelity, use Client.Stream with Handle.
type ClientOption ¶
func WithCaptureRawResponse ¶ added in v1.8.0
func WithCaptureRawResponse(enabled bool) ClientOption
func WithDefaults ¶
func WithDefaults(defaults RequestDefaults) ClientOption
func WithHook ¶ added in v1.6.7
func WithHook(h Hook) ClientOption
func WithHooks ¶ added in v1.6.7
func WithHooks(hooks ...Hook) ClientOption
func WithMessageRepair ¶ added in v1.8.0
func WithMessageRepair(policies ...MessageRepairPolicy) ClientOption
func WithStreamIdleTimeout ¶ added in v1.8.0
func WithStreamIdleTimeout(timeout time.Duration) ClientOption
type ContentDelta ¶ added in v1.8.0
type DoneEvent ¶ added in v1.8.0
type DoneEvent struct {
FinishReason FinishReason
Provider string
Model string
}
type ErrorEvent ¶ added in v1.8.0
type ErrorEvent struct {
Err error
}
type ErrorType ¶ added in v1.5.0
type ErrorType string
const ( ErrorTypeAuth ErrorType = "auth" ErrorTypeRateLimit ErrorType = "rate_limit" ErrorTypeNetwork ErrorType = "network" ErrorTypeValidation ErrorType = "validation" ErrorTypeProvider ErrorType = "provider" ErrorTypeTimeout ErrorType = "timeout" ErrorTypeQuota ErrorType = "quota" ErrorTypeModel ErrorType = "model" ErrorTypeInternal ErrorType = "internal" ErrorTypeContextOverflow ErrorType = "context_overflow" ErrorTypeOverloaded ErrorType = "overloaded" )
type EventCollector ¶ added in v1.8.0
type EventCollector struct {
// contains filtered or unexported fields
}
func (*EventCollector) Apply ¶ added in v1.8.0
func (c *EventCollector) Apply(event Event) (bool, error)
func (*EventCollector) Response ¶ added in v1.8.0
func (c *EventCollector) Response() *Response
type FinishReason ¶ added in v1.8.0
type FinishReason string
const ( FinishReasonStop FinishReason = "stop" FinishReasonLength FinishReason = "length" FinishReasonToolCall FinishReason = "tool_calls" FinishReasonError FinishReason = "error" FinishReasonSafety FinishReason = "safety" )
func NormalizeFinishReason ¶ added in v1.5.7
func NormalizeFinishReason(raw string) FinishReason
type HookFuncs ¶ added in v1.6.7
type HookFuncs struct {
BeforeRequestFunc func(context.Context, CallMeta, *Request)
AfterResponseFunc func(context.Context, CallMeta, *Response, error)
OnStreamEventFunc func(context.Context, CallMeta, Event)
OnStreamEndFunc func(context.Context, CallMeta, error)
OnWarningFunc func(context.Context, CallMeta, Warning)
}
func (HookFuncs) AfterResponse ¶ added in v1.6.7
func (HookFuncs) BeforeRequest ¶ added in v1.6.7
func (HookFuncs) OnStreamEnd ¶ added in v1.6.14
func (HookFuncs) OnStreamEvent ¶ added in v1.8.0
type ImageBlock ¶ added in v1.8.0
type ImageBlock struct {
URL string
Data []byte
MIME string
FileURI string
Detail string
Cache *CacheControl
}
func ImageURL ¶ added in v1.8.0
func ImageURL(url string) ImageBlock
type JSONSchema ¶ added in v1.2.1
type JSONSchema struct {
Name string
Description string
Schema Schema
Strict StrictMode
}
type LiteLLMError ¶ added in v1.5.0
type LiteLLMError struct {
Type ErrorType
Code string
Message string
Provider string
Model string
StatusCode int
Retryable bool
RetryAfter int
Cause error
}
func NewAuthError ¶ added in v1.5.0
func NewAuthError(provider, message string) *LiteLLMError
func NewError ¶ added in v1.5.0
func NewError(errorType ErrorType, message string) *LiteLLMError
func NewErrorWithCause ¶ added in v1.5.0
func NewErrorWithCause(errorType ErrorType, message string, cause error) *LiteLLMError
func NewHTTPError ¶ added in v1.5.0
func NewHTTPError(provider string, statusCode int, message string) *LiteLLMError
func NewModelError ¶ added in v1.5.0
func NewModelError(provider, model, message string) *LiteLLMError
func NewNetworkError ¶ added in v1.5.0
func NewNetworkError(provider, message string, cause error) *LiteLLMError
func NewProviderError ¶ added in v1.5.0
func NewProviderError(provider string, errorType ErrorType, message string) *LiteLLMError
func NewProviderErrorWithCause ¶ added in v1.8.0
func NewProviderErrorWithCause(provider string, errorType ErrorType, message string, cause error) *LiteLLMError
func NewRateLimitError ¶ added in v1.5.0
func NewRateLimitError(provider, message string, retryAfter int) *LiteLLMError
func NewTimeoutError ¶ added in v1.5.0
func NewTimeoutError(provider, message string) *LiteLLMError
func NewValidationError ¶ added in v1.5.0
func NewValidationError(provider, message string) *LiteLLMError
func (*LiteLLMError) Error ¶ added in v1.5.0
func (e *LiteLLMError) Error() string
func (*LiteLLMError) Unwrap ¶ added in v1.5.0
func (e *LiteLLMError) Unwrap() error
type MediaCapabilities ¶ added in v1.8.1
type Message ¶
func AssistantText ¶ added in v1.8.0
func ToolResult ¶ added in v1.8.0
func ToolResultText ¶ added in v1.8.0
type MessageRepairPolicy ¶ added in v1.8.0
type MessageRepairPolicy uint
const ( RepairNone MessageRepairPolicy = 0 RepairNormalizeToolUseIDs MessageRepairPolicy = 1 << iota RepairSynthesizeMissingToolUseIDs RepairInsertMissingToolResults RepairToolUseIDs = RepairNormalizeToolUseIDs | RepairSynthesizeMissingToolUseIDs RepairAll = RepairToolUseIDs | RepairInsertMissingToolResults )
type ModelLister ¶ added in v1.5.5
type ProviderEvent ¶ added in v1.8.0
type ProviderEvent struct {
Name string
Raw json.RawMessage
}
type ProviderFactory ¶
func TypedFactory ¶ added in v1.8.0
func TypedFactory[T any](fn func(T) (Provider, error)) ProviderFactory
type ProviderOptions ¶ added in v1.8.0
type ReasoningBlock ¶ added in v1.8.0
type ReasoningBlock struct {
Text string
Summary bool
Signature string
Redacted []byte
Extra json.RawMessage
Cache *CacheControl
}
type ReasoningCapabilities ¶ added in v1.8.1
type ReasoningDelta ¶ added in v1.8.0
type RefusalDelta ¶ added in v1.8.0
type Registry ¶ added in v1.8.0
type Registry struct {
// contains filtered or unexported fields
}
func NewRegistry ¶ added in v1.8.0
func NewRegistry() *Registry
type Request ¶
type Request struct {
Model string
Messages []Message
MaxTokens *int
Temperature *float64
TopP *float64
Stop []string
Tools []Tool
ToolChoice ToolChoice
ResponseFormat *ResponseFormat
Thinking *Thinking
Cache *CachePolicy
ProviderOptions ProviderOptions
// contains filtered or unexported fields
}
func (*Request) CaptureRawResponse ¶ added in v1.8.3
type RequestDefaults ¶ added in v1.8.0
type Response ¶
type Response struct {
Blocks []Block
Usage Usage
Model string
Provider string
FinishReason FinishReason
Warnings []Warning
Raw json.RawMessage
}
func Collect ¶ added in v1.8.0
Collect consumes the stream and returns the aggregated Response. It errors if the stream ends before a DoneEvent.
func Handle ¶ added in v1.8.0
Handle consumes the stream, invoking fn for each event as it arrives, and returns the aggregated Response. It is the real-time counterpart to Collect; a nil fn behaves exactly like Collect. If fn returns an error, Handle stops and returns it. The caller still owns Close.
func HandleText ¶ added in v1.8.0
HandleText consumes the stream, invoking fn for each text content delta, and returns the aggregated Response. It is the simplest path for streaming answer text; reasoning and tool events are still aggregated into the Response but are not passed to fn.
func HandleWith ¶ added in v1.8.0
func HandleWith(stream Stream, handler StreamHandler) (*Response, error)
HandleWith consumes the stream, dispatching content and reasoning deltas to the handler's callbacks, and returns the aggregated Response.
func (*Response) ToolCalls ¶
func (r *Response) ToolCalls() []ToolUseBlock
type ResponseFormat ¶ added in v1.2.1
type ResponseFormat struct {
Type ResponseFormatType
JSONSchema *JSONSchema
}
func NewResponseFormatJSONObject ¶ added in v1.2.1
func NewResponseFormatJSONObject() *ResponseFormat
func NewResponseFormatJSONSchema ¶ added in v1.2.1
func NewResponseFormatJSONSchema(name, description string, schema any, strict StrictMode) (*ResponseFormat, error)
func NewResponseFormatText ¶ added in v1.2.1
func NewResponseFormatText() *ResponseFormat
type ResponseFormatType ¶ added in v1.8.0
type ResponseFormatType string
const ( ResponseFormatText ResponseFormatType = "text" ResponseFormatJSONObject ResponseFormatType = "json_object" ResponseFormatJSONSchema ResponseFormatType = "json_schema" )
type Stream ¶ added in v1.8.0
func WithStreamIdleWatchdog ¶ added in v1.8.0
func WithStreamIdleWatchdog(inner Stream, cancel context.CancelFunc, timeout time.Duration, provider string) Stream
WithStreamIdleWatchdog wraps inner with a per-event idle timeout. It returns inner unchanged when timeout <= 0 or inner is nil.
type StreamHandler ¶ added in v1.8.0
StreamHandler routes streamed deltas to per-category callbacks. Unset callbacks are skipped; every event is still aggregated into the returned Response. For full event fidelity (tool-call streaming, provider events), use Handle or the raw Stream.
type StreamingCapabilities ¶ added in v1.8.1
type StrictMode ¶ added in v1.8.0
type StrictMode int
const ( StrictDefault StrictMode = iota StrictEnabled StrictDisabled )
type StructuredCapabilities ¶ added in v1.8.1
type TextBlock ¶ added in v1.8.0
type TextBlock struct {
Text string
Annotations []Annotation
Logprobs json.RawMessage
Cache *CacheControl
}
type Thinking ¶ added in v1.8.0
type Thinking struct {
Mode ThinkingMode
Effort string
BudgetTokens *int
IncludeOutput bool
}
func (*Thinking) HasOptions ¶ added in v1.8.1
type ThinkingCapabilities ¶ added in v1.8.1
type ThinkingCapabilities struct {
Supported Support
Disable Support
Efforts []string
BudgetTokens Support
IncludeOutput Support
Notes []string
}
func (ThinkingCapabilities) SupportsEffort ¶ added in v1.8.1
func (c ThinkingCapabilities) SupportsEffort(effort string) bool
type ThinkingMode ¶ added in v1.8.0
type ThinkingMode int
const ( ThinkingUnspecified ThinkingMode = iota ThinkingDisabled ThinkingEnabled )
type ToolCapabilities ¶ added in v1.8.1
type ToolChoice ¶ added in v1.8.0
type ToolChoice any
type ToolReferenceBlock ¶ added in v1.8.0
type ToolReferenceBlock struct {
ToolName string
Extra json.RawMessage
Cache *CacheControl
}
type ToolResultBlock ¶ added in v1.8.0
type ToolResultBlock struct {
ToolUseID string
Content []Block
IsError bool
Cache *CacheControl
}
type ToolUseAccumulator ¶ added in v1.8.0
type ToolUseAccumulator struct {
// contains filtered or unexported fields
}
func NewToolUseAccumulator ¶ added in v1.8.0
func NewToolUseAccumulator() *ToolUseAccumulator
func (*ToolUseAccumulator) Delta ¶ added in v1.8.0
func (a *ToolUseAccumulator) Delta(delta ToolUseDelta) (string, *ToolUseBlock, error)
func (*ToolUseAccumulator) Done ¶ added in v1.8.0
func (a *ToolUseAccumulator) Done(done ToolUseDone) (string, *ToolUseBlock, error)
func (*ToolUseAccumulator) Start ¶ added in v1.8.0
func (a *ToolUseAccumulator) Start(start ToolUseStart) (string, *ToolUseBlock, error)
type ToolUseBlock ¶ added in v1.8.0
type ToolUseBlock struct {
ID string
Name string
Arguments json.RawMessage
Signature string
Extra json.RawMessage
Cache *CacheControl
}
type ToolUseDelta ¶ added in v1.8.0
type ToolUseDone ¶ added in v1.8.0
type ToolUseStart ¶ added in v1.8.0
type Usage ¶
type Usage struct {
InputTokens int
OutputTokens int
TotalTokens int
ReasoningTokens int
CacheReadTokens int
CacheWriteTokens int
Provider string
Model string
}
func (*Usage) StampModel ¶ added in v1.8.0
type UsageCapabilities ¶ added in v1.8.1
type UsageEvent ¶ added in v1.8.0
type UsageEvent struct {
Usage Usage
}
type WarningEvent ¶ added in v1.8.0
type WarningEvent struct {
Warning Warning
}
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
anthropic
command
|
|
|
bedrock
command
|
|
|
deepseek
command
|
|
|
gemini
command
|
|
|
glm
command
|
|
|
grok
command
|
|
|
minimax
command
|
|
|
ollama
command
|
|
|
openai
command
|
|
|
openrouter
command
|
|
|
qwen
command
|
|
|
internal
|
|
|
otel
module
|
|
|
provider
|
|
|
Package retry provides explicit opt-in HTTP retry transports for providers.
|
Package retry provides explicit opt-in HTTP retry transports for providers. |