litellm

package module
v1.2.2 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2025 License: Apache-2.0 Imports: 14 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.

Features

  • Simple & Clean - One-line API calls to any LLM platform
  • Unified Interface - Same request/response format across all providers
  • Network Resilience - Automatic 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 := litellm.New()

    // Method 2: Manual configuration (recommended for production)
    client = 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
    )

    // Basic chat
    response, err := client.Complete(context.Background(), &litellm.Request{
        Model: "gpt-4o-mini",
        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.Complete(context.Background(), &litellm.Request{
    Model: "o3-mini",
    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

Built-in automatic retry with exponential backoff for network failures and API errors.

// Default: 3 retries with smart backoff
client := litellm.New(litellm.WithOpenAI("your-api-key"))

// Custom timeout
client := litellm.New(
    litellm.WithOpenAI("your-api-key"),
    litellm.WithTimeout(60*time.Second),
)

// Custom retries
client := litellm.New(
    litellm.WithOpenAI("your-api-key"),
    litellm.WithRetries(5, 2*time.Second), // 5 retries, 2s initial delay
)

Streaming

Real-time streaming with reasoning process display:

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

defer stream.Close()
for {
    chunk, err := stream.Read()
    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.Complete(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.Complete(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.Complete(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.Complete(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.Read()
    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.Complete(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.Complete(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:

// Implement Provider interface
type MyProvider struct {
    *litellm.BaseProvider
}

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

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

// Use it
client := litellm.New()
response, _ := client.Complete(ctx, &litellm.Request{
    Model: "my-model",
    Messages: []litellm.Message{{Role: "user", Content: "Hello"}},
})

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 (智谱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 := 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),
)

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) Complete(ctx context.Context, req *Request) (*Response, error)
func (c *Client) Stream(ctx context.Context, req *Request) (StreamReader, error)

License

Apache License

Documentation

Index

Constants

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

Response format type constants

Variables

View Source
var ProviderRegistry = make(map[string]ProviderFactory)

ProviderRegistry holds all registered provider factories

Functions

func BoolPtr added in v1.2.1

func BoolPtr(v bool) *bool

BoolPtr returns a pointer to a bool value Helper function to make it easier to set optional bool fields

func Float64Ptr

func Float64Ptr(v float64) *float64

Float64Ptr returns a pointer to a float64 value Helper function to make it easier to set optional float64 fields

func IntPtr

func IntPtr(v int) *int

IntPtr returns a pointer to an int value Helper function to make it easier to set optional int fields

func RegisterProvider

func RegisterProvider(name string, factory ProviderFactory)

RegisterProvider registers a provider factory

Types

type AnthropicProvider

type AnthropicProvider struct {
	*BaseProvider
}

AnthropicProvider implements the Provider interface for Anthropic

func (*AnthropicProvider) Complete

func (p *AnthropicProvider) Complete(ctx context.Context, req *Request) (*Response, error)

func (*AnthropicProvider) Models

func (p *AnthropicProvider) Models() []ModelInfo

Models returns the list of supported models

func (*AnthropicProvider) Stream

func (p *AnthropicProvider) Stream(ctx context.Context, req *Request) (StreamReader, error)

type BaseProvider

type BaseProvider struct {
	// contains filtered or unexported fields
}

BaseProvider provides common functionality for all providers

func NewBaseProvider

func NewBaseProvider(name string, config ProviderConfig) *BaseProvider

NewBaseProvider creates a new base provider

func (*BaseProvider) Config

func (p *BaseProvider) Config() ProviderConfig

Config returns the provider configuration

func (*BaseProvider) HTTPClient

func (p *BaseProvider) HTTPClient() *ResilientHTTPClient

HTTPClient returns the resilient HTTP client

func (*BaseProvider) Name

func (p *BaseProvider) Name() string

Name returns the provider name

func (*BaseProvider) ResilienceConfig added in v1.2.2

func (p *BaseProvider) ResilienceConfig() ResilienceConfig

ResilienceConfig returns the resilience configuration

func (*BaseProvider) Validate

func (p *BaseProvider) Validate() error

Validate checks if the provider is properly configured

type ChunkType

type ChunkType string

ChunkType defines the type of streaming chunk

const (
	ChunkTypeContent       ChunkType = "content"         // Regular content
	ChunkTypeReasoning     ChunkType = "reasoning"       // Reasoning content
	ChunkTypeToolCall      ChunkType = "tool_call"       // Complete tool call
	ChunkTypeToolCallDelta ChunkType = "tool_call_delta" // Tool call arguments delta
	ChunkTypeUsage         ChunkType = "usage"           // Usage statistics
	ChunkTypeDone          ChunkType = "done"            // Completion marker
	ChunkTypeError         ChunkType = "error"           // Error
)

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the main LLM client

func New

func New(opts ...ClientOption) *Client

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

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

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

ClientOption defines options for configuring the client

func WithAnthropic

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

WithAnthropic adds Anthropic provider with custom configuration

func WithDeepSeek added in v1.1.0

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

WithDeepSeek adds DeepSeek provider with custom configuration

func WithDefaults

func WithDefaults(maxTokens int, temperature float64) ClientOption

WithDefaults sets default configuration values

func WithGLM added in v1.2.0

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

WithGLM adds GLM provider with custom configuration

func WithGemini

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

WithGemini adds Gemini provider with custom configuration

func WithOpenAI

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

WithOpenAI adds OpenAI provider with custom configuration

func WithOpenRouter added in v1.1.0

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

WithOpenRouter adds OpenRouter provider with custom configuration

func WithProvider

func WithProvider(name string, provider Provider) ClientOption

WithProvider adds a custom provider

func WithProviderConfig

func WithProviderConfig(name string, config ProviderConfig) ClientOption

WithProviderConfig adds a provider using ProviderConfig

func WithQwen added in v1.1.0

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

WithQwen adds Qwen provider with custom configuration

func WithResilience added in v1.2.2

func WithResilience(config ResilienceConfig) ClientOption

WithResilience sets default resilience configuration

func WithRetries added in v1.2.2

func WithRetries(maxRetries int, initialDelay time.Duration) ClientOption

WithRetries sets retry configuration for all providers

func WithTimeout added in v1.2.2

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets request timeout for all providers

type DeepSeekProvider added in v1.1.0

type DeepSeekProvider struct {
	*BaseProvider
}

DeepSeekProvider implements the Provider interface for DeepSeek

func (*DeepSeekProvider) Complete added in v1.1.0

func (p *DeepSeekProvider) Complete(ctx context.Context, req *Request) (*Response, error)

Complete implements the Provider interface for DeepSeek

func (*DeepSeekProvider) Models added in v1.1.0

func (p *DeepSeekProvider) Models() []ModelInfo

Models returns the list of available DeepSeek models

func (*DeepSeekProvider) Stream added in v1.1.0

func (p *DeepSeekProvider) Stream(ctx context.Context, req *Request) (StreamReader, error)

Stream implements streaming for DeepSeek

type DefaultConfig

type DefaultConfig struct {
	MaxTokens   int              `json:"max_tokens"`
	Temperature float64          `json:"temperature"`
	Resilience  ResilienceConfig `json:"resilience"`
}

DefaultConfig holds default configuration values

type FunctionCall

type FunctionCall struct {
	Name      string `json:"name"`      // Function name
	Arguments string `json:"arguments"` // JSON string of arguments
}

FunctionCall represents the function to be called

type FunctionSchema

type FunctionSchema struct {
	Name        string `json:"name"`        // Function name
	Description string `json:"description"` // Function description
	Parameters  any    `json:"parameters"`  // JSON schema for parameters
}

FunctionSchema defines a callable function

type GLMProvider added in v1.2.0

type GLMProvider struct {
	*BaseProvider
}

GLMProvider implements the Provider interface for ZhiPu GLM-4.5 models

func (*GLMProvider) Complete added in v1.2.0

func (p *GLMProvider) Complete(ctx context.Context, req *Request) (*Response, error)

Complete implements the Provider interface for GLM

func (*GLMProvider) Models added in v1.2.0

func (p *GLMProvider) Models() []ModelInfo

Models returns the list of supported GLM models

func (*GLMProvider) Stream added in v1.2.0

func (p *GLMProvider) Stream(ctx context.Context, req *Request) (StreamReader, error)

Stream implements streaming chat completions for GLM

type GeminiProvider

type GeminiProvider struct {
	*BaseProvider
}

GeminiProvider implements the Provider interface for Google Gemini

func (*GeminiProvider) Complete

func (p *GeminiProvider) Complete(ctx context.Context, req *Request) (*Response, error)

func (*GeminiProvider) Models

func (p *GeminiProvider) Models() []ModelInfo

Models returns the list of supported models

func (*GeminiProvider) Stream

func (p *GeminiProvider) Stream(ctx context.Context, req *Request) (StreamReader, error)

type JSONSchema added in v1.2.1

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
}

JSONSchema defines a JSON schema for structured output

type Message

type Message struct {
	Role       string     `json:"role"`                   // "user", "assistant", "system", "tool"
	Content    string     `json:"content"`                // Message content
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`   // Tool calls made by assistant
	ToolCallID string     `json:"tool_call_id,omitempty"` // ID for tool response
}

Message represents a conversation message

type ModelCapability

type ModelCapability string

ModelCapability represents what a model can do

const (
	CapabilityChat         ModelCapability = "chat"          // Chat completion
	CapabilityCompletion   ModelCapability = "completion"    // Text completion
	CapabilityEmbedding    ModelCapability = "embedding"     // Text embedding
	CapabilityFunctionCall ModelCapability = "function_call" // Function calling
	CapabilityVision       ModelCapability = "vision"        // Image understanding
	CapabilityReasoning    ModelCapability = "reasoning"     // Step-by-step reasoning
	CapabilityCode         ModelCapability = "code"          // Code generation
	CapabilityMultimodal   ModelCapability = "multimodal"    // Multiple input types
)

type ModelInfo

type ModelInfo struct {
	ID           string            `json:"id"`                     // Model identifier
	Provider     string            `json:"provider"`               // Provider name
	Name         string            `json:"name"`                   // Display name
	Description  string            `json:"description,omitempty"`  // Model description
	MaxTokens    int               `json:"max_tokens,omitempty"`   // Maximum context tokens
	Capabilities []ModelCapability `json:"capabilities,omitempty"` // Model capabilities
	Extra        map[string]any    `json:"extra,omitempty"`        // Provider-specific info
}

ModelInfo represents information about a model

type OpenAIProvider

type OpenAIProvider struct {
	*BaseProvider
}

OpenAIProvider implements the Provider interface for OpenAI

func (*OpenAIProvider) Complete

func (p *OpenAIProvider) Complete(ctx context.Context, req *Request) (*Response, error)

func (*OpenAIProvider) Models

func (p *OpenAIProvider) Models() []ModelInfo

Models returns the list of supported models

func (*OpenAIProvider) Stream

func (p *OpenAIProvider) Stream(ctx context.Context, req *Request) (StreamReader, error)

type OpenRouterProvider added in v1.1.0

type OpenRouterProvider struct {
	*BaseProvider
}

OpenRouterProvider implements the Provider interface for OpenRouter

func (*OpenRouterProvider) Complete added in v1.1.0

func (p *OpenRouterProvider) Complete(ctx context.Context, req *Request) (*Response, error)

Complete implements the Provider interface

func (*OpenRouterProvider) Models added in v1.1.0

func (p *OpenRouterProvider) Models() []ModelInfo

Models returns the list of available models for OpenRouter

func (*OpenRouterProvider) Stream added in v1.1.0

func (p *OpenRouterProvider) Stream(ctx context.Context, req *Request) (StreamReader, error)

Stream implements the Provider interface for streaming responses

func (*OpenRouterProvider) Validate added in v1.1.0

func (p *OpenRouterProvider) Validate() error

Validate checks if the provider configuration is valid

type Provider

type Provider interface {
	// Name returns the provider name
	Name() string

	// Complete performs a completion request
	Complete(ctx context.Context, req *Request) (*Response, error)

	// Stream performs a streaming completion request
	Stream(ctx context.Context, req *Request) (StreamReader, error)

	// Models returns the list of supported models
	Models() []ModelInfo

	// Validate checks if the provider is properly configured
	Validate() error
}

Provider defines the interface that all LLM providers must implement

func CreateProvider

func CreateProvider(name string, config ProviderConfig) (Provider, error)

CreateProvider creates a provider instance by name

func NewAnthropicProvider

func NewAnthropicProvider(config ProviderConfig) Provider

NewAnthropicProvider creates a new Anthropic provider

func NewDeepSeekProvider added in v1.1.0

func NewDeepSeekProvider(config ProviderConfig) Provider

NewDeepSeekProvider creates a new DeepSeek provider

func NewGLMProvider added in v1.2.0

func NewGLMProvider(config ProviderConfig) Provider

NewGLMProvider creates a new GLM provider instance

func NewGeminiProvider

func NewGeminiProvider(config ProviderConfig) Provider

NewGeminiProvider creates a new Gemini provider

func NewOpenAIProvider

func NewOpenAIProvider(config ProviderConfig) Provider

NewOpenAIProvider creates a new OpenAI provider

func NewOpenRouterProvider added in v1.1.0

func NewOpenRouterProvider(config ProviderConfig) Provider

NewOpenRouterProvider creates a new OpenRouter provider

func NewQwenProvider added in v1.1.0

func NewQwenProvider(config ProviderConfig) Provider

NewQwenProvider creates a new Qwen provider

type ProviderConfig

type ProviderConfig struct {
	APIKey     string           `json:"api_key"`              // API key
	BaseURL    string           `json:"base_url,omitempty"`   // Custom base URL
	Resilience ResilienceConfig `json:"resilience,omitempty"` // Network resilience config
	Extra      map[string]any   `json:"extra,omitempty"`      // Provider-specific config
}

ProviderConfig holds configuration for a provider

type ProviderFactory

type ProviderFactory func(config ProviderConfig) Provider

ProviderFactory creates a provider instance

type QwenProvider added in v1.1.0

type QwenProvider struct {
	*BaseProvider
}

QwenProvider implements the Provider interface for Qwen (Alibaba Cloud DashScope)

func (*QwenProvider) Complete added in v1.1.0

func (p *QwenProvider) Complete(ctx context.Context, req *Request) (*Response, error)

Complete performs a completion request

func (*QwenProvider) Models added in v1.1.0

func (p *QwenProvider) Models() []ModelInfo

Models returns the list of supported models

func (*QwenProvider) Stream added in v1.1.0

func (p *QwenProvider) Stream(ctx context.Context, req *Request) (StreamReader, error)

Stream performs a streaming completion request

type ReasoningChunk

type ReasoningChunk struct {
	Content string `json:"content,omitempty"` // Reasoning content delta
	Summary string `json:"summary,omitempty"` // Reasoning summary delta
}

ReasoningChunk represents a reasoning content chunk

type ReasoningData

type ReasoningData struct {
	Content    string `json:"content,omitempty"`     // Reasoning process content
	Summary    string `json:"summary,omitempty"`     // Reasoning summary
	TokensUsed int    `json:"tokens_used,omitempty"` // Tokens used for reasoning
}

ReasoningData contains reasoning process information

type Request

type Request struct {
	Model       string    `json:"model"`                 // Model identifier in "provider/model" format
	Messages    []Message `json:"messages"`              // Conversation messages
	MaxTokens   *int      `json:"max_tokens,omitempty"`  // Maximum tokens to generate
	Temperature *float64  `json:"temperature,omitempty"` // Sampling temperature
	Stream      bool      `json:"stream,omitempty"`      // Enable streaming
	Tools       []Tool    `json:"tools,omitempty"`       // Available tools
	ToolChoice  any       `json:"tool_choice,omitempty"` // Tool choice strategy

	// Response format for structured outputs
	ResponseFormat *ResponseFormat `json:"response_format,omitempty"` // Response format specification

	// Reasoning model parameters (OpenAI o-series)
	ReasoningEffort  string `json:"reasoning_effort,omitempty"`  // "low", "medium", "high"
	ReasoningSummary string `json:"reasoning_summary,omitempty"` // "concise", "detailed", "auto"
	UseResponsesAPI  bool   `json:"use_responses_api,omitempty"` // Force Responses API usage

	// Extension fields for provider-specific features
	Extra map[string]any `json:"extra,omitempty"` // Provider-specific parameters
}

Request represents a completion request

type ResilienceConfig added in v1.2.2

type ResilienceConfig struct {
	MaxRetries     int           `json:"max_retries"`     // Maximum retry attempts, default 3
	InitialDelay   time.Duration `json:"initial_delay"`   // Initial delay, default 1 second
	MaxDelay       time.Duration `json:"max_delay"`       // Maximum delay, default 30 seconds
	Multiplier     float64       `json:"multiplier"`      // Backoff multiplier, default 2.0
	Jitter         bool          `json:"jitter"`          // Whether to add jitter, default true
	RequestTimeout time.Duration `json:"request_timeout"` // Single request timeout, default 30 seconds
	ConnectTimeout time.Duration `json:"connect_timeout"` // Connection timeout, default 10 seconds
}

ResilienceConfig holds network resilience configuration

func DefaultResilienceConfig added in v1.2.2

func DefaultResilienceConfig() ResilienceConfig

DefaultResilienceConfig returns default resilience configuration

type ResilientHTTPClient added in v1.2.2

type ResilientHTTPClient struct {
	// contains filtered or unexported fields
}

ResilientHTTPClient wraps http.Client with retry logic

func NewResilientHTTPClient added in v1.2.2

func NewResilientHTTPClient(config ResilienceConfig) *ResilientHTTPClient

NewResilientHTTPClient creates a new resilient HTTP client

func (*ResilientHTTPClient) Do added in v1.2.2

Do executes HTTP request with retry logic

type Response

type Response struct {
	Content   string     `json:"content"`              // Generated content
	ToolCalls []ToolCall `json:"tool_calls,omitempty"` // Tool calls requested
	Usage     Usage      `json:"usage"`                // Token usage statistics
	Model     string     `json:"model"`                // Actual model used
	Provider  string     `json:"provider"`             // Provider name

	// Reasoning data (for reasoning models)
	Reasoning *ReasoningData `json:"reasoning,omitempty"` // Reasoning process data

	// Metadata
	FinishReason string         `json:"finish_reason,omitempty"` // Why generation stopped
	Extra        map[string]any `json:"extra,omitempty"`         // Provider-specific data
}

Response represents a completion response

func Quick

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

Quick performs a quick completion with minimal configuration It creates a new client with auto-discovery and makes a simple completion request

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"` // JSON schema for structured output
}

ResponseFormat specifies the format of the model's output

func NewResponseFormatJSONObject added in v1.2.1

func NewResponseFormatJSONObject() *ResponseFormat

NewResponseFormatJSONObject creates a JSON object response format

func NewResponseFormatJSONSchema added in v1.2.1

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

NewResponseFormatJSONSchema creates a JSON schema response format

func NewResponseFormatText added in v1.2.1

func NewResponseFormatText() *ResponseFormat

NewResponseFormatText creates a text response format

type StreamChunk

type StreamChunk struct {
	Type      ChunkType  `json:"type"`                 // Chunk type
	Content   string     `json:"content,omitempty"`    // Content delta
	ToolCalls []ToolCall `json:"tool_calls,omitempty"` // Complete tool calls
	Usage     *Usage     `json:"usage,omitempty"`      // Final usage stats
	Done      bool       `json:"done"`                 // Stream completion flag
	Error     error      `json:"error,omitempty"`      // Error if any

	// Reasoning data
	Reasoning *ReasoningChunk `json:"reasoning,omitempty"` // Reasoning chunk

	// Tool call delta data
	ToolCallDelta *ToolCallDelta `json:"tool_call_delta,omitempty"` // Tool call incremental data

	// Metadata
	Model        string         `json:"model,omitempty"`         // Model name
	Provider     string         `json:"provider,omitempty"`      // Provider name
	FinishReason string         `json:"finish_reason,omitempty"` // Completion reason
	Extra        map[string]any `json:"extra,omitempty"`         // Provider-specific data
}

StreamChunk represents a streaming response chunk

type StreamReader

type StreamReader interface {
	Read() (*StreamChunk, error) // Read next chunk
	Close() error                // Close the stream
	Err() error                  // Get any error that occurred
}

StreamReader provides an interface for reading streaming responses

type Tool

type Tool struct {
	Type     string         `json:"type"`     // Always "function" for now
	Function FunctionSchema `json:"function"` // Function schema
}

Tool represents a function that can be called

type ToolCall

type ToolCall struct {
	ID       string       `json:"id"`       // Unique identifier
	Type     string       `json:"type"`     // Always "function" for now
	Function FunctionCall `json:"function"` // Function details
}

ToolCall represents a function call request

type ToolCallDelta

type ToolCallDelta struct {
	Index          int    `json:"index,omitempty"`           // Tool call index in the array
	ID             string `json:"id,omitempty"`              // Tool call ID
	Type           string `json:"type,omitempty"`            // Tool type (e.g., "function")
	FunctionName   string `json:"function_name,omitempty"`   // Function name
	ArgumentsDelta string `json:"arguments_delta,omitempty"` // Incremental arguments
}

ToolCallDelta represents incremental tool call data

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`              // Input tokens
	CompletionTokens int `json:"completion_tokens"`          // Output tokens
	TotalTokens      int `json:"total_tokens"`               // Total tokens
	ReasoningTokens  int `json:"reasoning_tokens,omitempty"` // Reasoning tokens (o-series)
}

Usage represents token usage statistics

Directories

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

Jump to

Keyboard shortcuts

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