关于 Where On-Device and Cloud LLMs Meet
该项目是一个演示协议,让小型端侧模型与云端大模型协作,端侧模型只在本地处理长上下文,以降低云端成本。适合希望控制 API 费用的研究者和开发者。
主要功能
- 01端侧小模型与云端大模型协同工作
- 02本地读取长上下文以减少云端开销
- 03提供 Minion 与 Minions 两种协议
- 04支持多种本地模型服务与云端 API
适用场景
- 01降低长文档分析的云端 API 费用
- 02在本地模型与云端模型之间拆分任务
- 03在 Docker 容器中通过 stdin/stdout 运行协议
详细介绍

设备端与云端大模型的交汇
这是什么? Minions 是一种通信协议,可让设备端的小型模型与云端的前沿模型协作。只在本地读取较长的上下文,就能在几乎不降低或完全不降低质量的情况下减少云端成本。本仓库提供了该协议的演示。请参阅下方的入门说明,或查看下方的论文和博客文章了解更多信息。
论文:Minions:设备端与云端语言模型之间的高性价比协作
Minions 博客文章:https://hazyresearch.stanford.edu/blog/2025-02-24-minions
Secure Minions Chat 博客文章:https://hazyresearch.stanford.edu/blog/2025-05-12-security
目录
在寻找 Secure Minions Chat? 如果您对我们的端到端加密聊天系统感兴趣,请参阅 Secure Minions Chat README,了解详细的设置和使用说明。
- 设置
- Minions 演示应用
- Minions WebGPU 应用
- 示例代码
- Python Notebook
- Docker 支持
- 命令行界面
- Secure Minions 本地-远程协议
- Secure Minions Chat
- 应用
- 推理估算器
- 其他设置
- 维护者
设置
我们已在 Mac 和 Ubuntu 上使用 Python 3.10-3.11 测试了以下设置(注意:不支持 Python 3.13)
可选:使用你喜欢的包管理器(例如 conda、venv、uv)创建虚拟环境
conda create -n minions python=3.11
步骤 1: 克隆仓库并安装 Python 包。
git clone https://github.com/HazyResearch/minions.git
cd minions
pip install -e . # installs the minions package in editable mode
注意:如需安装可选的 MLX-LM,请运行以下命令安装该包:
pip install -e ".[mlx]"
注意:如需使用安全的 Minions 聊天,请运行以下命令安装该包:
pip install -e ".[secure]"
注意:如需安装可选的 Cartesia-MLX,请先使用 pip 安装基础包,然后按照以下说明操作。
步骤 2: 安装用于运行本地模型的服务端。
我们支持使用三个服务端运行本地模型:lemonade、ollama 和 tokasaurus。你至少需要安装其中一个。
- 如果你无法使用 NVIDIA/AMD GPU,应使用
ollama。按照此处的说明安装ollama。要启用 Flash Attention,请运行launchctl setenv OLLAMA_FLASH_ATTENTION 1;如果使用 Mac,还需重启 ollama 应用。 - 如果你可以使用本地 AMD CPU/GPU/NPU,应使用
lemonade。按照此处的说明安装lemonade。- 查看以下文档,了解支持的 APU 配置:https://ryzenai.docs.amd.com/en/latest/llm/overview.html#supported-configurations
- 安装
lemonade后,请确保启动 lemonade 服务。可以通过一键式 Windows GUI安装程序完成,该程序会将 Lemonade Server 安装为独立工具。 - 注意:Lemonade 目前不支持 Minion-CUA 协议。
- 如果你可以使用 NVIDIA GPU,并且正在运行 Minions 协议,应使用
tokasaurus,因为该协议可受益于tokasaurus的高吞吐量。运行以下命令安装tokasaurus:
pip install tokasaurus
可选:安装 Cartesia-MLX(仅适用于 Apple Silicon)
- 下载 XCode
- 运行
xcode-select --install安装命令行工具 - 安装 Nanobind🧮
pip install nanobind@git+https://github.com/wjakob/nanobind.git@2f04eac452a6d9142dedb957701bdb20125561e4
- 运行以下命令安装 Cartesia Metal 后端:
pip install git+https://github.com/cartesia-ai/edge.git#subdirectory=cartesia-metal
- 运行以下命令安装 Cartesia-MLX 包:
pip install git+https://github.com/cartesia-ai/edge.git#subdirectory=cartesia-mlx
可选:安装 llama-cpp-python
安装
首先,安装 llama-cpp-python 包:
# CPU-only installation
pip install llama-cpp-python
# For Metal on Mac (Apple Silicon/Intel)
CMAKE_ARGS="-DGGML_METAL=on" pip install llama-cpp-python
# For CUDA on NVIDIA GPUs
CMAKE_ARGS="-DGGML_CUDA=on" pip install llama-cpp-python
# For OpenBLAS CPU optimizations
CMAKE_ARGS="-DGGML_BLAS=ON -DGGML_BLAS_VENDOR=OpenBLAS" pip install llama-cpp-python
如需了解更多安装选项,请参阅 llama-cpp-python 文档。
基本用法
客户端遵循 llama-cpp-python 库的基本模式:
from minions.clients import LlamaCppClient
# Initialize the client with a local model
client = LlamaCppClient(
model_path="/path/to/model.gguf",
chat_format="chatml", # Most modern models use "chatml" format
n_gpu_layers=35 # Set to 0 for CPU-only inference
)
# Run a chat completion
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What's the capital of France?"}
]
responses, usage, done_reasons = client.chat(messages)
print(responses[0]) # The generated response
从 Hugging Face 加载模型
你可以直接从 Hugging Face 轻松加载模型:
client = LlamaCppClient(
model_path="dummy", # Will be replaced by downloaded model
model_repo_id="TheBloke/Mistral-7B-Instruct-v0.2-GGUF",
model_file_pattern="*Q4_K_M.gguf", # Optional - specify quantization
chat_format="chatml",
n_gpu_layers=35 # Offload 35 layers to GPU
)
步骤 3: 为以下至少一个云端大模型提供商设置 API 密钥。
如有需要,请创建 OpenAI API 密钥、TogetherAI API 密钥、DeepSeek API 密钥或 MiniMax API 密钥,以使用云端模型。
# OpenAI
export OPENAI_API_KEY=<your-openai-api-key>
export OPENAI_BASE_URL=<your-openai-base-url> # Optional: Use a different OpenAI API endpoint
# Together AI
export TOGETHER_API_KEY=<your-together-api-key>
# OpenRouter
export OPENROUTER_API_KEY=<your-openrouter-api-key>
export OPENROUTER_BASE_URL=<your-openrouter-base-url> # Optional: Use a different OpenRouter API endpoint
# Perplexity
export PERPLEXITY_API_KEY=<your-perplexity-api-key>
export PERPLEXITY_BASE_URL=<your-perplexity-base-url> # Optional: Use a different Perplexity API endpoint
# Tokasaurus
export TOKASAURUS_BASE_URL=<your-tokasaurus-base-url> # Optional: Use a different Tokasaurus API endpoint
# DeepSeek
export DEEPSEEK_API_KEY=<your-deepseek-api-key>
# Anthropic
export ANTHROPIC_API_KEY=<your-anthropic-api-key>
# Mistral AI
export MISTRAL_API_KEY=<your-mistral-api-key>
# MiniMax
export MINIMAX_API_KEY=<your-minimax-api-key>
# Gemini
export GEMINI_API_KEY=<your-gemini-api-key>
# Groq
export GROQ_API_KEY=<your-groq-api-key>
# Grok (xAI)
export XAI_API_KEY=<your-xai-api-key>
# Cohere
export COHERE_API_KEY=<your-cohere-api-key>
Minions 演示应用
要试用 Minion 或 Minions 协议,请运行以下命令:
pip install torch transformers
streamlit run app.py
如果你遇到有关 ollama 客户端的错误,
An error occurred: Failed to connect to Ollama. Please check that Ollama is downloaded, running and accessible. https://ollama.com/download
请尝试运行以下命令:
OLLAMA_FLASH_ATTENTION=1 ollama serve
Minions WebGPU 应用
Minions WebGPU 应用展示了如何完全在浏览器中运行 Minions 协议:使用 WebGPU 进行本地模型推理,并通过云端 API 提供监督。这种方式无需设置本地服务端,同时提供了易于使用的 Web 界面。
功能
- 基于浏览器:完全在 Web 浏览器中运行,无需本地服务器
- WebGPU 加速:使用 WebGPU 加速本地模型推理
- 模型选择:从 MLC AI 提供的多个预优化模型中进行选择
- 实时进度:实时查看模型加载进度和对话日志
- 注重隐私:你的 API 密钥和数据不会离开浏览器
快速开始
-
进入 WebGPU 应用目录:
cd apps/minions-webgpu -
安装依赖:
npm install -
启动开发服务器:
npm start -
打开浏览器,并访问终端中显示的 URL(通常为
http://localhost:5173)
示例代码:Minion(单数)
以下示例使用 ollama 本地客户端和 openai 远程客户端。
协议为 minion。
from minions.clients.ollama import OllamaClient
from minions.clients.openai import OpenAIClient
from minions.minion import Minion
local_client = OllamaClient(
model_name="llama3.2",
)
remote_client = OpenAIClient(
model_name="gpt-4o",
)
# Instantiate the Minion object with both clients
minion = Minion(local_client, remote_client)
context = """
Patient John Doe is a 60-year-old male with a history of hypertension. In his latest checkup, his blood pressure was recorded at 160/100 mmHg, and he reported occasional chest discomfort during physical activity.
Recent laboratory results show that his LDL cholesterol level is elevated at 170 mg/dL, while his HDL remains within the normal range at 45 mg/dL. Other metabolic indicators, including fasting glucose and renal function, are unremarkable.
"""
task = "Based on the patient's blood pressure and LDL cholesterol readings in the context, evaluate whether these factors together suggest an increased risk for cardiovascular complications."
# Execute the minion protocol for up to two communication rounds
output = minion(
task=task,
context=[context],
max_rounds=2
)
示例代码:Minions(复数)
以下示例使用 ollama 本地客户端和 openai 远程客户端。
协议为 minions。
from minions.clients.ollama import OllamaClient
from minions.clients.openai import OpenAIClient
from minions.minions import Minions
from pydantic import BaseModel
class StructuredLocalOutput(BaseModel):
explanation: str
citation: str | None
answer: str | None
local_client = OllamaClient(
model_name="llama3.2",
temperature=0.0,
structured_output_schema=StructuredLocalOutput
)
remote_client = OpenAIClient(
model_name="gpt-4o",
)
# Instantiate the Minion object with both clients
minion = Minions(local_client, remote_client)
context = """
Patient John Doe is a 60-year-old male with a history of hypertension. In his latest checkup, his blood pressure was recorded at 160/100 mmHg, and he reported occasional chest discomfort during physical activity.
Recent laboratory results show that his LDL cholesterol level is elevated at 170 mg/dL, while his HDL remains within the normal range at 45 mg/dL. Other metabolic indicators, including fasting glucose and renal function, are unremarkable.
"""
task = "Based on the patient's blood pressure and LDL cholesterol readings in the context, evaluate whether these factors together suggest an increased risk for cardiovascular complications."
# Execute the minion protocol for up to two communication rounds
output = minion(
task=task,
doc_metadata="Medical Report",
context=[context],
max_rounds=2
)
Python Notebook
若要在 Notebook 中运行 Minion/Minions,请查看 minions.ipynb。
Docker 支持
构建 Docker 镜像
docker build -t minions-docker .
运行容器
**注意:**容器会在后台自动启动 Ollama 服务,以进行本地模型推理。这样无需额外设置,即可使用 llama3.2:3b 等模型。
# Basic usage (includes Ollama service)
docker run -i minions-docker
# With Docker socket mounted (for Docker Model Runner)
docker run -i -v /var/run/docker.sock:/var/run/docker.sock minions-docker
# With API keys for remote models
docker run -i -e OPENAI_API_KEY=your_key -e ANTHROPIC_API_KEY=your_key minions-docker
# With custom Ollama host
docker run -i -e OLLAMA_HOST=0.0.0.0:11434 minions-docker
# For Streamlit app (legacy usage)
docker run -p 8501:8501 --env OPENAI_API_KEY=<your-openai-api-key> --env DEEPSEEK_API_KEY=<your-deepseek-api-key> minions-docker
Docker Minion 协议用法
Docker 容器支持 stdin/stdout 接口,可运行各种 minion 协议。它接受以下结构的 JSON 输入:
{
"local_client": {
"type": "ollama",
"model_name": "llama3.2:3b",
"port": 11434,
"kwargs": {}
},
"remote_client": {
"type": "openai",
"model_name": "gpt-4o",
"kwargs": {
"api_key": "your_openai_key"
}
},
"protocol": {
"type": "minion",
"max_rounds": 3,
"log_dir": "minion_logs",
"kwargs": {}
},
"call_params": {
"task": "Your task here",
"context": ["Context string 1", "Context string 2"],
"max_rounds": 2
}
}
用法示例
基本 Minion 协议:
echo '{
"local_client": {
"type": "ollama",
"model_name": "llama3.2:3b"
},
"remote_client": {
"type": "openai",
"model_name": "gpt-4o"
},
"protocol": {
"type": "minion",
"max_rounds": 3
},
"call_params": {
"task": "Analyze the patient data and provide a diagnosis",
"context": ["Patient John Doe is a 60-year-old male with hypertension. Blood pressure: 160/100 mmHg. LDL cholesterol: 170 mg/dL."]
}
}' | docker run -i -e OPENAI_API_KEY=$OPENAI_API_KEY minions-docker
Minions(并行)协议:
echo '{
"local_client": {
"type": "ollama",
"model_name": "llama3.2:3b"
},
"remote_client": {
"type": "openai",
"model_name": "gpt-4o"
},
"protocol": {
"type": "minions"
},
"call_params": {
"task": "Analyze the financial data and extract key insights",
"doc_metadata": "Financial report",
"context": ["Revenue increased by 15% year-over-year. Operating expenses rose by 8%. Net profit margin improved to 12%."]
}
}' | docker run -i -e OPENAI_API_KEY=$OPENAI_API_KEY minions-docker
支持的客户端类型
本地客户端:
ollama:使用 Ollama 进行本地推理(容器中已包含)docker_model_runner:使用 Docker Model Runner 进行本地推理
远程客户端:
openai:OpenAI APIanthropic:Anthropic API
支持的协议类型
minion:单轮对话协议minions:并行处理协议
输出格式
容器会输出以下结构的 JSON:
{
"success": true,
"result": {
"final_answer": "The analysis result...",
"supervisor_messages": [...],
"worker_messages": [...],
"remote_usage": {...},
"local_usage": {...}
},
"error": null
}
出错时则输出:
{
"success": false,
"result": null,
"error": "Error message"
}
环境变量
OPENAI_API_KEY:OpenAI API 密钥ANTHROPIC_API_KEY:Anthropic API 密钥OLLAMA_HOST:Ollama 服务主机(默认设置为 0.0.0.0:11434)PYTHONPATH:Python 路径(默认设置为 /app)PYTHONUNBUFFERED:无缓冲输出(默认设置为 1)
提示和高级用法
- Ollama 模型:容器会在首次使用时自动拉取模型(例如
llama3.2:3b) - Docker Model Runner:确保 Docker 正在运行,并且可从容器内部访问
- API 密钥:将 API 密钥作为环境变量传入,以确保安全
- 卷:挂载卷以持久化工作区或日志
- 网络:如需访问本地服务,请使用
--network host
使用自定义卷:
docker run -i \
-v /var/run/docker.sock:/var/run/docker.sock \
-v $(pwd)/logs:/app/minion_logs \
-v $(pwd)/workspace:/app/workspace \
-e OPENAI_API_KEY=$OPENAI_API_KEY \
minions-docker
交互模式:
docker run -it \
-e OPENAI_API_KEY=$OPENAI_API_KEY \
minions-docker bash
然后可以手动运行接口:
python minion_stdin_interface.py
持久化容器用法
若要在不每次都重启容器和 Ollama 服务的情况下运行多个查询:
1. 启动持久化容器:
docker run -d --name minions-container -e OPENAI_API_KEY="$OPENAI_API_KEY" minions-docker
2. 向运行中的容器发送查询:
echo '{
"local_client": {"type": "ollama", "model_name": "llama3.2:3b"},
"remote_client": {"type": "openai", "model_name": "gpt-4o"},
"protocol": {"type": "minion", "max_rounds": 1},
"call_params": {"task": "How many times did Roger Federer end the year as No.1?"}
}' | docker exec -i minions-container /app/start_minion.sh
3. 发送其他查询(速度快,无需等待重启):
echo '{
"local_client": {"type": "ollama", "model_name": "llama3.2:3b"},
"remote_client": {"type": "openai", "model_name": "gpt-4o"},
"protocol": {"type": "minion", "max_rounds": 1},
"call_params": {"task": "What is the capital of France?"}
}' | docker exec -i minions-container /app/start_minion.sh
4. 完成后清理:
docker stop minions-container
docker rm minions-container
持久化容器的优势:
- ✅ Ollama 持续运行——查询之间无需等待重启
- ✅ 模型保持加载状态——后续查询速度更快
- ✅ 资源利用高效——一个容器即可处理多个查询
- ✅ 自动拉取模型——首次使用时下载模型
CLI
若要通过 CLI 运行 Minion/Minions,请查看 minions_cli.py。
运行以下命令,设置你选择的本地和远程模型。格式为 <provider>/<model_name>。可选提供商包括 ollama、openai、anthropic、together、perplexity、openrouter、groq、deepseek 和 mlx。
export MINIONS_LOCAL=ollama/llama3.2
export MINIONS_REMOTE=openai/gpt-4o
minions --help
minions --context <path_to_context> --protocol <minion|minions>
Secure Minions 本地-远程协议
Secure Minions 本地-远程协议(secure/minions_secure.py)提供了 Minions 协议的端到端加密实现,可在本地工作模型与远程主管服务之间实现安全通信。该协议包含证明验证、前向保密和重放保护。
前置条件
安装安全依赖项:
pip install -e ".[secure]"
基本用法
Python API
from minions.clients import OllamaClient
from secure.minions_secure import SecureMinionProtocol
# Initialize local client
local_client = OllamaClient(model_name="llama3.2")
# Create secure protocol instance
protocol = SecureMinionProtocol(
supervisor_url="https://your-supervisor-server.com",
local_client=local_client,
max_rounds=3,
system_prompt="You are a helpful AI assistant."
)
# Run a secure task
result = protocol(
task="Analyze this document for key insights",
context=["Your document content here"],
max_rounds=2
)
print(f"Final Answer: {result['final_answer']}")
print(f"Session ID: {result['session_id']}")
print(f"Log saved to: {result['log_file']}")
# Clean up the session
protocol.end_session()
命令行界面
python secure/minions_secure.py \
--supervisor_url https://your-supervisor-server.com \
--local_client_type ollama \
--local_model llama3.2 \
--max_rounds 3
Secure Minions Chat
如需安装 Secure Minions Chat,请运行以下命令安装软件包:
pip install -e ".[secure]"
有关如何设置客户端并运行安全聊天协议的更多详情,请参阅 Secure Minions Chat README。
应用
apps/ 目录包含展示各种用例的专用应用:
- 📊 A2A-Minions - Agent-to-Agent 集成服务
- 🎭 Character Chat - 与 AI 角色扮演
- 🔍 Document Search - 多方法文档检索
- 🐳 Docker - 搭载 HTTP 服务的容器化 Minions
- 📚 Story Teller - 搭配插图的创意故事创作
- 🛠️ Tools Comparison - MCP 工具性能比较
- 🌐 WebGPU App - 基于浏览器的 Minions 协议
推理速度估算器
Minions 提供了一个实用工具,用于估算大模型在你的硬件上的推理速度。推理速度估算器可帮助你:
- 分析硬件能力(GPU、MPS 或 CPU)
- 计算模型的峰值性能
- 估算每秒生成的 Token 数和完成时间
命令行用法
直接从命令行运行估算器,查看模型的运行速度:
python -m minions.utils.inference_estimator --model llama3.2 --tokens 1000 --describe
参数:
--model:受支持模型列表中的模型名称(例如,llama3.2、mistral7b)--tokens:要估算生成时间的 Token 数量--describe:显示详细的硬件和模型性能统计信息--quantized:指定模型已量化--quant-bits:量化位宽(4、8 或 16)
Python API 用法
你也可以在 Python 代码中使用推理速度估算器:
from minions.utils.inference_estimator import InferenceEstimator
# Initialize the estimator for a specific model
estimator = InferenceEstimator(
model_name="llama3.2", # Model name
is_quant=True, # Is model quantized?
quant_bits=4 # Quantization level (4, 8, 16)
)
# Estimate performance for 1000 tokens
tokens_per_second, estimated_time = estimator.estimate(1000)
print(f"Estimated speed: {tokens_per_second:.1f} tokens/sec")
print(f"Estimated time: {estimated_time:.2f} seconds")
# Get detailed stats
detailed_info = estimator.describe(1000)
print(detailed_info)
# Calibrate with your actual model client for better accuracy
# (requires a model client that implements a chat() method)
estimator.calibrate(my_model_client, sample_tokens=32, prompt="Hello")
估算器使用 Roofline 模型,同时考虑计算和内存带宽限制,并应用经验校准以提高准确性。校准数据会缓存至 ~/.cache/ie_calib.json,供后续使用。
其他设置
在 Minions 中使用 Azure OpenAI
设置环境变量
export AZURE_OPENAI_API_KEY=your-api-key
export AZURE_OPENAI_ENDPOINT=https://your-resource-name.openai.azure.com/
export AZURE_OPENAI_API_VERSION=2024-02-15-preview
示例代码
以下示例展示了如何在自己的代码中通过 Minions 协议使用 Azure OpenAI:
from minions.clients.ollama import OllamaClient
from minions.clients.azure_openai import AzureOpenAIClient
from minions.minion import Minion
local_client = OllamaClient(
model_name="llama3.2",
)
remote_client = AzureOpenAIClient(
model_name="gpt-4o", # This should match your deployment name
api_key="your-api-key",
azure_endpoint="https://your-resource-name.openai.azure.com/",
api_version="2024-02-15-preview",
)
# Instantiate the Minion object with both clients
minion = Minion(local_client, remote_client)
维护者
- Avanika Narayan(联系邮箱:[email protected])
评论
一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。
