mistral.rs 集成
在本地运行 LLMs,使用原生 Rust 推理 - 无需外部服务器,无需 API 密钥。
什么是 mistral.rs?
mistral.rs 是一个高性能的 Rust 推理引擎,可在您的硬件上直接运行 LLMs。 ADK-Rust 通过 adk-mistralrs crate 集成它,固定到 v0.8.0 并支持 Gemma 4。
主要亮点:
- 🦀 原生 Rust - 无 Python,无外部服务器
- 🔒 完全离线 - 无 API 密钥或互联网要求
- ⚡ 硬件加速 - CUDA, Metal (3.1 bfloat16), CPU 优化
- 📦 量化 - ISQ, MXFP4, GGUF, UQFF,用于在有限硬件上运行大型模型
- 🔧 LoRA 适配器 - 支持微调模型并支持热插拔
- 👁️ 多模态 - 视觉、音频和视频理解 (Gemma 4, Qwen 3 VL)
- 🎤 语音 - Voxtral 实时语音识别
- 🎯 多模型 - 从一个实例提供多个模型
步骤 1:添加依赖
adk-mistralrs 作为工作区成员发布到 crates.io。将其添加为标准依赖项:
[package]
name = "my-local-agent"
version = "0.1.0"
edition = "2024"
[dependencies]
adk-mistralrs = "2.0.0"
adk-agent = "2.0.0"
adk-rust = "2.0.0"
tokio = { version = "1", features = ["full"] }
anyhow = "1.0"
对于硬件加速,添加功能标志:
# macOS with Apple Silicon
adk-mistralrs = { version = "2.0.0", features = ["metal"] }
# NVIDIA GPU (requires CUDA toolkit)
adk-mistralrs = { version = "2.0.0", features = ["cuda"] }
步骤 2:基本示例
从 HuggingFace 加载模型并在本地运行:
use adk_agent::LlmAgentBuilder;
use adk_mistralrs::{Llm, MistralRsConfig, MistralRsModel, ModelSource};
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load model from HuggingFace (downloads on first run)
let config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("microsoft/Phi-3.5-mini-instruct"))
.build();
println!("Loading model (this may take a while on first run)...");
let model = MistralRsModel::new(config).await?;
println!("Model loaded: {}", model.name());
// Create agent
let agent = LlmAgentBuilder::new("local_assistant")
.description("Local AI assistant powered by mistral.rs")
.instruction("You are a helpful assistant running locally. Be concise.")
.model(Arc::new(model))
.build()?;
// Run interactive chat
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
会发生什么:
- 首次运行会从 HuggingFace 下载模型(根据模型大小,约 2-8GB)
- 模型会本地缓存到
~/.cache/huggingface/ - 后续运行会立即从缓存加载
步骤 3:使用量化减少内存
大型模型需要大量 RAM。使用 ISQ (In-Situ Quantization) 来减少内存:
use adk_agent::LlmAgentBuilder;
use adk_mistralrs::{Llm, MistralRsConfig, MistralRsModel, ModelSource, QuantizationLevel};
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load model with 4-bit quantization for reduced memory
let config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("microsoft/Phi-3.5-mini-instruct"))
.isq(QuantizationLevel::Q4_0) // 4-bit quantization
.paged_attention(true) // Memory-efficient attention
.build();
println!("Loading quantized model...");
let model = MistralRsModel::new(config).await?;
println!("Model loaded: {}", model.name());
let agent = LlmAgentBuilder::new("quantized_assistant")
.instruction("You are a helpful assistant. Be concise.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
量化级别:
| 等级 | 内存减少 | 质量 | 最适合 |
|---|---|---|---|
Q4_0 | ~75% | 良好 | 有限的内存 (8GB) |
Q4_1 | ~70% | 更好 | 平衡 |
Q8_0 | ~50% | 高 | 注重质量 |
Q8_1 | ~50% | 最高 | 最佳质量 |
步骤 4: LoRA 适配器(微调模型)
使用 LoRA 适配器加载模型以执行专业任务:
use adk_agent::LlmAgentBuilder;
use adk_mistralrs::{AdapterConfig, Llm, MistralRsAdapterModel, MistralRsConfig, ModelSource};
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Load base model with LoRA adapter
let config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("meta-llama/Llama-3.2-3B-Instruct"))
.adapter(AdapterConfig::lora("username/my-lora-adapter"))
.build();
println!("Loading model with LoRA adapter...");
let model = MistralRsAdapterModel::new(config).await?;
println!("Model loaded: {}", model.name());
println!("Available adapters: {:?}", model.available_adapters());
let agent = LlmAgentBuilder::new("lora_assistant")
.instruction("You are a helpful assistant with specialized knowledge.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
在运行时热插拔适配器:
model.swap_adapter("another-adapter").await?;
步骤 5: 视觉模型(图像理解)
使用视觉语言模型处理图像:
use adk_mistralrs::{Llm, MistralRsConfig, MistralRsVisionModel, ModelSource};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("microsoft/Phi-3.5-vision-instruct"))
.build();
println!("Loading vision model...");
let model = MistralRsVisionModel::new(config).await?;
println!("Model loaded: {}", model.name());
// Analyze an image
let image = image::open("photo.jpg")?;
let response = model.generate_with_image("Describe this image.", vec![image]).await?;
Ok(())
}
步骤 6: 多模型服务
从单个实例提供多个模型:
use adk_mistralrs::{MistralRsConfig, MistralRsMultiModel, ModelSource};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let multi = MistralRsMultiModel::new();
// Add models
let phi_config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("microsoft/Phi-3.5-mini-instruct"))
.build();
multi.add_model("phi", phi_config).await?;
let gemma_config = MistralRsConfig::builder()
.model_source(ModelSource::huggingface("google/gemma-2-2b-it"))
.build();
multi.add_model("gemma", gemma_config).await?;
// Set default and route requests
multi.set_default("phi").await?;
println!("Available models: {:?}", multi.model_names().await);
// Route to specific model
// multi.generate_with_model(Some("gemma"), request, false).await?;
Ok(())
}
模型来源
HuggingFace Hub(默认)
ModelSource::huggingface("microsoft/Phi-3.5-mini-instruct")
本地目录
ModelSource::local("/path/to/model")
预量化 GGUF
ModelSource::gguf("/path/to/model.Q4_K_M.gguf")
推荐模型
| 模型 | 大小 | 所需内存 | 最佳用途 |
|---|---|---|---|
google/gemma-4-4b-it | 4B | 8GB | Gemma 4 — 多模态(文本、图像、音频、视频), Apache 2.0 |
google/gemma-4-12b-it | 12B | 24GB | Gemma 4 — 高质量多模态推理 |
microsoft/Phi-3.5-mini-instruct | 3.8B | 8GB | 快速、通用 |
microsoft/Phi-3.5-vision-instruct | 4.2B | 10GB | 视觉 + 文本 |
Qwen/Qwen3-4B | 4B | 8GB | 多语言、编码、推理 |
Qwen/Qwen3.5-7B-Instruct | 7B | 16GB | 最新 Qwen 具有强大的推理能力 |
google/gemma-2-2b-it | 2B | 4GB | 轻量级 |
mistralai/Mistral-7B-Instruct-v0.3 | 7B | 16GB | 高质量 |
硬件加速
macOS (Apple Silicon)
adk-mistralrs = { version = "2.0.0", features = ["metal"] }
在 M1/M2/M3 Mac 上,Metal 加速是自动的。
NVIDIA GPU
adk-mistralrs = { version = "2.0.0", features = ["cuda"] }
需要 CUDA toolkit 11.8+。
仅限 CPU
无需任何功能 - CPU 是默认设置。
验证 Crate
cargo build -p adk-mistralrs
cargo build -p adk-mistralrs --features metal
故障排除
内存不足
// Enable quantization
.isq(QuantizationLevel::Q4_0)
// Enable paged attention
.paged_attention(true)
首次加载缓慢
- 首次运行会下载模型(约 2-8GB)
- 后续运行使用缓存模型
未找到模型
- 检查 HuggingFace 模型 ID 是否正确
- 确保首次下载时有互联网连接
相关
上一页: ← Ollama (本地) | 下一页: Function Tools →