litellm

package module
v1.8.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 3, 2026 License: Apache-2.0 Imports: 14 Imported by: 2

README

LiteLLM Go

中文 | English

LiteLLM is a small, explicit Go SDK for calling LLM providers through one typed core model. The root package owns the provider-agnostic API; concrete providers live in provider/<name> subpackages.

Install

go get github.com/voocel/litellm

Quick Start

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/voocel/litellm"
	"github.com/voocel/litellm/provider/openai"
)

func main() {
	client, err := openai.NewClient(openai.Config{
		APIKey: os.Getenv("OPENAI_API_KEY"),
	})
	if err != nil {
		log.Fatal(err)
	}

	resp, err := client.Chat(context.Background(), litellm.Request{
		Model: "gpt-5.4-mini",
		Messages: []litellm.Message{
			litellm.System("You are concise."),
			litellm.UserText("Explain Go interfaces in one sentence."),
		},
		MaxTokens: litellm.IntPtr(120),
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(resp.Text())
}

openai.NewClient(cfg, opts...) builds the provider first, then returns a ready *litellm.Client; every provider package exposes it. The explicit two-step form — provider, _ := openai.New(cfg) then litellm.New(provider, opts...) — is equivalent; prefer it when you want to share one provider across multiple clients. Both forms accept the same ClientOptions.

Core Model

Messages and responses use ordered Block values:

  • TextBlock
  • ImageBlock
  • ReasoningBlock
  • ToolUseBlock
  • ToolResultBlock
  • ToolReferenceBlock

Response.Blocks is the canonical response content. Text(), Reasoning(), and ToolCalls() are convenience views.

msgs := []litellm.Message{
	litellm.User(litellm.Text("What is in this image?"), litellm.ImageURL("https://example.com/cat.png")),
}

resp, err := client.Chat(ctx, litellm.Request{Model: "gpt-5.4-mini", Messages: msgs})
_ = resp
_ = err

For multi-turn tool workflows, append the previous response blocks directly:

args, err := litellm.JSONRaw(map[string]any{"ok": true})
if err != nil {
	log.Fatal(err)
}

msgs = append(msgs,
	litellm.Assistant(resp.Blocks...),
	litellm.ToolResultText("call_1", string(args)),
)

JSONRaw returns marshal errors instead of silently producing invalid tool arguments. Use MustJSONRaw only for static test data or package-level examples where panic is acceptable.

By default the SDK validates message history strictly. Dirty tool histories, invalid tool IDs, missing tool results, and unsupported provider options return errors. If you need to import legacy history, enable repair explicitly:

client, err := openai.NewClient(openai.Config{APIKey: os.Getenv("OPENAI_API_KEY")}, litellm.WithMessageRepair(litellm.RepairAll))

Repairs and provider normalizations that change observable data are exposed through Response.Warnings, WarningEvent, and Hook.OnWarning.

Raw provider response bodies are not retained by default. Enable them explicitly when debugging:

client, err := openai.NewClient(openai.Config{APIKey: os.Getenv("OPENAI_API_KEY")}, litellm.WithCaptureRawResponse(true))

Streaming

Streams emit typed Event values. Stream is intended for single-goroutine consumption; do not call Next concurrently. Use WithStreamIdleTimeout when you want an explicit per-event idle timeout; it is off by default. WithStreamIdleTimeout only covers generic Client.Stream; OpenAI Responses native streaming uses openai.Config.StreamIdleTimeout. For example:

client, err := openai.NewClient(openai.Config{APIKey: os.Getenv("OPENAI_API_KEY")}, litellm.WithStreamIdleTimeout(120*time.Second))
stream, err := client.Stream(ctx, litellm.Request{
	Model:    "gpt-5.4-mini",
	Messages: []litellm.Message{litellm.UserText("Tell me a short joke.")},
})
if err != nil {
	log.Fatal(err)
}
defer stream.Close()

for {
	event, err := stream.Next()
	if err != nil {
		log.Fatal(err)
	}
	switch e := event.(type) {
	case litellm.ContentDelta:
		fmt.Print(e.Text)
	case litellm.ReasoningDelta:
		fmt.Print(e.Text)
	case litellm.ProviderEvent:
		// Provider-native lifecycle/hosted-tool event.
	case litellm.DoneEvent:
		return
	}
}

To aggregate a stream:

resp, err := litellm.Collect(stream)

Retry

Retries are off by default. Enable them per provider:

import "github.com/voocel/litellm/retry"

provider, err := openai.New(openai.Config{
	APIKey: os.Getenv("OPENAI_API_KEY"),
	Retry:  retry.DefaultPolicy(),
})

Bedrock retries re-sign each attempt internally, so users do not need to compose SigV4 transports by hand.

If you need a proxy, tracing, or a custom base transport, pass Transport together with Retry. A custom HTTPClient is an advanced escape hatch and cannot be combined with Retry; configure retry inside that client yourself.

Choose the smallest configuration that matches your use case:

Use case Config
Normal retries Retry: retry.DefaultPolicy()
Retries plus proxy/tracing/custom base transport Retry + Transport
Fully custom request execution HTTPClient, without Retry/Transport

APIKeyFunc is resolved once when a request is created; retry attempts reuse that request. If you use extremely short-lived Bearer tokens, inject auth in a lower-level custom Transport or HTTPClient. Normal API keys and the default retry window do not need special handling.

Tools

tool, err := litellm.NewTool("get_weather", "Get weather for a city.", map[string]any{
	"type": "object",
	"properties": map[string]any{
		"city": map[string]any{"type": "string"},
	},
	"required": []string{"city"},
})
if err != nil {
	log.Fatal(err)
}
tool.Strict = litellm.StrictEnabled

resp, err := client.Chat(ctx, litellm.Request{
	Model:      "gpt-5.4-mini",
	Messages:   []litellm.Message{litellm.UserText("Weather in Paris?")},
	Tools:      []litellm.Tool{tool},
	ToolChoice: "auto",
})

Structured Output

format, err := litellm.NewResponseFormatJSONSchema("person", "", map[string]any{
	"type": "object",
	"properties": map[string]any{
		"name": map[string]any{"type": "string"},
	},
	"required": []string{"name"},
}, litellm.StrictEnabled)
if err != nil {
	log.Fatal(err)
}

resp, err := client.Chat(ctx, litellm.Request{
	Model:          "gpt-5.4-mini",
	Messages:       []litellm.Message{litellm.UserText("Generate a person.")},
	ResponseFormat: format,
})

Thinking

Thinking is explicit. If Thinking is nil, the SDK sends no thinking control fields.

resp, err := client.Chat(ctx, litellm.Request{
	Model:    "claude-sonnet-4-5-20250929",
	Messages: []litellm.Message{litellm.UserText("Explain the tradeoffs.")},
	MaxTokens: litellm.IntPtr(2048),
	Thinking: &litellm.Thinking{
		Mode:  litellm.ThinkingEnabled,
		Effort: "low",
	},
})

Provider constraints are validated locally. For example, Anthropic thinking requires max_tokens >= 1024, a budget or effort, and no conflicting explicit temperature. Portable effort values are minimal, low, medium, high, xhigh, and max; providers that require token budgets map these values to budget_tokens. Use client.Capabilities(model) or litellm.GetCapabilities(provider, model) for UI/preflight checks across providers.

OpenAI Responses

OpenAI Responses is provider-native and lives on provider/openai.Provider, not the generic client.

oai, err := openai.New(openai.Config{APIKey: os.Getenv("OPENAI_API_KEY")})
if err != nil {
	log.Fatal(err)
}

resp, err := oai.Responses(ctx, &openai.ResponsesRequest{
	Model: "gpt-5.5",
	Messages: []litellm.Message{
		litellm.UserText("Solve 15*8 step by step."),
	},
	ReasoningEffort:  "medium",
	ReasoningSummary: "auto",
	MaxOutputTokens:  litellm.IntPtr(800),
	OpenAITools: []openai.ResponsesTool{
		{"type": "web_search_preview"},
	},
})

Streaming Responses uses the same typed event model:

oai, err := openai.New(openai.Config{
	APIKey:            os.Getenv("OPENAI_API_KEY"),
	StreamIdleTimeout: 120 * time.Second,
})

stream, err := oai.ResponsesStream(ctx, &openai.ResponsesRequest{
	Model:    "gpt-5.5",
	Messages: []litellm.Message{litellm.UserText("Search and summarize.")},
})

Providers

Provider configs are provider-specific. Authentication is not forced into a single API-key shape.

import (
	"github.com/voocel/litellm/provider/anthropic"
	"github.com/voocel/litellm/provider/bedrock"
	"github.com/voocel/litellm/provider/deepseek"
	"github.com/voocel/litellm/provider/gemini"
	"github.com/voocel/litellm/provider/glm"
	"github.com/voocel/litellm/provider/grok"
	"github.com/voocel/litellm/provider/minimax"
	"github.com/voocel/litellm/provider/ollama"
	"github.com/voocel/litellm/provider/openrouter"
	"github.com/voocel/litellm/provider/qwen"
)

Examples:

anthropic.New(anthropic.Config{APIKey: os.Getenv("ANTHROPIC_API_KEY")})
gemini.New(gemini.Config{APIKey: os.Getenv("GEMINI_API_KEY")})
deepseek.New(deepseek.Config{APIKey: os.Getenv("DEEPSEEK_API_KEY")})
ollama.New(ollama.Config{})

bedrock.New(bedrock.Config{
	Region: "us-east-1",
	Credentials: bedrock.StaticCredentials(
		os.Getenv("AWS_ACCESS_KEY_ID"),
		os.Getenv("AWS_SECRET_ACCESS_KEY"),
		os.Getenv("AWS_SESSION_TOKEN"),
	),
})

Supported provider packages currently include OpenAI, Anthropic, Gemini, Bedrock, DeepSeek, Qwen, GLM, OpenRouter, MiniMax, Grok, MiMo, and Ollama. See Provider Capabilities for thinking, reasoning, usage, and cache support across providers.

Model Listing

models, err := client.ListModels(ctx)

Only providers that implement ModelLister support this. Returned fields are best-effort.

Provider Options

Provider-specific request options go in Request.ProviderOptions. Unknown keys error by default.

resp, err := client.Chat(ctx, litellm.Request{
	Model:    "gpt-5.4-mini",
	Messages: []litellm.Message{litellm.UserText("Hello")},
	ProviderOptions: litellm.ProviderOptions{
		openai.ProviderOptionPromptCacheRetention: "24h",
	},
})

Hooks And OTel

Hooks observe requests, responses, warnings, and stream events. Hook inputs are copies; mutating them does not affect provider calls, returned responses, or events seen by the caller. Core hooks do not recover panics.

client, err := litellm.New(provider, litellm.WithHook(litellm.HookFuncs{
	OnStreamEventFunc: func(ctx context.Context, meta litellm.CallMeta, event litellm.Event) {
		if delta, ok := event.(litellm.ContentDelta); ok {
			fmt.Print(delta.Text)
		}
	},
}))

The optional github.com/voocel/litellm/otel module adapts hooks to OpenTelemetry spans.

Pricing

Pricing is explicit. Cost calculation never loads remote pricing implicitly.

import "github.com/voocel/litellm/pricing"

reg := pricing.NewRegistry()
err := reg.LoadFromURL(ctx, pricing.DefaultURL)
cost, err := reg.Calculate(resp.Model, resp.Usage)

err = reg.Set("my-model", pricing.ModelPricing{
	InputCostPerToken:  0.000001,
	OutputCostPerToken: 0.000002,
})

Custom Providers

Implement the small provider interface:

type Provider interface {
	Name() string
	Chat(context.Context, *litellm.Request) (*litellm.Response, error)
	Stream(context.Context, *litellm.Request) (litellm.Stream, error)
}

License

Apache License

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

View Source
const (
	CacheTypeEphemeral = "ephemeral"
	CacheTTL5m         = "5m"
	CacheTTL1h         = "1h"
)

Variables

View Source
var ErrStreamIdle = errors.New("stream idle timeout")

Functions

func Bool added in v1.8.0

func Bool(v bool) *bool

func BoolPtr added in v1.2.1

func BoolPtr(v bool) *bool

func CaptureRawResponse added in v1.8.0

func CaptureRawResponse(req *Request, resp *Response, raw []byte)

func Float64Ptr

func Float64Ptr(v float64) *float64

func GetRetryAfter added in v1.5.0

func GetRetryAfter(err error) int

func IntPtr

func IntPtr(v int) *int

func IsAuthError added in v1.5.0

func IsAuthError(err error) bool

func IsContextOverflowError added in v1.6.0

func IsContextOverflowError(err error) bool

func IsModelError added in v1.5.0

func IsModelError(err error) bool

func IsNetworkError added in v1.5.0

func IsNetworkError(err error) bool

func IsOverloadedError added in v1.6.3

func IsOverloadedError(err error) bool

func IsProviderError added in v1.8.0

func IsProviderError(err error) bool

func IsRateLimitError added in v1.5.0

func IsRateLimitError(err error) bool

func IsRetryableError added in v1.5.0

func IsRetryableError(err error) bool

func IsStreamIdleError added in v1.6.8

func IsStreamIdleError(err error) bool

func IsTimeoutError added in v1.8.0

func IsTimeoutError(err error) bool

func IsValidationError added in v1.5.0

func IsValidationError(err error) bool

func JSONRaw added in v1.8.0

func JSONRaw(v any) (json.RawMessage, error)

func MustJSONRaw added in v1.8.0

func MustJSONRaw(v any) json.RawMessage

func NormalizeToolUseID added in v1.8.0

func NormalizeToolUseID(id string) string

func PortableThinkingEfforts added in v1.8.1

func PortableThinkingEfforts() []string

func StringPtr added in v1.5.2

func StringPtr(v string) *string

func WrapError added in v1.5.0

func WrapError(err error, provider string) error

func WrapValidationError added in v1.8.0

func WrapValidationError(provider string, err error) error

Types

type Annotation added in v1.8.0

type Annotation struct {
	Type  string
	Text  string
	URL   string
	Extra json.RawMessage
}

type Block added in v1.8.0

type Block interface {
	// contains filtered or unexported methods
}

type CacheCapabilities added in v1.8.1

type CacheCapabilities struct {
	Block         Support
	RequestPolicy Support
	PromptKey     Support
	Retention     Support
	UsageRead     Support
	UsageWrite    Support
}

type CacheControl added in v1.5.0

type CacheControl struct {
	Type string
	TTL  string
}

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 CallMeta added in v1.6.7

type CallMeta struct {
	CallID    string
	Provider  string
	Operation string
	Model     string
	Streaming bool
	StartedAt time.Time
	Duration  time.Duration
}

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 New

func New(provider Provider, opts ...ClientOption) (*Client, error)

func (*Client) Capabilities added in v1.8.1

func (c *Client) Capabilities(model string) Capabilities

func (*Client) Chat added in v1.5.0

func (c *Client) Chat(ctx context.Context, req Request) (*Response, error)

func (*Client) ListModels added in v1.5.5

func (c *Client) ListModels(ctx context.Context) ([]ModelInfo, error)

func (*Client) ProviderName added in v1.5.7

func (c *Client) ProviderName() string

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, req Request) (Stream, error)

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

type ClientOption func(*Client) error

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 ContentDelta struct {
	Text         string
	OutputIndex  *int
	ContentIndex *int
}

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 Event added in v1.8.0

type Event interface {
	// contains filtered or unexported methods
}

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 Hook added in v1.6.7

type Hook interface {
	BeforeRequest(context.Context, CallMeta, *Request)
	AfterResponse(context.Context, CallMeta, *Response, error)
	OnStreamEvent(context.Context, CallMeta, Event)
	OnStreamEnd(context.Context, CallMeta, error)
	OnWarning(context.Context, CallMeta, Warning)
}

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 (h HookFuncs) AfterResponse(ctx context.Context, meta CallMeta, resp *Response, err error)

func (HookFuncs) BeforeRequest added in v1.6.7

func (h HookFuncs) BeforeRequest(ctx context.Context, meta CallMeta, req *Request)

func (HookFuncs) OnStreamEnd added in v1.6.14

func (h HookFuncs) OnStreamEnd(ctx context.Context, meta CallMeta, err error)

func (HookFuncs) OnStreamEvent added in v1.8.0

func (h HookFuncs) OnStreamEvent(ctx context.Context, meta CallMeta, event Event)

func (HookFuncs) OnWarning added in v1.8.0

func (h HookFuncs) OnWarning(ctx context.Context, meta CallMeta, warning Warning)

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 MediaCapabilities struct {
	ImageURL    Support
	ImageBytes  Support
	FileURI     Support
	ImageDetail Support
}

type Message

type Message struct {
	Role   Role
	Blocks []Block
}

func Assistant added in v1.8.0

func Assistant(blocks ...Block) Message

func AssistantText added in v1.8.0

func AssistantText(text string) Message

func System added in v1.8.0

func System(text string) Message

func ToolResult added in v1.8.0

func ToolResult(toolUseID string, blocks ...Block) Message

func ToolResultText added in v1.8.0

func ToolResultText(toolUseID, text string) Message

func User added in v1.8.0

func User(blocks ...Block) Message

func UserText added in v1.8.0

func UserText(text string) Message

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 ModelInfo

type ModelInfo struct {
	ID               string
	Name             string
	Provider         string
	Description      string
	ContextLength    int
	InputTokenLimit  int
	OutputTokenLimit int
	Created          int64

	SupportsTools    bool
	SupportsVision   bool
	SupportsThinking bool
}

type ModelLister added in v1.5.5

type ModelLister interface {
	ListModels(context.Context) ([]ModelInfo, error)
}

type Provider

type Provider interface {
	Name() string
	Chat(context.Context, *Request) (*Response, error)
	Stream(context.Context, *Request) (Stream, error)
}

type ProviderEvent added in v1.8.0

type ProviderEvent struct {
	Name string
	Raw  json.RawMessage
}

type ProviderFactory

type ProviderFactory func(any) (Provider, error)

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 ProviderOptions map[string]any

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 ReasoningCapabilities struct {
	Blocks          Support
	StreamingDeltas Support
	ReasoningTokens Support
}

type ReasoningDelta added in v1.8.0

type ReasoningDelta struct {
	Text      string
	Summary   bool
	Signature string
	Redacted  []byte
	Extra     json.RawMessage
	ExtraFull bool
	Index     *int
}

type RefusalDelta added in v1.8.0

type RefusalDelta struct {
	Text         string
	OutputIndex  *int
	ContentIndex *int
}

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

func (*Registry) Names added in v1.8.0

func (r *Registry) Names() []string

func (*Registry) New added in v1.8.0

func (r *Registry) New(name string, config any) (Provider, error)

func (*Registry) Register added in v1.8.0

func (r *Registry) Register(name string, factory ProviderFactory) error

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

func (r *Request) CaptureRawResponse() bool

type RequestDefaults added in v1.8.0

type RequestDefaults struct {
	MaxTokens   *int
	Temperature *float64
	TopP        *float64
}

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

func Collect(stream Stream) (*Response, error)

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

func Handle(stream Stream, fn func(Event) error) (*Response, error)

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

func HandleText(stream Stream, fn func(string) error) (*Response, error)

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) Reasoning

func (r *Response) Reasoning() string

func (*Response) Text added in v1.8.0

func (r *Response) Text() string

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 Role added in v1.8.0

type Role string
const (
	RoleSystem    Role = "system"
	RoleUser      Role = "user"
	RoleAssistant Role = "assistant"
	RoleTool      Role = "tool"
)

type Schema added in v1.8.0

type Schema json.RawMessage

func SchemaFrom added in v1.8.0

func SchemaFrom(v any) (Schema, error)

type Stream added in v1.8.0

type Stream interface {
	Next() (Event, error)
	Close() error
}

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

type StreamHandler struct {
	Content   func(string) error
	Reasoning func(string) error
}

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 StreamingCapabilities struct {
	Supported       Support
	Usage           Support
	ReasoningDeltas Support
	ToolCallDeltas  Support
	NativeResponses Support
	IdleTimeout     Support
}

type StrictMode added in v1.8.0

type StrictMode int
const (
	StrictDefault StrictMode = iota
	StrictEnabled
	StrictDisabled
)

type StructuredCapabilities added in v1.8.1

type StructuredCapabilities struct {
	JSONObject Support
	JSONSchema Support
	Strict     Support
	PromptOnly bool
}

type Support added in v1.8.1

type Support int
const (
	SupportUnknown Support = iota
	SupportNo
	SupportYes
	SupportPartial
)

type TextBlock added in v1.8.0

type TextBlock struct {
	Text        string
	Annotations []Annotation
	Logprobs    json.RawMessage
	Cache       *CacheControl
}

func Text added in v1.8.0

func Text(text string) TextBlock

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

func (t *Thinking) HasOptions() bool

func (*Thinking) Validate added in v1.8.1

func (t *Thinking) Validate() error

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 Tool

type Tool struct {
	Name        string
	Description string
	Parameters  Schema
	Strict      StrictMode
}

func NewTool added in v1.5.4

func NewTool(name, description string, parameters any) (Tool, error)

type ToolCapabilities added in v1.8.1

type ToolCapabilities struct {
	Calls               Support
	ParallelCalls       Support
	StrictSchema        Support
	Choice              Support
	MultimodalResults   Support
	RequiresAdjacency   bool
	RoundTripSignatures Support
	HostedProviderTools Support
}

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 (*ToolUseAccumulator) Done added in v1.8.0

func (*ToolUseAccumulator) Start added in v1.8.0

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 ToolUseDelta struct {
	ID             string
	Index          *int
	OutputIndex    *int
	ItemID         string
	ArgumentsDelta []byte
	Signature      string
}

type ToolUseDone added in v1.8.0

type ToolUseDone struct {
	ID          string
	Index       *int
	OutputIndex *int
	ItemID      string
}

type ToolUseStart added in v1.8.0

type ToolUseStart struct {
	ID          string
	Name        string
	Index       *int
	OutputIndex *int
	ItemID      string
	Signature   string
}

type Usage

type Usage struct {
	InputTokens     int
	OutputTokens    int
	TotalTokens     int
	ReasoningTokens int

	CacheReadTokens  int
	CacheWriteTokens int

	Provider string
	Model    string
}

func (Usage) HasTokens added in v1.8.0

func (u Usage) HasTokens() bool

func (*Usage) StampModel added in v1.8.0

func (u *Usage) StampModel(provider, model string)

type UsageCapabilities added in v1.8.1

type UsageCapabilities struct {
	InputTokens      Support
	OutputTokens     Support
	TotalTokens      Support
	ReasoningTokens  Support
	CacheReadTokens  Support
	CacheWriteTokens Support
}

type UsageEvent added in v1.8.0

type UsageEvent struct {
	Usage Usage
}

type Warning added in v1.8.0

type Warning struct {
	Code     string
	Provider string
	Message  string
}

type WarningEvent added in v1.8.0

type WarningEvent struct {
	Warning Warning
}

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
glm
Package retry provides explicit opt-in HTTP retry transports for providers.
Package retry provides explicit opt-in HTTP retry transports for providers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL