litellm

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 2, 2025 License: Apache-2.0 Imports: 10 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
  • 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.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)
}

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

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

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-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
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
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 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.WithOpenRouter("your-openrouter-key"),
    litellm.WithDefaults(2048, 0.8),
)

API Reference

Core Types
type Request struct {
    Model            string    `json:"model"`                 // model namel
    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
    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
}
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

This section is empty.

Variables

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

ProviderRegistry holds all registered provider factories

Functions

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() *http.Client

HTTPClient returns the HTTP client

func (*BaseProvider) Name

func (p *BaseProvider) Name() string

Name returns the provider name

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

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"`
}

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

	// 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 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 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
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