Phi-3.5-Mini-Instruct保姆级教程:对接LangChain实现Agent工作流编排

1. 项目背景与价值

Phi-3.5-Mini-Instruct是微软推出的轻量级大模型,专为本地推理优化设计。本教程将带您从零开始,实现该模型与LangChain框架的无缝对接,构建可编排的Agent工作流。

相比直接使用模型,通过LangChain集成可以带来三大核心价值:

  • 工作流自动化:将单一对话能力扩展为多步骤任务处理
  • 工具集成:无缝接入搜索引擎、数据库等外部工具
  • 记忆管理:实现跨会话的长期记忆和上下文保持

2. 环境准备与安装

2.1 基础环境配置

确保您的系统满足以下要求:

  • Python 3.8+
  • CUDA 11.7+ (如需GPU加速)
  • 至少8GB显存

推荐使用conda创建独立环境:

conda create -n phi3_langchain python=3.8
conda activate phi3_langchain

2.2 依赖安装

安装核心依赖包:

pip install torch transformers langchain langchain-core

如需使用Streamlit界面,额外安装:

pip install streamlit

3. 模型加载与初始化

3.1 本地模型加载

创建model_loader.py文件,添加以下代码:

from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline

model_path = "microsoft/Phi-3-mini-128k-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    torch_dtype="auto",
    device_map="auto"
)

phi3_pipeline = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer
)

3.2 LangChain适配器封装

创建phi3_wrapper.py文件:

from langchain_core.language_models import BaseLLM
from typing import Any, List, Optional

class Phi3Wrapper(BaseLLM):
    pipeline: Any
    
    def _call(self, prompt: str, **kwargs) -> str:
        outputs = self.pipeline(
            prompt,
            max_new_tokens=kwargs.get("max_new_tokens", 1024),
            temperature=kwargs.get("temperature", 0.7),
            do_sample=True
        )
        return outputs[0]["generated_text"]
    
    @property
    def _llm_type(self) -> str:
        return "phi3-mini-instruct"

4. LangChain Agent工作流构建

4.1 基础对话链实现

创建basic_chain.py

from langchain_core.prompts import ChatPromptTemplate
from phi3_wrapper import Phi3Wrapper

prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个专业AI助手"),
    ("human", "{input}")
])

llm = Phi3Wrapper(pipeline=phi3_pipeline)
chain = prompt | llm

response = chain.invoke({"input": "解释量子计算的基本原理"})
print(response)

4.2 工具增强型Agent

创建agent_with_tools.py

from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain.tools import Tool

def search_api(query: str) -> str:
    return f"关于{query}的搜索结果..."

tools = [
    Tool(
        name="Search",
        func=search_api,
        description="用于搜索最新信息"
    )
]

agent_prompt = ChatPromptTemplate.from_messages([
    ("system", "你是一个可以调用工具的AI助手"),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}")
])

agent = create_tool_calling_agent(llm, tools, agent_prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)

response = agent_executor.invoke({
    "input": "2024年最新的AI会议有哪些?"
})
print(response["output"])

5. 高级工作流编排

5.1 多Agent协作系统

创建multi_agent_system.py

from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_core.messages import HumanMessage

class SpecialistAgent:
    def __init__(self, role: str):
        self.prompt = ChatPromptTemplate.from_messages([
            ("system", f"你是{role}领域的专家"),
            ("human", "{input}")
        ])
        self.chain = self.prompt | llm
    
    def advise(self, question: str) -> str:
        return self.chain.invoke({"input": question})

tech_agent = SpecialistAgent("技术")
business_agent = SpecialistAgent("商业")

def coordinator(question: str) -> str:
    tech = tech_agent.advise(question)
    biz = business_agent.advise(question)
    
    synthesis = llm.invoke(
        f"结合以下专家意见给出综合回答:\n技术观点:{tech}\n商业观点:{biz}"
    )
    return synthesis

print(coordinator("如何评估大模型在企业中的实施风险?"))

5.2 记忆增强型工作流

创建memory_workflow.py

from langchain_core.memory import ConversationBufferMemory

memory = ConversationBufferMemory()
memory.save_context(
    {"input": "我的名字是张三"}, 
    {"output": "好的,已记住您叫张三"}
)

prompt_with_memory = ChatPromptTemplate.from_messages([
    ("system", "你是一个有记忆的助手"),
    MessagesPlaceholder(variable_name="history"),
    ("human", "{input}")
])

chain_with_memory = {
    "input": lambda x: x["input"],
    "history": lambda x: memory.load_memory_variables({})["history"]
} | prompt_with_memory | llm

response = chain_with_memory.invoke({"input": "我叫什么名字?"})
print(response)

6. 部署与优化建议

6.1 性能优化技巧

  1. 批处理推理:同时处理多个请求提升吞吐量
batch_inputs = ["问题1", "问题2", "问题3"]
batch_outputs = llm.batch(batch_inputs)
  1. 缓存机制:减少重复计算
from langchain.cache import InMemoryCache
langchain.llm_cache = InMemoryCache()
  1. 量化压缩:降低显存占用
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    load_in_4bit=True,
    device_map="auto"
)

6.2 生产环境部署

推荐使用FastAPI构建服务接口:

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Request(BaseModel):
    input: str

@app.post("/chat")
async def chat(request: Request):
    response = chain.invoke({"input": request.input})
    return {"response": response}

启动服务:

uvicorn api:app --reload

7. 总结与下一步

通过本教程,您已经掌握了:

  • Phi-3.5-Mini-Instruct与LangChain的核心集成方法
  • 基础对话链和工具增强型Agent的构建
  • 多Agent协作和记忆管理的高级工作流
  • 生产环境部署和性能优化技巧

建议下一步探索:

  1. 接入更多工具(数据库、API等)
  2. 实现RAG(检索增强生成)工作流
  3. 开发自定义工具和Agent类型
  4. 监控和评估系统性能

获取更多AI镜像

想探索更多AI镜像和应用场景?访问 CSDN星图镜像广场,提供丰富的预置镜像,覆盖大模型推理、图像生成、视频生成、模型微调等多个领域,支持一键部署。

Logo

脑启社区是一个专注类脑智能领域的开发者社区。欢迎加入社区,共建类脑智能生态。社区为开发者提供了丰富的开源类脑工具软件、类脑算法模型及数据集、类脑知识库、类脑技术培训课程以及类脑应用案例等资源。

更多推荐