本地 LLM 部署与 LangChain 应用开发

# 本地 LLM 部署与 LangChain 应用开发 > 本文介绍如何在本地环境部署大语言模型(LLM),并通过 LangChain 框架构建 AI 应用,涵盖模型部署、微调、API 集成等完整流程。 ## 本地 LLM 部署方案 ### 硬件要求 | 模型规模 | 显存需求 | 推荐显卡 | 适

# 本地 LLM 部署与 LangChain 应用开发 > 本文介绍如何在本地环境部署大语言模型(LLM),并通过 LangChain 框架构建 AI 应用,涵盖模型部署、微调、API 集成等完整流程。 ## 本地 LLM 部署方案 ### 硬件要求 | 模型规模 | 显存需求 | 推荐显卡 | 适用场景 | |----------|----------|----------|----------| | 7B (INT4) | 8GB+ | RTX 3060 12G | 个人开发 | | 13B (INT4) | 12GB+ | RTX 4070 Ti | 小型团队 | | 70B (INT4) | 48GB+ | A6000/A100 | 企业应用 | ### WSL2 + Docker 部署方案 **WSL2 配置**: ```powershell # 启用 WSL Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux # 设置 WSL 默认版本 wsl --set-default-version 2 # 导入 Ubuntu wsl --import Ubuntu-LLM $env:USERPROFILE\wsl-llm ubuntu-22.04.tar.gz ``` **安装 NVIDIA 容器工具包**: ```bash # 添加 NVIDIA 仓库 curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add - distribution=$(. /etc/os-release;echo $ID$VERSION_ID) curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | \ sudo tee /etc/apt/sources.list.d/nvidia-docker.list # 安装工具包 apt-get update apt-get install -y nvidia-container-toolkit ``` **部署 ChatGLM/ChatChat**: ```bash # 一键启动本地大模型+dashboard docker run -d --gpus all -p 80:8501 \ registry.cn-beijing.aliyuncs.com/chatchat/chatchat:0.2.10 ``` ## 模型微调实践 ### 环境准备 ```bash # 安装 Git LFS apt-get install git git-lfs -y git lfs install # 下载模型 MODEL_DIR="/data/model/chatglm2-6b" git clone https://huggingface.co/THUDM/chatglm2-6b-int4 $MODEL_DIR ``` ### 基础推理测试 ```python from transformers import AutoTokenizer, AutoModel # 加载模型 model_path = "/data/model/chatglm2-6b" tokenizer = AutoTokenizer.from_pretrained( model_path, trust_remote_code=True ) model = AutoModel.from_pretrained( model_path, trust_remote_code=True ).half().cuda() model = model.eval() # 对话测试 response, history = model.chat( tokenizer, "你好,请介绍一下自己", history=[] ) print(response) ``` ### P-Tuning 微调 ```bash # 安装依赖 pip install rouge_chinese nltk jieba datasets peft # 准备训练数据 # data/train.json 格式: # { # "prompt": "问题内容", # "response": "期望回答", # "history": [] # } # 启动训练 bash train.sh # train.sh 示例 # PRE_SEQ_LEN=128 # LR=2e-2 # CUDA_VISIBLE_DEVICES=0 python main.py \ # --do_train \ # --train_file data/train.json \ # --prompt_column prompt \ # --response_column response \ # --model_name_or_path THUDM/chatglm2-6b \ # --output_dir output/adgen-chatglm2-6b-pt-$PRE_SEQ_LEN-$LR \ # --overwrite_output_dir \ # --max_source_length 64 \ # --max_target_length 128 \ # --per_device_train_batch_size 1 \ # --per_device_eval_batch_size 1 \ # --gradient_accumulation_steps 16 \ # --predict_with_generate \ # --max_steps 3000 \ # --logging_steps 10 \ # --save_steps 1000 \ # --learning_rate $LR \ # --pre_seq_len $PRE_SEQ_LEN ``` ## LangChain 集成开发 ### LangChain 简介 LangChain 是一个用于开发 LLM 应用的框架,提供: - **模型接口**:统一调用不同 LLM - **提示词管理**:模板化 Prompt - **链式调用**:复杂任务编排 - **工具集成**:搜索引擎、数据库等 - **记忆管理**:对话上下文保持 ### 基础使用 ```python from langchain.llms import ChatGLM from langchain import LLMChain, PromptTemplate # 配置本地模型 llm = ChatGLM( endpoint_url="http://localhost:8000", max_token=2048, temperature=0.7 ) # 定义模板 template = """ 你是一个专业的{role}。 请回答以下问题:{question} """ prompt = PromptTemplate( input_variables=["role", "question"], template=template ) # 创建链 chain = LLMChain(llm=llm, prompt=prompt) # 执行 result = chain.predict( role="Python 专家", question="什么是装饰器?" ) print(result) ``` ### 检索增强生成 (RAG) ```python from langchain.embeddings import HuggingFaceEmbeddings from langchain.vectorstores import Chroma from langchain.text_splitter import CharacterTextSplitter from langchain.document_loaders import TextLoader # 加载文档 loader = TextLoader("docs/knowledge.txt") documents = loader.load() # 文本分割 text_splitter = CharacterTextSplitter( chunk_size=1000, chunk_overlap=0 texts = text_splitter.split_documents(documents) # 创建向量库 embeddings = HuggingFaceEmbeddings( model_name="shibing624/text2vec-base-chinese" ) db = Chroma.from_documents(texts, embeddings) # 检索问答 from langchain.chains import RetrievalQA qa_chain = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=db.as_retriever() ) result = qa_chain.run("根据文档,系统架构是什么?") ``` ### Agent 智能体 ```python from langchain.agents import Tool, AgentExecutor, initialize_agent from langchain.tools import DuckDuckGoSearchRun # 定义工具 tools = [ Tool( name="搜索", func=DuckDuckGoSearchRun().run, description="用于搜索互联网信息" ), Tool( name="计算", func=lambda x: eval(x), description="用于执行数学计算" ) ] # 创建 Agent agent = initialize_agent( tools, llm, agent="zero-shot-react-description", verbose=True ) # 执行任务 agent.run("2024年最新的Python版本是什么?它的主要特性有哪些?") ``` ## 常见问题解决 ### 显存不足 ```python # 使用 INT4 量化 model = AutoModel.from_pretrained( model_path, trust_remote_code=True ).quantize(4).cuda() # 或使用 CPU 卸载 model = AutoModel.from_pretrained( model_path, trust_remote_code=True, device_map="auto" ) ``` ### Tokenizer 错误 ```bash # 安装缺失依赖 pip install cpm_kernels sentencepiece # 更新 tokenization 文件 # 从官方仓库重新下载 tokenization_chatglm.py ``` ### CUDA 版本不匹配 ```bash # 检查 CUDA 版本 nvidia-smi nvcc --version # 安装对应版本 PyTorch pip install torch torchvision torchaudio \ --index-url https://download.pytorch.org/whl/cu118 ``` ## 生产环境部署 ### API 服务 ```python from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Query(BaseModel): question: str history: list = [] @app.post("/chat") async def chat(query: Query): response, history = model.chat( tokenizer, query.question, history=query.history ) return { "answer": response, "history": history } # 启动 # uvicorn api:app --host 0.0.0.0 --port 8000 ``` ### 负载均衡 ```nginx upstream llm_backend { server 127.0.0.1:8000; server 127.0.0.1:8001; server 127.0.0.1:8002; } server { listen 80; location /chat { proxy_pass http://llm_backend; proxy_set_header Connection ""; proxy_http_version 1.1; } } ``` ## 性能优化 ### 推理加速 ```python # 使用 BetterTransformer from optimum.bettertransformer import BetterTransformer model = BetterTransformer.transform(model) # Flash Attention # 安装: pip install flash-attn from transformers import AutoModel model = AutoModel.from_pretrained( model_path, trust_remote_code=True, attn_implementation="flash_attention_2" ) ``` ### 批处理 ```python # 批量推理 questions = ["问题1", "问题2", "问题3"] results = [] for q in questions: response, _ = model.chat(tokenizer, q, history=[]) results.append(response) ``` ## 小结 本文介绍了本地 LLM 部署与 LangChain 应用开发的完整流程: 1. **环境准备**:WSL2/Docker + NVIDIA 容器 2. **模型部署**:ChatGLM 等开源模型本地运行 3. **模型微调**:P-Tuning 特定领域优化 4. **LangChain 集成**:RAG、Agent 应用开发 5. **生产部署**:API 服务、负载均衡 适用场景: - 数据隐私要求高的企业内网 - 定制化 AI 应用开发 - 低延迟本地推理需求 --- *参考资料*: - [ChatGLM GitHub](https://github.com/THUDM/ChatGLM2-6B) - [LangChain 文档](https://python.langchain.com/) - [Hugging Face Transformers](https://huggingface.co/docs/transformers/)
LICENSED UNDER CC BY-NC-SA 4.0
Comment