anyllm

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: Apache-2.0 Imports: 3 Imported by: 33 modules, 12 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Project logo

any-llm (Go)

Go Reference Go Report Card Discord

Communicate with any LLM provider using a single, unified interface. Switch between OpenAI, Anthropic, Mistral, Ollama, and more without changing your code.

Python SDK | Documentation | Platform (Beta)

Quickstart

go get github.com/mozilla-ai/any-llm-go
export OPENAI_API_KEY="YOUR_KEY_HERE"  # or ANTHROPIC_API_KEY, etc
package main

import (
    "context"
    "fmt"
    "log"

    anyllm "github.com/mozilla-ai/any-llm-go"
    "github.com/mozilla-ai/any-llm-go/providers/openai"
)

func main() {
    ctx := context.Background()

    provider, err := openai.New()
    if err != nil {
        log.Fatal(err)
    }

    response, err := provider.Completion(ctx, anyllm.CompletionParams{
        Model: "gpt-4o-mini",
        Messages: []anyllm.Message{
            {Role: anyllm.RoleUser, Content: "Hello!"},
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(response.Choices[0].Message.Content)
}

That's it! To switch providers, change the import and constructor (e.g., anthropic.New() instead of openai.New()).

Installation

Requirements
  • Go 1.26 or newer
  • API keys for whichever LLM providers you want to use

Import the main package and the providers you need:

import (
    anyllm "github.com/mozilla-ai/any-llm-go"
    "github.com/mozilla-ai/any-llm-go/providers/openai"    // OpenAI
    "github.com/mozilla-ai/any-llm-go/providers/anthropic" // Anthropic
)

See our list of supported providers to choose which ones you need.

Setting Up API Keys

Set environment variables for your chosen providers:

export OPENAI_API_KEY="your-key-here"
export ANTHROPIC_API_KEY="your-key-here"
export MISTRAL_API_KEY="your-key-here"
# ... etc

Alternatively, pass API keys directly in your code:

provider, err := openai.New(anyllm.WithAPIKey("your-key-here"))

any-llm-gateway

any-llm-gateway is an optional FastAPI-based proxy server that adds enterprise-grade features on top of the core library:

  • Budget Management - Enforce spending limits with automatic daily, weekly, or monthly resets
  • API Key Management - Issue, revoke, and monitor virtual API keys without exposing provider credentials
  • Usage Analytics - Track every request with full token counts, costs, and metadata
  • Multi-tenant Support - Manage access and budgets across users and teams

The gateway sits between your applications and LLM providers, exposing an OpenAI-compatible API that works with any supported provider.

Quick Start
docker run \
  -e GATEWAY_MASTER_KEY="your-secure-master-key" \
  -e OPENAI_API_KEY="your-api-key" \
  -p 8000:8000 \
  ghcr.io/mozilla-ai/any-llm/gateway:latest

Note: You can use a specific release version instead of latest (e.g., 1.2.0). See available versions.

Managed Platform (Beta)

Prefer a hosted experience? The any-llm platform provides a managed control plane for keys, usage tracking, and cost visibility across providers, while still building on the same any-llm interfaces.

Usage

Create a provider instance and use it for requests:

import (
    "context"
    "fmt"
    "log"

    anyllm "github.com/mozilla-ai/any-llm-go"
    "github.com/mozilla-ai/any-llm-go/providers/openai"
)

provider, err := openai.New(anyllm.WithAPIKey("your-api-key"))
if err != nil {
    log.Fatal(err)
}

ctx := context.Background()

response, err := provider.Completion(ctx, anyllm.CompletionParams{
    Model: "gpt-4o-mini",
    Messages: []anyllm.Message{
        {Role: anyllm.RoleUser, Content: "Hello!"},
    },
})
if err != nil {
    log.Fatal(err)
}

fmt.Println(response.Choices[0].Message.Content)

Provider instances are reusable and recommended for production applications.

Streaming
chunks, errs := provider.CompletionStream(ctx, anyllm.CompletionParams{
    Model: "gpt-4o-mini",
    Messages: []anyllm.Message{
        {Role: anyllm.RoleUser, Content: "Write a short poem about Go."},
    },
})

for chunk := range chunks {
    if len(chunk.Choices) > 0 {
        fmt.Print(chunk.Choices[0].Delta.Content)
    }
}

if err := <-errs; err != nil {
    log.Fatal(err)
}
Tools / Function Calling
response, err := provider.Completion(ctx, anyllm.CompletionParams{
    Model: "gpt-4o-mini",
    Messages: []anyllm.Message{
        {Role: anyllm.RoleUser, Content: "What's the weather in Paris?"},
    },
    Tools: []anyllm.Tool{
        {
            Type: "function",
            Function: anyllm.Function{
                Name:        "get_weather",
                Description: "Get the current weather for a location",
                Parameters: map[string]any{
                    "type": "object",
                    "properties": map[string]any{
                        "location": map[string]any{
                            "type":        "string",
                            "description": "The city name",
                        },
                    },
                    "required": []string{"location"},
                },
            },
        },
    },
    ToolChoice: "auto",
})

// Check for tool calls.
if len(response.Choices[0].Message.ToolCalls) > 0 {
    tc := response.Choices[0].Message.ToolCalls[0]
    fmt.Printf("Function: %s, Args: %s\n", tc.Function.Name, tc.Function.Arguments)
}
Extended Thinking (Reasoning)

For models that support extended thinking (like Claude):

response, err := provider.Completion(ctx, anyllm.CompletionParams{
    Model: "claude-sonnet-4-20250514",
    Messages: []anyllm.Message{
        {Role: anyllm.RoleUser, Content: "Solve this step by step: What is 15% of 80?"},
    },
    ReasoningEffort: anyllm.ReasoningEffortMedium,
})

if response.Choices[0].Message.Reasoning != nil {
    fmt.Println("Thinking:", response.Choices[0].Message.Reasoning.Content)
}
fmt.Println("Answer:", response.Choices[0].Message.Content)
Embeddings
provider, _ := openai.New()
result, err := provider.Embedding(ctx, anyllm.EmbeddingParams{
    Model: "text-embedding-3-small",
    Input: "Hello world",
})
Listing Models
provider, _ := openai.New()
models, err := provider.ListModels(ctx)
for _, model := range models.Data {
    fmt.Println(model.ID)
}
Moderation

The gateway provider supports OpenAI-compatible content moderation. Use errors.As with *anyllm.UnsupportedOperationError (or errors.Is with anyllm.ErrUnsupported) to detect providers that do not support moderation.

import (
    stderrors "errors"

    anyllm "github.com/mozilla-ai/any-llm-go"
    "github.com/mozilla-ai/any-llm-go/config"
    "github.com/mozilla-ai/any-llm-go/providers/gateway"
)

provider, err := gateway.New(config.WithBaseURL("https://gw.example.com"))
if err != nil {
    log.Fatal(err)
}

resp, err := provider.Moderation(ctx, anyllm.ModerationParams{
    Model: "openai:omni-moderation-latest",
    Input: "I want to hurt someone",
})
if err != nil {
    var unsup *anyllm.UnsupportedOperationError
    if stderrors.As(err, &unsup) {
        // Provider does not support moderation; pick another model.
        log.Printf("%s cannot do %s", unsup.Provider, unsup.Operation)
        return
    }
    log.Fatal(err)
}
if resp.Results[0].Flagged {
    // Handle flagged content.
}
Error Handling

All provider errors are normalized to common error types:

response, err := provider.Completion(ctx, params)
if err != nil {
    switch {
    case errors.Is(err, anyllm.ErrRateLimit):
        // Handle rate limiting - maybe retry with backoff.
    case errors.Is(err, anyllm.ErrAuthentication):
        // Handle auth errors - check API key.
    case errors.Is(err, anyllm.ErrContextLength):
        // Handle context too long - reduce input.
    default:
        // Handle other errors.
    }
}

You can also use type assertions for more details:

var rateLimitErr *anyllm.RateLimitError
if errors.As(err, &rateLimitErr) {
    fmt.Printf("Rate limited by %s: %s\n", rateLimitErr.Provider, rateLimitErr.Message)
}

Supported Providers

Provider Completion Streaming Tools Reasoning Embeddings
Anthropic ✅ ✅ ✅ ✅ ❌
DeepSeek ✅ ✅ ✅ ✅ ❌
Gemini ✅ ✅ ✅ ✅ ✅
Groq ✅ ✅ ✅ ❌ ❌
llama.cpp ✅ ✅ ✅ ❌ ✅
Llamafile ✅ ✅ ✅ ❌ ✅
Mistral ✅ ✅ ✅ ✅ ✅
Ollama ✅ ✅ ✅ ✅ ✅
OpenAI ✅ ✅ ✅ ✅ ✅
z.ai ✅ ✅ ✅ ✅ ❌

Why choose any-llm-go?

  • Simple, unified interface - Same types and patterns across all providers, switch models with just a string change
  • Developer friendly - Full type definitions for better IDE support and clear, actionable error messages
  • Leverages official provider SDKs - Uses github.com/openai/openai-go and github.com/anthropics/anthropic-sdk-go for maximum compatibility
  • Stays framework-agnostic so it can be used across different projects and use cases
  • Idiomatic Go - Follows Go conventions with proper error handling and context support
  • Streaming support - Channel-based streaming that's natural in Go
  • Battle-tested - Based on the proven any-llm Python library

Development

make lint       # Run linter with auto-fix
make test       # Lint + run all tests
make test-only  # Run tests without linting
make test-unit  # Run unit tests only (skip integration)
make build      # Verify compilation

Documentation

Contributing

We welcome contributions from developers of all skill levels! Please see our Contributing Guide or open an issue to discuss changes.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Documentation

Overview

Package anyllm provides a unified interface for interacting with LLM providers.

This package re-exports common types and configuration options from subpackages, allowing most use cases to work with just two imports:

import (
    anyllm "github.com/mozilla-ai/any-llm-go"
    "github.com/mozilla-ai/any-llm-go/providers/openai"
)

provider, err := openai.New(anyllm.WithAPIKey("sk-..."))
response, err := provider.Completion(ctx, anyllm.CompletionParams{
    Model: "gpt-4o-mini",
    Messages: []anyllm.Message{
        {Role: anyllm.RoleUser, Content: "Hello!"},
    },
})

Index

Constants

View Source
const (
	RoleAssistant = providers.RoleAssistant
	RoleSystem    = providers.RoleSystem
	RoleTool      = providers.RoleTool
	RoleUser      = providers.RoleUser
)

Message roles.

View Source
const (
	FinishReasonContentFilter = providers.FinishReasonContentFilter
	FinishReasonLength        = providers.FinishReasonLength
	FinishReasonStop          = providers.FinishReasonStop
	FinishReasonToolCalls     = providers.FinishReasonToolCalls
)

Finish reasons.

View Source
const (
	BatchStatusCancelled  = providers.BatchStatusCancelled
	BatchStatusCancelling = providers.BatchStatusCancelling
	BatchStatusCompleted  = providers.BatchStatusCompleted
	BatchStatusExpired    = providers.BatchStatusExpired
	BatchStatusFailed     = providers.BatchStatusFailed
	BatchStatusFinalizing = providers.BatchStatusFinalizing
	BatchStatusInProgress = providers.BatchStatusInProgress
	BatchStatusValidating = providers.BatchStatusValidating
)

Batch status constants.

View Source
const (
	ReasoningEffortAuto   = providers.ReasoningEffortAuto
	ReasoningEffortHigh   = providers.ReasoningEffortHigh
	ReasoningEffortLow    = providers.ReasoningEffortLow
	ReasoningEffortMedium = providers.ReasoningEffortMedium
	ReasoningEffortNone   = providers.ReasoningEffortNone
)

ReasoningEffort levels.

Variables

View Source
var (
	NewConfig      = config.New
	WithAPIKey     = config.WithAPIKey
	WithBaseURL    = config.WithBaseURL
	WithExtra      = config.WithExtra
	WithHeader     = config.WithHeader
	WithHTTPClient = config.WithHTTPClient
	WithTimeout    = config.WithTimeout
)

Configuration options.

View Source
var (
	ErrAuthentication      = errors.ErrAuthentication
	ErrContentFilter       = errors.ErrContentFilter
	ErrContextLength       = errors.ErrContextLength
	ErrInsufficientFunds   = errors.ErrInsufficientFunds
	ErrInvalidRequest      = errors.ErrInvalidRequest
	ErrMissingAPIKey       = errors.ErrMissingAPIKey
	ErrModelNotFound       = errors.ErrModelNotFound
	ErrProvider            = errors.ErrProvider
	ErrRateLimit           = errors.ErrRateLimit
	ErrUnsupported         = errors.ErrUnsupported
	ErrUnsupportedParam    = errors.ErrUnsupportedParam
	ErrUnsupportedProvider = errors.ErrUnsupportedProvider
)

Sentinel errors for type checking with errors.Is().

Functions

This section is empty.

Types

type AuthenticationError

type AuthenticationError = errors.AuthenticationError

Error types.

type BaseError

type BaseError = errors.BaseError

Error types.

type Batch added in v0.10.0

type Batch = providers.Batch

Batch types.

type BatchProvider added in v0.10.0

type BatchProvider = providers.BatchProvider

Provider types.

type BatchRequestCounts added in v0.10.0

type BatchRequestCounts = providers.BatchRequestCounts

Batch types.

type BatchRequestItem added in v0.10.0

type BatchRequestItem = providers.BatchRequestItem

Batch types.

type BatchResult added in v0.10.0

type BatchResult = providers.BatchResult

Batch types.

type BatchResultError added in v0.10.0

type BatchResultError = providers.BatchResultError

Batch types.

type BatchResultItem added in v0.10.0

type BatchResultItem = providers.BatchResultItem

Batch types.

type BatchStatus added in v0.10.0

type BatchStatus = providers.BatchStatus

Usage and model types.

type Capabilities

type Capabilities = providers.Capabilities

Provider types.

type CapabilityProvider

type CapabilityProvider = providers.CapabilityProvider

Provider types.

type ChatCompletion

type ChatCompletion = providers.ChatCompletion

Request/Response types.

type ChatCompletionChunk

type ChatCompletionChunk = providers.ChatCompletionChunk

Request/Response types.

type Choice

type Choice = providers.Choice

Request/Response types.

type ChunkChoice

type ChunkChoice = providers.ChunkChoice

Request/Response types.

type ChunkDelta

type ChunkDelta = providers.ChunkDelta

Request/Response types.

type CompletionParams

type CompletionParams = providers.CompletionParams

Request/Response types.

type Config

type Config = config.Config

Config types.

type ContentFilterError

type ContentFilterError = errors.ContentFilterError

Error types.

type ContentPart

type ContentPart = providers.ContentPart

Message types.

type ContextLengthError

type ContextLengthError = errors.ContextLengthError

Error types.

type CreateBatchParams added in v0.10.0

type CreateBatchParams = providers.CreateBatchParams

Batch types.

type EmbeddingData

type EmbeddingData = providers.EmbeddingData

Usage and model types.

type EmbeddingParams

type EmbeddingParams = providers.EmbeddingParams

Request/Response types.

type EmbeddingProvider

type EmbeddingProvider = providers.EmbeddingProvider

Provider types.

type EmbeddingResponse

type EmbeddingResponse = providers.EmbeddingResponse

Request/Response types.

type EmbeddingUsage

type EmbeddingUsage = providers.EmbeddingUsage

Usage and model types.

type Function

type Function = providers.Function

Tool types.

type FunctionCall

type FunctionCall = providers.FunctionCall

Tool types.

type ImageURL

type ImageURL = providers.ImageURL

Message types.

type InsufficientFundsError added in v0.10.0

type InsufficientFundsError = errors.InsufficientFundsError

Error types.

type InvalidRequestError

type InvalidRequestError = errors.InvalidRequestError

Error types.

type JSONSchema

type JSONSchema = providers.JSONSchema

Response format types.

type ListBatchesOptions added in v0.10.0

type ListBatchesOptions = providers.ListBatchesOptions

Batch types.

type Message

type Message = providers.Message

Message types.

type MissingAPIKeyError

type MissingAPIKeyError = errors.MissingAPIKeyError

Error types.

type Model

type Model = providers.Model

Usage and model types.

type ModelLister

type ModelLister = providers.ModelLister

Provider types.

type ModelNotFoundError

type ModelNotFoundError = errors.ModelNotFoundError

Error types.

type ModelsResponse

type ModelsResponse = providers.ModelsResponse

Request/Response types.

type ModerationParams added in v0.10.0

type ModerationParams = providers.ModerationParams

Request/Response types.

type ModerationProvider added in v0.10.0

type ModerationProvider = providers.ModerationProvider

Provider types.

type ModerationResponse added in v0.10.0

type ModerationResponse = providers.ModerationResponse

Request/Response types.

type ModerationResult added in v0.10.0

type ModerationResult = providers.ModerationResult

Request/Response types.

type Option

type Option = config.Option

Config types.

type Provider

type Provider = providers.Provider

Provider types.

type ProviderError

type ProviderError = errors.ProviderError

Error types.

type RateLimitError

type RateLimitError = errors.RateLimitError

Error types.

type Reasoning

type Reasoning = providers.Reasoning

Message types.

type ReasoningEffort

type ReasoningEffort = providers.ReasoningEffort

Usage and model types.

type RerankMeta added in v0.10.0

type RerankMeta = providers.RerankMeta

Rerank types.

type RerankParams added in v0.10.0

type RerankParams = providers.RerankParams

Rerank types.

type RerankProvider added in v0.10.0

type RerankProvider = providers.RerankProvider

Provider types.

type RerankResponse added in v0.10.0

type RerankResponse = providers.RerankResponse

Rerank types.

type RerankResult added in v0.10.0

type RerankResult = providers.RerankResult

Rerank types.

type RerankUsage added in v0.10.0

type RerankUsage = providers.RerankUsage

Rerank types.

type ResponseFormat

type ResponseFormat = providers.ResponseFormat

Response format types.

type StreamOptions

type StreamOptions = providers.StreamOptions

Response format types.

type Tool

type Tool = providers.Tool

Tool types.

type ToolCall

type ToolCall = providers.ToolCall

Tool types.

type ToolChoice

type ToolChoice = providers.ToolChoice

Tool types.

type ToolChoiceFunction

type ToolChoiceFunction = providers.ToolChoiceFunction

Tool types.

type UnsupportedOperationError added in v0.10.0

type UnsupportedOperationError = errors.UnsupportedOperationError

Error types.

type UnsupportedParamError

type UnsupportedParamError = errors.UnsupportedParamError

Error types.

type UnsupportedProviderError

type UnsupportedProviderError = errors.UnsupportedProviderError

Error types.

type Usage

type Usage = providers.Usage

Usage and model types.

Directories

Path Synopsis
examples
basic command
Example: Basic completion request
Example: Basic completion request
llamafile-tools command
Example: Tool/Function calling with Llamafile
Example: Tool/Function calling with Llamafile
multi-provider command
Example: Multi-provider usage
Example: Multi-provider usage
streaming command
Example: Streaming responses
Example: Streaming responses
tools command
Example: Tool/Function calling
Example: Tool/Function calling
internal
redirect
Package redirect keeps credentials on the origin the caller sent them to.
Package redirect keeps credentials on the origin the caller sent them to.
testutil
Package testutil provides testing utilities and fixtures for any-llm.
Package testutil provides testing utilities and fixtures for any-llm.
Package providers defines the core provider interface and related types.
Package providers defines the core provider interface and related types.
anthropic
Package anthropic provides an Anthropic provider implementation for any-llm.
Package anthropic provides an Anthropic provider implementation for any-llm.
deepseek
Package deepseek provides a DeepSeek provider implementation for any-llm.
Package deepseek provides a DeepSeek provider implementation for any-llm.
gateway
Package gateway provides a gateway provider implementation for any-llm.
Package gateway provides a gateway provider implementation for any-llm.
gemini
Package gemini provides a Google Gemini provider implementation for any-llm.
Package gemini provides a Google Gemini provider implementation for any-llm.
groq
Package groq provides a Groq provider implementation for any-llm.
Package groq provides a Groq provider implementation for any-llm.
llamacpp
Package llamacpp provides a provider that talks to a running llama.cpp server using its OpenAI-compatible HTTP API.
Package llamacpp provides a provider that talks to a running llama.cpp server using its OpenAI-compatible HTTP API.
llamafile
Package llamafile provides a Llamafile provider implementation for any-llm.
Package llamafile provides a Llamafile provider implementation for any-llm.
mistral
Package mistral provides a Mistral provider implementation for any-llm.
Package mistral provides a Mistral provider implementation for any-llm.
ollama
Package ollama provides an Ollama provider implementation for any-llm.
Package ollama provides an Ollama provider implementation for any-llm.
openai
Package openai provides an OpenAI provider implementation for any-llm.
Package openai provides an OpenAI provider implementation for any-llm.
platform
Package platform provides a platform provider implementation for any-llm.
Package platform provides a platform provider implementation for any-llm.
zai
Package zai provides a z.ai provider implementation for any-llm.
Package zai provides a z.ai provider implementation for any-llm.
Package sdk provides metadata for the any-llm-go library.
Package sdk provides metadata for the any-llm-go library.

Jump to

Keyboard shortcuts

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