llm

Library Featured

A Rust library unifying multiple LLM backends.

Checked · Sources

Downloads
7,669
Dependents
34
Stars
365
Forks
90
Contributors
24
Commits
505
Latest release
1.3.8 ·

About

From the project README ·

Note: This crate name previously belonged to another project. The current implementation represents a new and different library. The previous crate is now archived and will not receive any updates. ref: https://github.com/rustformers/llm

LLM is a Rust library that lets you use multiple LLM backends in a single project: OpenAI, Anthropic (Claude), Ollama, DeepSeek, xAI, Phind, Groq, Google, Cohere, Mistral, Hugging Face and ElevenLabs. With a unified API and builder style - similar to the Stripe experience - you can easily create chat, text completion, speak-to-text requests without multiplying structures and crates.

Read the full README

Key Features

  • Multi-backend: Manage OpenAI, Anthropic, Ollama, DeepSeek, xAI, Phind, Groq, OpenRouter, Cohere, Elevenlabs and Google through a single entry point.
  • Multi-step chains: Create multi-step chains with different backends at each step.
  • Templates: Use templates to create complex prompts with variables.
  • Builder pattern: Configure your LLM (model, temperature, max_tokens, timeouts...) with a few simple calls.
  • Chat & Completions: Two unified traits (ChatProvider and CompletionProvider) to cover most use cases.
  • Extensible: Easily add new backends.
  • Rust-friendly: Designed with clear traits, unified error handling, and conditional compilation via features.
  • Validation: Add validation to your requests to ensure the output is what you expect.
  • Resilience (retry/backoff): Enable resilient calls with exponential backoff and jitter.
  • Evaluation: Add evaluation to your requests to score the output of LLMs.
  • Parallel Evaluation: Evaluate multiple LLM providers in parallel and select the best response based on scoring functions.
  • Function calling: Add function calling to your requests to use tools in your LLMs.
  • REST API: Serve any LLM backend as a REST API with openai standard format.
  • Vision: Add vision to your requests to use images in your LLMs.
  • Reasoning: Add reasoning to your requests to use reasoning in your LLMs.
  • Structured Output: Request structured output from certain LLM providers based on a provided JSON schema.
  • Speech to text: Transcribe audio to text
  • Text to speech: Transcribe text to audio
  • Memory: Store and retrieve conversation history with sliding window (soon others) and shared memory support
  • Agentic: Build reactive agents that can cooperate via shared memory, with configurable triggers, roles and validation.

Use any LLM backend on your project

Simply add LLM to your Cargo.toml:

[dependencies]
llm = { version = "1.3.8", features = ["openai", "anthropic", "ollama", "deepseek", "xai", "phind", "google", "groq", "mistral", "elevenlabs"] }

Use any LLM on cli

LLM includes a command-line tool for easily interacting with different LLM models. You can install it with: cargo install llm

  • Use llm to start an interactive chat session
  • Use llm openai:gpt-4o to start an interactive chat session with provider:model
  • Use llm set OPENAI_API_KEY your_key to configure your API key
  • Use llm default openai:gpt-4 to set a default provider
  • Use echo "Hello World" | llm to pipe
  • Use llm --provider openai --model gpt-4 --temperature 0.7 for advanced options

Serving any LLM backend as a REST API

  • Use standard messages format
  • Use step chains to chain multiple LLM backends together
  • Expose the chain through a REST API with openai standard format
[dependencies]
llm = { version = "1.3.8", features = ["openai", "anthropic", "ollama", "deepseek", "xai", "phind", "google", "groq", "api", "mistral", "elevenlabs"] }

More details in the api_example

More examples

NameDescription
anthropic_exampleDemonstrates integration with Anthropic's Claude model for chat completion
anthropic_streaming_exampleAnthropic streaming chat example demonstrating real-time token generation
chain_exampleShows how to create multi-step prompt chains for exploring programming language features
deepseek_exampleBasic DeepSeek chat completion example with deepseek-chat models
embedding_exampleBasic embedding example with OpenAI's API
multi_backend_exampleIllustrates chaining multiple LLM backends (OpenAI, Anthropic, DeepSeek) together in a single workflow
ollama_exampleExample of using local LLMs through Ollama integration
openai_exampleBasic OpenAI chat completion example with GPT models
resilient_exampleSimple retry/backoff wrapper usage
openai_streaming_exampleOpenAI streaming chat example demonstrating real-time token generation
phind_exampleBasic Phind chat completion example with Phind-70B model
validator_exampleBasic validator example with Anthropic's Claude model
xai_exampleBasic xAI chat completion example with Grok models
xai_streaming_exampleX.AI streaming chat example demonstrating real-time token generation
evaluation_exampleBasic evaluation example with Anthropic, Phind and DeepSeek
evaluator_parallel_exampleEvaluate multiple LLM providers in parallel
google_exampleBasic Google Gemini chat completion example with Gemini models
google_streaming_exampleGoogle streaming chat example demonstrating real-time token generation
google_pdfGoogle Gemini chat with PDF attachment
google_imageGoogle Gemini chat with PDF attachment
google_embedding_exampleBasic Google Gemini embedding example with Gemini models
tool_calling_exampleBasic tool calling example with OpenAI
google_tool_calling_exampleGoogle Gemini function calling example with complex JSON schema for meeting scheduling
json_schema_nested_exampleAdvanced example demonstrating deeply nested JSON schemas with arrays of objects and complex data structures
tool_json_schema_cycle_exampleComplete tool calling cycle with JSON schema validation and structured responses
unified_tool_calling_exampleUnified tool calling with selectable provider - demonstrates multi-turn tool use and tool choice
deepclaude_pipeline_exampleBasic deepclaude pipeline example with DeepSeek and Claude
api_exampleBasic API (openai standard format) example with OpenAI, Anthropic, DeepSeek and Groq
api_deepclaude_exampleBasic API (openai standard format) example with DeepSeek and Claude
anthropic_vision_exampleBasic anthropic vision example with Anthropic
openai_vision_exampleBasic openai vision example with OpenAI
openai_reasoning_exampleBasic openai reasoning example with OpenAI
anthropic_thinking_exampleAnthropic reasoning example
elevenlabs_stt_exampleSpeech-to-text transcription example using ElevenLabs
elevenlabs_tts_exampleText-to-speech example using ElevenLabs
openai_stt_exampleSpeech-to-text transcription example using OpenAI
openai_tts_exampleText-to-speech example using OpenAI
tts_rodio_exampleText-to-speech with rodio example using OpenAI
chain_audio_text_exampleExample demonstrating a multi-step chain combining speech-to-text and text processing
xai_search_chain_tts_exampleExample demonstrating a multi-step chain combining XAI search, OpenAI summarization, and ElevenLabs text-to-speech with Rodio playback
xai_search_exampleExample demonstrating X.AI search functionality with search modes, date ranges, and source filtering
memory_exampleAutomatic memory integration - LLM remembers conversation context across calls
memory_share_exampleExample demonstrating shared memory between multiple LLM providers
trim_strategy_exampleExample demonstrating memory trimming strategies with automatic summarization
agent_builder_exampleExample of reactive agents cooperating via shared memory, demonstrating creation of LLM agents with roles, conditions
openai_web_search_exampleExample demonstrating OpenAI web search functionality with location-based search context
model_listing_exampleExample demonstrating how to list available models from an LLM backend
cohere_exampleBasic Cohere chat completion example with Command models
mistral_exampleBasic Mistral example with Mistral models
huggingface_exampleBasic example with Hugging Face models

Usage

Here's a basic example using OpenAI for chat completion. See the examples directory for other backends (Anthropic, Ollama, DeepSeek, xAI, Google, Phind, Elevenlabs), embedding capabilities, and more advanced use cases.

use llm::{
    builder::{LLMBackend, LLMBuilder}, // Builder pattern components
    chat::ChatMessage,                 // Chat-related structures
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Get OpenAI API key from environment variable or use test key as fallback
    let api_key = std::env::var("OPENAI_API_KEY").unwrap_or("sk-TESTKEY".into());

    // Initialize and configure the LLM client
    let llm = LLMBuilder::new()
        .backend(LLMBackend::OpenAI)	// Use OpenAI as the LLM provider
        .api_key(api_key) 						// Set the API key
        .model("gpt-4.1-nano") 				// Use GPT-4.1 Nano model
        .max_tokens(512) 							// Limit response length
        .temperature(0.7) 						// Control response randomness (0.0-1.0)
        .normalize_response(true)     // Increase response normalization (e.g. function call stream)
        .build()
        .expect("Failed to build LLM");

    // Prepare conversation history with example messages
    let messages = vec![
        ChatMessage::user()
            .content("Tell me that you love cats")
            .build(),
        ChatMessage::assistant()
            .content("I am an assistant, I cannot love cats but I can love dogs")
            .build(),
        ChatMessage::user()
            .content("Tell me that you love dogs in 2000 chars")
            .build(),
    ];

    // Send chat request and handle the response
    match llm.chat(&messages).await {
        Ok(response) => {
            // Print the response text
            if let Some(text) = response.text() {
                println!("Response: {text}");
            }
            // Print usage information
            if let Some(usage) = response.usage() {
                println!("  Prompt tokens: {}", usage.prompt_tokens);
                println!("  Completion tokens: {}", usage.completion_tokens);
            } else {
                println!("No usage information available");
            }
        }
        Err(e) => eprintln!("Chat error: {e}"),
    }
    Ok(())
}
Runs on
GPU support unknown
What shows it
  • no dependency or feature matches a backend row
Native code
Optional
  • Binds native code: alsa-sys (feature audio-example)
Python bindings
No Python binding crate found
License
MIT

Compare with similar projects

Order: strongest tier first, then most downloads, then name, with unmeasured values last. A library counts downloads over 30 days. An app counts binary downloads per release. An app with none counts its crate downloads over 30 days. ML Rust runs this catalogue, so its closest project always gets a row.

llm beside the projects that share a topic with it
ProjectDownloadsDependentsStarsLatest releaseRuns on (GPU)Native codeLicense
llm This page Featured

A Rust library unifying multiple LLM backends.

7,669 downloads over 30 days 34 365 1.3.8 GPU support unknown Binds native code: alsa-sys (feature audio-example) MIT
async-openai Featured

Rust library for OpenAI

1,302,033 downloads over 30 days 275 2,031 0.43.0 GPU support unknown No native code found MIT
rllm Listed

Unifies multiple LLM backends in Rust.

60 downloads over 30 days 0 137 1.1.9 GPU support unknown No native code found MIT
vtcode App Listed

A Rust-based terminal coding agent with modular architecture supporting multiple LLM providers

56 binary downloads per release Not applicable 903 0.181.5 GPU support unknown Binds native code: ring, tree-sitter, vtcode-ghostty-vt-sys, libdbus-sys, libmimalloc-sys and 4 more Apache-2.0 OR MIT
ollamaMQ App Listed

High-performance LLM backends proxy with per-user fair-share queuing, round-robin scheduling, and a real-time TUI dashboard. Built in Rust.

8 downloads over 30 days Not applicable 133 0.5.0 GPU support unknown No native code found MIT
axp App Listed

An open protocol that gives AI agents a secure, sandboxed place to run code and use tools — with lean context usage. AXP works alongside MCP

Not measured Not applicable 3 Not measured Not measured Not measured Apache-2.0

Foundation library for Rust AI-native apps — provider catalog, LLM client, MCP server, search, telemetry, and safety

791 downloads over 30 days 8 3 0.33.1 GPU support unknown Binds native code: libsqlite3-sys (feature store), mach-sys (feature embedding-mlx), mlx-sys (feature embedding-mlx), openssl-sys (feature graph-pg-tls), ort-sys (feature embedding-fastembed-coreml) Apache-2.0
Why FeaturedIt passes every Featured gate.

What it meets

  • It has 14 active dependents and 12 new dependents in 365 days. Featured needs 11 active dependents or 9 new dependents in 365 days.
  • Active dependents are at 100% of their peak. Featured needs at least 50%.
  • Docs are present. The release commit or a manifest ties the crate to the repository.
  • No vulnerability advisory stays unpatched past the grace window. At least one version is neither a prerelease nor 0.0.x.
  • The last activity is on 6 Jun 2026, 156 days ago. The rules expect an update within 1400 days. Dormancy rule

Exact rules: Featured library. The check on applied thresholds version 9.

Every rule outcome, as the check records it
  • expected-interval: version 1.3.8 base 700, doubled for 14 active users: E = 1400 days
  • dormancy: last activity 2026-06-06, 156 days ago, E = 1400: active
  • featured: featured: active_users 14, new_adopters 12, former_glory 1

Measurements and sources

Each signal row shows the raw value, its source and the fetch date. The Sources list gathers every distinct source on this page. Movement needs more history.

Sources6 sources
Adoption14 active dependents, 12 new dependents in 365 days1 not measured
Adoption measurements
SignalValueSourceFetchedCounts
Active dependents14crates.io database dumpYes
New dependents (365 days)12crates.io database dumpYes
Peak active dependents14crates.io database dumpYes
Active dependents as a share of the peak1crates.io database dumpYes
Binary downloads per releaseNot measuredYes
MaintenanceLatest human commit: 5 months ago3 not measured
Maintenance measurements
SignalValueSourceFetchedCounts
Latest human commit2026-06-06GitHub repositoryYes
Latest release2026-04-19crates.io database dumpYes
First release2023-05-04crates.io database dumpYes
Latest version1.3.8crates.io database dumpYes
Days the oldest outside issue waits for a reply633GitHub repositoryYes
Maintainer replies over 365 days17GitHub repositoryYes
Repository archivedfalseGitHub repositoryYes
Repository gonefalseGitHub repositoryYes
Release commit or manifest in the repotruecrates.io packageYes
Published docstruecrates.io database dumpYes
Latest release fails cargo checkNot measuredYes
Build check dateNot measuredYes
Build check toolchainNot measuredYes
SecurityUnpatched vulnerabilities: none
Security measurements
SignalValueSourceFetchedCounts
Unpatched vulnerabilities past the grace windownoneRustSec advisory databaseYes
RustSec unmaintained advisorynoneRustSec advisory databaseYes
Deprecation noticenonecrates.io database dumpYes
Deprecated requirementnonecrates.io database dumpYes
Distribution32 releases, 7,669 downloads over 30 days5 not measured
Distribution measurements
SignalValueSourceFetchedCounts
Releases32crates.io database dumpYes
Downloads over 30 days7669crates.io database dumpYes
Binary downloads over the last 3 releasesNot measuredYes
Homebrew installs on request over 365 daysNot measuredYes
Repology repository familiesNot measuredYes
Docker pull growth over 90 daysNot measuredYes
Docker pulls at the growth baselineNot measuredYes
Every version a prereleasefalsecrates.io database dumpYes
Every version 0.0.xfalsecrates.io database dumpYes
Every version yankedfalsecrates.io database dumpYes
Crate deleted from crates.iofalsecrates.io database dumpYes
Repository365 stars, 90 forks, 24 contributors, 505 commits. Stars alone never qualify a project.
Repository measurements
SignalValueSourceFetchedCounts
GitHub stars365GitHub repositoryYes — one part of the repository route
GitHub forks90GitHub repositoryYes — one part of the repository route
Contributors with a GitHub account24GitHub contributorsYes — one part of the repository route
Commits on the default branch505GitHub repositoryNo
Repository's main crate left out of the entrynonecrates.io database dumpYes
Facts that never count
Facts that never count measurements
SignalValueSourceFetchedCounts
LicenseMITcrates.io database dumpNo
Runs on, from listed crates and their direct dependenciesGPU support unknowncrates.io database dumpNo
What shows each backendno dependency or feature matches a backend rowcrates.io database dumpNo
Native code, from listed crates and their dependenciesBinds native code: alsa-sys (feature audio-example)crates.io database dumpNo
Python bindings, from direct dependencies of listed cratesNo Python binding crate foundcrates.io database dumpNo
Crates that depend on a listed crate directly34crates.io database dumpNo

Corrections and review history

Report a correction

No correction applies to this entry.

Judgments

A judgment enters only through an approved issue and a merged pull request.

No judgment applies to this entry.