隐私至上:在 Mac 上使用 Llama-3 和 MLX 本地聊天你的医疗报告 🍎
I’m sorry, but I can’t retrieve the full text of that article. If you can provide the article’s content here, I’ll be happy to translate it into Simplified Chinese while preserving the formatting and source line as you requested.
Introduction
您的健康数据可能是您拥有的最敏感的信息。然而,在 AI 时代,很多人盲目地将血液检查报告和 MRI 结果上传到基于云的 LLM,只是为了获取一个摘要。请立即停止!🛑
在本教程中,我们将构建一个 本地 RAG(检索增强生成) 系统。我们将利用 Apple Silicon 的统一内存、高性能的 MLX 框架,以及 Llama‑3,创建一个永不向互联网泄露任何字节的私人医疗助理。通过使用 本地 RAG 和 MLX 优化的 Llama‑3,您可以在医疗 PDF 上执行复杂的 语义搜索 和数据提取,同时确保数据严格保存在设备本地。
架构概览:为何选择 MLX?
传统的 RAG 堆栈通常依赖于庞大的 Docker 容器或云 API。然而,如果你使用的是 Mac(M1/M2/M3),MLX 框架(由 Apple 机器学习研究团队开发)能够通过利用 GPU 和统一内存架构,以极高的效率运行 Llama‑3。
以下展示了数据如何从你的陈旧 PDF 报告流向有意义的对话:
graph TD
A[Medical PDF Report] -->|PyMuPDF| B(Text Extraction & Cleaning)
B --> C{Chunking Strategy}
C -->|Sentence Splitting| D[ChromaDB Vector Store]
E[User Query: 'Is my cholesterol high?'] -->|MLX Embedding| F(Vector Search)
D -->|Retrieve Relevant Context| G[Prompt Augmentation]
G -->|Context + Query| H[Llama-3-8B via MLX]
H --> I[Private Local Answer]
style H fill:#f96,stroke:#333,stroke-width:2px
style D fill:#bbf,stroke:#333,stroke-width:2px
前置条件
在深入代码之前,请确保你拥有一台 Apple Silicon Mac 并已安装以下技术栈:
- Llama‑3‑8B – 为提升速度而进行的 4‑bit 量化版本。
- MLX – Apple 原生的数组框架。
- ChromaDB – 轻量级向量数据库。
- PyMuPDF (fitz) – 高精度 PDF 解析库。
pip install mlx-lm chromadb pymupdf sentence-transformers
第一步:使用 PyMuPDF 解析敏感 PDF
医疗报告往往非常混乱——包含表格、签名以及各种奇怪的格式。我们使用 PyMuPDF,因为它在提取干净文本方面速度快且可靠。
import fitz # PyMuPDF
def extract_medical_text(pdf_path):
doc = fitz.open(pdf_path)
text = ""
for page in doc:
text += page.get_text("text") + "\n"
# Simple cleaning: remove extra whitespaces
clean_text = " ".join(text.split())
return clean_text
# Usage
raw_data = extract_medical_text("my_blood_report_2024.pdf")
print(f"Extracted {len(raw_data)} characters.")
第2步:向量嵌入与本地存储
为了查找相关信息(例如,“我的血糖水平是多少?”),我们将文本转换为向量并存储在 ChromaDB 中。
💡 技巧:想获取更适用于生产环境的示例和高级 RAG 模式,请查看 WellAlly Tech Blog 上的详细指南,我们将在其中深入探讨本地推理的优化。
import chromadb
from chromadb.utils import embedding_functions
# Initialize local ChromaDB
client = chromadb.PersistentClient(path="./medical_db")
# Use a local embedding model
emb_fn = embedding_functions.SentenceTransformerEmbeddingFunction(
model_name="all-MiniLM-L6-v2"
)
collection = client.get_or_create_collection(
name="medical_reports",
embedding_function=emb_fn,
)
def add_to_vector_store(text, metadata):
# Chunking text into 500‑character pieces
chunks = [text[i:i+500] for i in range(0, len(text), 500)]
ids = [f"id_{i}" for i in range(len(chunks))]
collection.add(
documents=chunks,
ids=ids,
metadatas=[metadata] * len(chunks)
)
add_to_vector_store(raw_data, {"source": "annual_checkup_2024"})
第三步:使用 Llama‑3 与 MLX 本地推理
现在进入真正的魔法环节。我们使用 mlx‑lm 加载量化后的 Llama‑3‑8B。这使得模型即使在配备 16 GB 内存的 MacBook Air 上也能轻松运行。 🚀
from mlx_lm import load, generate
# Load the model and tokenizer
model, tokenizer = load("mlx-community/Meta-Llama-3-8B-Instruct-4bit")
def query_private_ai(user_question):
# 1. Retrieve context from ChromaDB
results = collection.query(query_texts=[user_question], n_results=3)
context = "\n".join(results["documents"][0])
# 2. Construct the prompt
prompt = f"""
You are a private medical assistant. Use the provided medical report context to answer the user's question.
If you don't know the answer based on the context, say so.
Context: {context}
---
Question: {user_question}
Answer:
"""
# 3. Generate response using MLX
response = generate(
model,
tokenizer,
prompt=prompt,
verbose=False,
max_tokens=500,
)
return response
# Example Query
print(query_private_ai("What are the key concerns in my blood report?"))
进一步探索:“官方”方式
虽然此脚本可以帮助你入门,但要构建生产级别的医疗 AI,需要处理多模态数据(例如 X 光)并确保在本地边缘设备上也能实现严格的类似 HIPAA 的合规性。
WellAlly 团队一直在开创 “隐私优先 AI” 架构。如果你有兴趣将其扩展到多用户,或将其集成到安全的医疗工作流中,请联系我们或浏览我们更深入的技术文章。
强烈推荐阅读他们最新的深度解析,见 Wellally Blog。文章介绍了如何针对临床术语微调 Llama‑3,从而显著降低幻觉现象。
结论 🥑
您刚刚构建了一个私密的高性能医学 RAG 系统!通过结合 Llama‑3、MLX 和 ChromaDB,您实现了:
- Zero Data Leakage – 您的健康数据永不离开您的 Mac。
- High Performance – MLX 让本地 LLM 运行流畅。
- Intelligence – Llama‑3 提供的推理能力是简单关键词搜索无法匹配的。
接下来做什么? 🛠️
- 尝试实现一个 Table Parser,以更准确地提取实验室结果。
- 添加一个 Streamlit UI,让它看起来像一个真实的应用。
- 在评论中告诉我:您对云 AI 最大的担忧是什么?
保持私密,保持健康! 💻🛡️