litellm

package module
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2025 License: Apache-2.0 Imports: 17 Imported by: 2

README

LiteLLM - Go Multi-Platform LLM API Client

LiteLLM - Making LLM API calls simple and elegant

中文 | English

A clean and elegant Go library for unified access to multiple LLM platforms.

Key Design Principles

  • 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

Features

  • Simple & Clean - One-line API calls to any LLM platform
  • Unified Interface - Same request/response format across all providers
  • Network Resilience - Optional retry with exponential backoff and jitter
  • Structured Outputs - JSON Schema validation with cross-provider support
  • Reasoning Support - Full support for OpenAI o-series reasoning models
  • Function Calling - Complete Function Calling support
  • Streaming - Real-time streaming responses
  • Zero Config - Auto-discovery from environment variables
  • Extensible - Easy to add new LLM platforms
  • Type Safe - Strong typing and comprehensive error handling

Quick Start

Installation
go get github.com/voocel/litellm
One-Line Usage
package main

import (
    "fmt"
    "github.com/voocel/litellm"
)

func main() {
    // Set environment variable: export OPENAI_API_KEY="your-key"
    response, err := litellm.Quick("gpt-4o-mini", "Hello, LiteLLM!")
    if err != nil {
        panic(err)
    }
    fmt.Println(response.Content)
}
Full Configuration
package main

import (
    "context"
    "fmt"
    "github.com/voocel/litellm"
)

func main() {
    // Method 1: Auto-discovery from environment variables
    client, err := litellm.New()
    if err != nil {
        panic(err)
    }

    // Method 2: Type-safe manual configuration (recommended for production)
    client, err = litellm.New(
        litellm.WithOpenAI("your-openai-key"),
        litellm.WithAnthropic("your-anthropic-key"),
        litellm.WithGemini("your-gemini-key"),
        litellm.WithQwen("your-dashscope-key"),
        litellm.WithGLM("your-glm-key"),
        litellm.WithOpenRouter("your-openrouter-key"),
        litellm.WithDefaults(2048, 0.8), // Custom defaults
    )
    if err != nil {
        panic(err)
    }

    // Basic chat
    response, err := client.Chat(context.Background(), &litellm.Request{
        Model: "gpt-4o-mini", // Auto-resolves to OpenAI provider
        Messages: []litellm.Message{
            {Role: "user", Content: "Explain artificial intelligence"},
        },
        MaxTokens:   litellm.IntPtr(200),
        Temperature: litellm.Float64Ptr(0.7),
    })

    if err != nil {
        panic(err)
    }

    fmt.Printf("Response: %s\n", response.Content)
    fmt.Printf("Tokens: %d (input: %d, output: %d)\n",
        response.Usage.TotalTokens,
        response.Usage.PromptTokens,
        response.Usage.CompletionTokens)
}

Reasoning Models

Full support for OpenAI o-series reasoning models with both Chat API and Responses API:

response, err := client.Chat(context.Background(), &litellm.Request{
    Model: "o3-mini", // Auto-resolves to OpenAI provider
    Messages: []litellm.Message{
        {Role: "user", Content: "Calculate 15 * 8 step by step"},
    },
    MaxTokens:        litellm.IntPtr(500),
    ReasoningEffort:  "medium",      // "low", "medium", "high"
    ReasoningSummary: "detailed",    // "concise", "detailed", "auto"
    UseResponsesAPI:  true,          // Force Responses API
})

// Access reasoning process
if response.Reasoning != nil {
    fmt.Printf("Reasoning: %s\n", response.Reasoning.Summary)
    fmt.Printf("Reasoning tokens: %d\n", response.Reasoning.TokensUsed)
}

Network Resilience

Optional retry mechanism with exponential backoff for network failures and API errors.

// Default: No automatic retries
client, err := litellm.New(litellm.WithOpenAI("your-api-key"))
if err != nil {
    log.Fatal(err)
}

// Custom timeout
client, err = litellm.New(
    litellm.WithOpenAI("your-api-key"),
    litellm.WithTimeout(60*time.Second),
)
if err != nil {
    log.Fatal(err)
}

// Enable retries (user opt-in)
client, err = litellm.New(
    litellm.WithOpenAI("your-api-key"),
    litellm.WithRetries(3, 1*time.Second), // 3 retries, 1s initial delay
)
if err != nil {
    log.Fatal(err)
}

Streaming

Real-time streaming with reasoning process display:

stream, err := client.Stream(context.Background(), &litellm.Request{
    Model: "gpt-4o-mini", // Auto-resolves to OpenAI provider
    Messages: []litellm.Message{
        {Role: "user", Content: "Tell me a programming joke"},
    },
})

defer stream.Close()
for {
    chunk, err := stream.Next()
    if err != nil || chunk.Done {
        break
    }

    switch chunk.Type {
    case litellm.ChunkTypeContent:
        fmt.Print(chunk.Content)
    case litellm.ChunkTypeReasoning:
        fmt.Printf("[Thinking: %s]", chunk.Reasoning.Summary)
    }
}
}

Structured Outputs

LiteLLM supports structured JSON outputs with JSON Schema validation, ensuring reliable and predictable responses across all providers.

Basic JSON Object Output
response, err := client.Chat(context.Background(), &litellm.Request{
    Model: "gpt-4o-mini",
    Messages: []litellm.Message{
        {Role: "user", Content: "Generate a person's information"},
    },
    ResponseFormat: litellm.NewResponseFormatJSONObject(),
})

// Response will be valid JSON
fmt.Println(response.Content) // {"name": "John Doe", "age": 30, ...}
JSON Schema with Strict Validation
// Define your data structure
personSchema := map[string]interface{}{
    "type": "object",
    "properties": map[string]interface{}{
        "name": map[string]interface{}{
            "type": "string",
            "description": "Full name",
        },
        "age": map[string]interface{}{
            "type": "integer",
            "minimum": 0,
            "maximum": 150,
        },
        "email": map[string]interface{}{
            "type": "string",
            "format": "email",
        },
    },
    "required": []string{"name", "age", "email"},
}

response, err := client.Chat(context.Background(), &litellm.Request{
    Model: "gpt-4o-mini",
    Messages: []litellm.Message{
        {Role: "user", Content: "Generate a software engineer's profile"},
    },
    ResponseFormat: litellm.NewResponseFormatJSONSchema(
        "person_profile",
        "A person's professional profile",
        personSchema,
        true, // strict mode
    ),
})

// Parse into your Go struct
type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

var person Person
json.Unmarshal([]byte(response.Content), &person)
Cross-Provider Compatibility

Structured outputs work across all providers with intelligent adaptation:

  • OpenAI: Native JSON Schema support with strict mode
  • Anthropic: Prompt engineering with JSON instructions
  • Gemini: Native response schema support
  • Other providers: Automatic fallback to prompt-based JSON generation
// Works with any provider
providers := []string{"gpt-4o-mini", "claude-4-sonnet", "gemini-2.5-flash"}

for _, model := range providers {
    response, _ := client.Chat(ctx, &litellm.Request{
        Model: model,
        Messages: []litellm.Message{
            {Role: "user", Content: "Generate user data"},
        },
        ResponseFormat: litellm.NewResponseFormatJSONObject(),
    })
    // All providers return valid JSON
}

Function Calling

Basic Function Calling

Complete Function Calling support compatible with OpenAI and Anthropic:

tools := []litellm.Tool{
    {
        Type: "function",
        Function: litellm.FunctionSchema{
            Name:        "get_weather",
            Description: "Get weather information for a city",
            Parameters: map[string]interface{}{
                "type": "object",
                "properties": map[string]interface{}{
                    "city": map[string]interface{}{
                        "type":        "string",
                        "description": "City name",
                    },
                },
                "required": []string{"city"},
            },
        },
    },
}

response, err := client.Chat(context.Background(), &litellm.Request{
    Model: "gpt-4o-mini",
    Messages: []litellm.Message{
        {Role: "user", Content: "What's the weather in Beijing?"},
    },
    Tools:      tools,
    ToolChoice: "auto",
})

// Handle tool calls
if len(response.ToolCalls) > 0 {
    // Execute function and continue conversation...
}
Advanced Streaming Tool Calls

Real-time streaming with incremental tool call processing:

// Start streaming with tool calls
stream, err := client.Stream(context.Background(), &litellm.Request{
    Model: "gpt-4.1-mini",
    Messages: []litellm.Message{
        {Role: "user", Content: "What's the weather like in Tokyo and New York? Use celsius."},
    },
    Tools:      tools,
    ToolChoice: "auto",
})

// Track tool calls with incremental data
toolCalls := make(map[string]*ToolCallBuilder)

defer stream.Close()
for {
    chunk, err := stream.Next()
    if err != nil || chunk.Done {
        break
    }

    switch chunk.Type {
    case litellm.ChunkTypeContent:
        fmt.Print(chunk.Content)

    case litellm.ChunkTypeToolCallDelta:
        // Handle incremental tool call data
        if chunk.ToolCallDelta != nil {
            delta := chunk.ToolCallDelta

            // Create or get tool call builder
            if _, exists := toolCalls[delta.ID]; !exists && delta.ID != "" {
                toolCalls[delta.ID] = &ToolCallBuilder{
                    ID:   delta.ID,
                    Type: delta.Type,
                    Name: delta.FunctionName,
                }
                fmt.Printf("\nTool call started: %s", delta.FunctionName)
            }

            // Accumulate arguments
            if delta.ArgumentsDelta != "" && delta.ID != "" {
                if builder, exists := toolCalls[delta.ID]; exists {
                    builder.Arguments.WriteString(delta.ArgumentsDelta)
                    fmt.Print(".")
                }
            }
        }
    }
}

// Process completed tool calls
for id, builder := range toolCalls {
    fmt.Printf("\nTool: %s(%s)", builder.Name, builder.Arguments.String())
    // Execute the function with the accumulated arguments
}
// ToolCallBuilder helps accumulate tool call data
type ToolCallBuilder struct {
    ID        string
    Type      string
    Name      string
    Arguments strings.Builder
}
Reasoning Mode (Qwen3 Thinking)

Qwen3-Coder models support step-by-step reasoning through the enable_thinking parameter, providing detailed thinking process for complex coding and mathematical problems:

// Enable reasoning mode for complex problem solving
response, err := client.Chat(ctx, &litellm.Request{
    Model: "qwen3-coder-plus",
    Messages: []litellm.Message{
        {Role: "user", Content: "Write a Python function to implement binary search. Explain your approach step by step."},
    },
    Extra: map[string]interface{}{
        "enable_thinking": true, // Enable Qwen3 reasoning mode
    },
})

if err != nil {
    log.Fatal(err)
}

fmt.Printf("Final Answer: %s\n", response.Content)
if response.Reasoning != nil {
    fmt.Printf("Reasoning Process: %s\n", response.Reasoning.Content)
    fmt.Printf("Reasoning Summary: %s\n", response.Reasoning.Summary)
    fmt.Printf("Reasoning Tokens: %d\n", response.Reasoning.TokensUsed)
}
Reasoning Mode (GLM-4.5 Thinking)

GLM-4.5 models support hybrid reasoning capabilities through the enable_thinking parameter, providing step-by-step analysis for complex problems:

// Enable thinking mode for GLM-4.5
response, err := client.Chat(ctx, &litellm.Request{
    Model: "glm-4.5",
    Messages: []litellm.Message{
        {Role: "user", Content: "Design an efficient algorithm to solve the traveling salesman problem and analyze its time complexity."},
    },
    Extra: map[string]interface{}{
        "enable_thinking": true, // Enable GLM-4.5 thinking mode
    },
})

if err != nil {
    log.Fatal(err)
}

fmt.Printf("Final Answer: %s\n", response.Content)
if response.Reasoning != nil {
    fmt.Printf("Reasoning Process: %s\n", response.Reasoning.Content)
    fmt.Printf("Reasoning Summary: %s\n", response.Reasoning.Summary)
    fmt.Printf("Reasoning Tokens: %d\n", response.Reasoning.TokensUsed)
}

Extending New Platforms

Adding new LLM platforms is simple with the custom provider registration system:

// 1. Implement the Provider interface
type MyProvider struct {
    name   string
    config litellm.ProviderConfig
}

func (p *MyProvider) Name() string { return p.name }
func (p *MyProvider) Validate() error { return nil }
func (p *MyProvider) SupportsModel(model string) bool { return true }
func (p *MyProvider) Models() []litellm.ModelInfo {
    return []litellm.ModelInfo{
        {ID: "my-model", Provider: "myprovider", Name: "My Model", MaxTokens: 4096},
    }
}

func (p *MyProvider) Chat(ctx context.Context, req *litellm.Request) (*litellm.Response, error) {
    // Implement your API call logic here
    return &litellm.Response{
        Content:  "Hello from my provider!",
        Model:    req.Model,
        Provider: p.name,
        Usage:    litellm.Usage{TotalTokens: 10},
    }, nil
}

func (p *MyProvider) Stream(ctx context.Context, req *litellm.Request) (litellm.StreamReader, error) {
    // Implement streaming if needed
    return nil, fmt.Errorf("streaming not implemented")
}

// 2. Create a factory function
func NewMyProvider(config litellm.ProviderConfig) litellm.Provider {
    return &MyProvider{name: "myprovider", config: config}
}

// 3. Register the provider
func init() {
    litellm.RegisterProvider("myprovider", NewMyProvider)
}

// 4. Use it
client, err := litellm.New(
    litellm.WithProviderConfig("myprovider", litellm.ProviderConfig{
        APIKey: "your-api-key",
    }),
)
if err != nil {
    log.Fatal(err)
}
response, err := client.Chat(ctx, &litellm.Request{
    Model: "my-model",
    Messages: []litellm.Message{{Role: "user", Content: "Hello"}},
})
if err != nil {
    log.Fatal(err)
}
Provider Discovery
// List all available providers
providers := litellm.ListRegisteredProviders()
fmt.Printf("Available providers: %v\n", providers)

// Check if a provider is registered
if litellm.IsProviderRegistered("myprovider") {
    fmt.Println("Custom provider is available!")
}

Supported Platforms

OpenAI
  • GPT-5, GPT-4o, GPT-4o-mini, GPT-4.1, GPT-4.1-mini, GPT-4.1-mano
  • o3, o3-mini, o4-mini (reasoning models)
  • Chat Completions API & Responses API
  • Function Calling, Vision, Streaming
Usage tips for GPT-5
  • For deeper reasoning, set ReasoningEffort and/or ReasoningSummary. LiteLLM will automatically switch to the Responses API and use MaxCompletionTokens for better reasoning behavior.
  • Consider increasing MaxCompletionTokens to cover both reasoning and final answer tokens.
  • Ensure your API key has access to gpt-5; otherwise, requests may fail. You can also try routing via OpenRouter (openai/gpt-5).
Anthropic
  • Claude 3.7 Sonnet, Claude 4 Sonnet, Claude 4 Opus
  • Function Calling, Vision, Streaming
Google Gemini
  • Gemini 2.5 Pro, Gemini 2.5 Flash
  • Function Calling, Vision, Streaming
  • Large context window
DeepSeek
  • DeepSeek Chat, DeepSeek Reasoner
  • Function Calling, Code Generation, Reasoning
  • Large context window
Qwen (Alibaba Cloud DashScope)
  • Qwen3-Coder-Plus, Qwen3-Coder-Flash (with thinking mode support)
  • Qwen3-Coder-480B-A35B-Instruct, Qwen3-Coder-30B-A3B-Instruct (open source models)
  • Function Calling, Code Generation, Reasoning (step-by-step thinking via enable_thinking), Large context window (up to 1M tokens)
  • OpenAI-compatible API through DashScope
GLM (ZhiPu AI)
  • GLM-4.5 (355B-A32B flagship model with hybrid reasoning capabilities)
  • GLM-4.5-Air (106B-A12B lightweight version), GLM-4.5-Flash (fast version)
  • GLM-4, GLM-4-Flash, GLM-4-Air, GLM-4-AirX (previous generation models)
  • Function Calling, Code Generation, Reasoning (thinking mode), Large context window (128K tokens)
  • OpenAI-compatible API through Zhipu AI Open Platform
OpenRouter
  • Access to 200+ models from multiple providers
  • OpenAI, Anthropic, Google, Meta, and more
  • Unified API for all supported models
  • Reasoning models support

Configuration

Environment Variables
export OPENAI_API_KEY="sk-proj-..."
export ANTHROPIC_API_KEY="sk-ant-..."
export GEMINI_API_KEY="AIza..."
export DEEPSEEK_API_KEY="sk-..."
export QWEN_API_KEY="sk-..."  # For Qwen models
export GLM_API_KEY="your-glm-key"  # For GLM models
export OPENROUTER_API_KEY="sk-or-v1-..."
client, err := litellm.New(
    litellm.WithOpenAI("your-openai-key"),
    litellm.WithAnthropic("your-anthropic-key"),
    litellm.WithGemini("your-gemini-key"),
    litellm.WithDeepSeek("your-deepseek-key"),
    litellm.WithQwen("your-qwen-key"),
    litellm.WithGLM("your-glm-key"),
    litellm.WithOpenRouter("your-openrouter-key"),
    litellm.WithDefaults(2048, 0.8),
)
if err != nil {
    log.Fatal(err)
}

API Reference

Core Types
type Request struct {
    Model            string          `json:"model"`                 // Model name
    Messages         []Message       `json:"messages"`              // Conversation messages
    MaxTokens        *int            `json:"max_tokens,omitempty"`  // Max tokens to generate
    Temperature      *float64        `json:"temperature,omitempty"` // Sampling temperature
    Tools            []Tool          `json:"tools,omitempty"`       // Available tools
    ResponseFormat   *ResponseFormat `json:"response_format,omitempty"` // Response format
    ReasoningEffort  string          `json:"reasoning_effort,omitempty"`  // Reasoning effort
    ReasoningSummary string          `json:"reasoning_summary,omitempty"` // Reasoning summary
}

type Response struct {
    Content   string         `json:"content"`              // Generated content
    ToolCalls []ToolCall     `json:"tool_calls,omitempty"` // Tool calls
    Usage     Usage          `json:"usage"`                // Token usage
    Reasoning *ReasoningData `json:"reasoning,omitempty"`  // Reasoning data
}

type ResponseFormat struct {
    Type       string      `json:"type"`                 // "text", "json_object", "json_schema"
    JSONSchema *JSONSchema `json:"json_schema,omitempty"` // JSON schema for structured output
}

type JSONSchema struct {
    Name        string `json:"name"`                  // Schema name
    Description string `json:"description,omitempty"` // Schema description
    Schema      any    `json:"schema"`                // JSON schema definition
    Strict      *bool  `json:"strict,omitempty"`      // Whether to enforce strict adherence
}
Main Methods
func Quick(model, message string) (*Response, error)
func New(opts ...ClientOption) *Client
func (c *Client) Chat(ctx context.Context, req *Request) (*Response, error)
func (c *Client) Stream(ctx context.Context, req *Request) (StreamReader, error)

License

Apache License

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

View Source
const (
	ContextKeyRequestID  contextKey = "request_id"
	ContextKeyRetryCount contextKey = "retry_count"
	ContextKeyProvider   contextKey = "provider"
)
View Source
const (
	CacheTypeEphemeral  = "ephemeral"
	CacheTypePersistent = "persistent"
)

Cache control types

View Source
const (
	ChunkTypeContent       = "content"
	ChunkTypeToolCallDelta = "tool_call_delta"
	ChunkTypeReasoning     = "reasoning"
)

Chunk types for streaming

View Source
const (
	ResponseFormatText       = "text"
	ResponseFormatJSONObject = "json_object"
	ResponseFormatJSONSchema = "json_schema"
)

Response format types

Variables

View Source
var DefaultRouter = NewAutoRouter().WithFallback(FallbackNone)

Default router instance (By default, do not downgrade to avoid misrouting)

Functions

func BoolPtr added in v1.2.1

func BoolPtr(v bool) *bool

BoolPtr returns a pointer to a bool value Example: req.Store = litellm.BoolPtr(true)

func Float64Ptr

func Float64Ptr(v float64) *float64

Float64Ptr returns a pointer to a float64 value Example: req.Temperature = litellm.Float64Ptr(0.7)

func GetRetryAfter added in v1.5.0

func GetRetryAfter(err error) int

GetRetryAfter extracts retry-after duration from rate limit errors

func HasChatCapability added in v1.5.0

func HasChatCapability(p any) bool

HasChatCapability checks if provider supports chat

func HasModelCapability added in v1.5.0

func HasModelCapability(p any) bool

HasModelCapability checks if provider supports model information

func HasStreamCapability added in v1.5.0

func HasStreamCapability(p any) bool

HasStreamCapability checks if provider supports streaming

func IntPtr

func IntPtr(v int) *int

IntPtr returns a pointer to an int value Example: req.MaxTokens = litellm.IntPtr(2048)

func IsAuthError added in v1.5.0

func IsAuthError(err error) bool

IsAuthError checks if error is authentication related

func IsModelError added in v1.5.0

func IsModelError(err error) bool

IsModelError checks if error is model related

func IsNetworkError added in v1.5.0

func IsNetworkError(err error) bool

IsNetworkError checks if error is network related

func IsProviderRegistered added in v1.5.0

func IsProviderRegistered(name string) bool

IsProviderRegistered checks if a provider is registered (built-in or custom)

func IsRateLimitError added in v1.5.0

func IsRateLimitError(err error) bool

IsRateLimitError checks if error is rate limit related

func IsRetryableError added in v1.5.0

func IsRetryableError(err error) bool

IsRetryableError checks if an error is retryable

func IsValidationError added in v1.5.0

func IsValidationError(err error) bool

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 ResetDefaultClient added in v1.5.2

func ResetDefaultClient()

ResetDefaultClient resets the default client singleton This is useful for testing or when environment variables change

func StringPtr added in v1.5.2

func StringPtr(v string) *string

StringPtr returns a pointer to a string value Example: req.User = litellm.StringPtr("user-123")

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

func WrapError added in v1.5.0

func WrapError(err error, provider string) error

WrapError wraps an existing error as a LiteLLMError if it isn't already

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

type ChatProvider interface {
	Chat(ctx context.Context, req *Request) (*Response, error)
}

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

func (c *Client) AddProvider(name string, provider Provider) error

AddProvider adds a provider to the client

func (*Client) Chat added in v1.5.0

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

Chat performs a completion request

func (*Client) Models

func (c *Client) Models() []ModelInfo

Models returns all available models

func (*Client) Providers

func (c *Client) Providers() []string

Providers returns the names of all configured providers

func (*Client) Stream

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

Stream performs a streaming completion request

type ClientOption

type ClientOption func(*Client) error

ClientOption defines options for configuring the client

func WithAnthropic

func WithAnthropic(apiKey string, baseURL ...string) ClientOption

WithAnthropic adds Anthropic provider with custom configuration

func WithBedrock added in v1.5.2

func WithBedrock(accessKeyID, secretAccessKey string, region ...string) ClientOption

WithBedrock adds AWS Bedrock provider with custom configuration accessKeyID and secretAccessKey are AWS credentials regions is optional (defaults to "us-east-1")

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

type CustomRouterFunc func(model string, providers []Provider) (Provider, error)

CustomRouterFunc allows users to provide custom routing logic

func (CustomRouterFunc) Route added in v1.5.0

func (f CustomRouterFunc) Route(model string, providers []Provider) (Provider, error)

Route implements Router interface for CustomRouterFunc

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

func AssistantMessage added in v1.5.2

func AssistantMessage(content string) Message

AssistantMessage creates an assistant message Example: litellm.AssistantMessage("Hello! How can I help you?")

func SystemMessage added in v1.5.2

func SystemMessage(content string) Message

SystemMessage creates a system message Example: litellm.SystemMessage("You are a helpful assistant.")

func ToolMessage added in v1.5.2

func ToolMessage(toolCallID, content string) Message

ToolMessage creates a tool response message Example: litellm.ToolMessage("call_abc123", `{"result": "success"}`)

func UserMessage added in v1.5.2

func UserMessage(content string) Message

UserMessage creates a user message Example: litellm.UserMessage("Hello, AI!")

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

type ModelProvider interface {
	Models() []ModelInfo
	SupportsModel(model string) bool
}

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

func (*ResilientHTTPClient) Do added in v1.2.2

Do executes HTTP request with retry logic

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

func Quick

func Quick(model, message string) (*Response, error)

Quick performs a quick completion with minimal configuration It uses a singleton client with auto-discovery and makes a simple completion request with a default timeout of 30 seconds.

The client is created once on first call and reused for subsequent calls, providing better performance through connection pooling.

func QuickWithTimeout added in v1.5.0

func QuickWithTimeout(model, message string, timeout time.Duration) (*Response, error)

QuickWithTimeout performs a quick completion with a custom timeout It uses a singleton client with auto-discovery and makes a simple completion request.

The client is created once on first call and reused for subsequent calls, providing better performance through connection pooling.

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 This ensures the model returns valid JSON without enforcing a specific schema

func NewResponseFormatJSONSchema added in v1.2.1

func NewResponseFormatJSONSchema(name, description string, schema any, strict bool) *ResponseFormat

NewResponseFormatJSONSchema creates a JSON schema response format with strict validation enabled/disabled

Parameters:

  • name: Schema name (required)
  • description: Schema description (optional, can be empty)
  • schema: JSON Schema definition as a map[string]interface{}
  • strict: Enable strict schema validation (OpenAI only)

Example:

schema := map[string]interface{}{
    "type": "object",
    "properties": map[string]interface{}{
        "name": map[string]interface{}{"type": "string"},
        "age": map[string]interface{}{"type": "integer"},
    },
    "required": []string{"name", "age"},
}
format := litellm.NewResponseFormatJSONSchema("person", "A person object", schema, true)

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

type Router interface {
	Route(model string, availableProviders []Provider) (Provider, error)
}

Router interface defines how to select a provider for a given model

func RouteByProviderName added in v1.5.0

func RouteByProviderName(providerName string) Router

RouteByProviderName creates a router that selects provider by name

func RouteToProvider added in v1.5.0

func RouteToProvider(provider Provider) Router

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

Directories

Path Synopsis
examples
anthropic command
bedrock command
deepseek command
gemini command
glm command
openai command
openrouter command
qwen command
routing command
otel module

Jump to

Keyboard shortcuts

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