开启左侧

LangChain 使用教程(简单入门)

[复制链接]
yitiaocong 发表于 2025-9-7 23:38:07 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题
提示模板

langchain hub prompt

可以从 langchain hub 拉去适合的模板来构成 prompt,例如 ReAct Agent,在下文中也提到了
Langchain hub 链接:https://blog.langchain.ac.cn/langchain-prompt-hub/,可以下载别人的 prompt,也可以管理自己的 prompt
  1. from langchain import hub
  2. prompt = hub.pull("hwchase17/react")
复制代码
PromptTemplate

适用场景
    普通文本提示:适用于非对话式模型(如文本生成模型)单一文本输入:将用户输入和模板直接拼接为字符串简单场景:不需要区分系统、用户、AI 消息角色的场景
特点
    生成纯文本提示通过 {} 定义变量插值输出格式为字符串
  1. from langchain_core.prompts import PromptTemplate
  2. # 定义模板
  3. template ="""你是一个翻译助手,将中文翻译成英文。
  4. 输入内容:{text}
  5. 翻译结果:"""# 创建 prompt
  6. prompt = PromptTemplate.from_template(template)# 格式化输入
  7. formatted_prompt = prompt_template.format(text="你好,世界!")# 输出 formatted_prompt:"""
  8. 你是一个翻译助手,将中文翻译成英文。
  9. 输入内容:你好,世界!
  10. 翻译结果:
  11. """
复制代码
ChatPromptTemplate

适用场景
    对话式模型:专为聊天模型(如 ChatGPT、Qwen 等)设计多角色消息:需要区分系统指令、用户输入、AI 回复的场景复杂对话:需要动态插入对话历史的场景
特点
    生成结构化消息列表支持角色标签(system, human, ai)输出格式为 ChatMessage 对象列表
  1. from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
  2. from langchain_core.messages import HumanMessage, SystemMessage
  3. # 创建 prompt(包含系统指令和动态历史)
  4. prompt = ChatPromptTemplate.from_messages([
  5.     SystemMessage(content="你是一个专业翻译助手,当前时间:{time}"),
  6.     MessagesPlaceholder(variable_name="chat_history"),# 动态注入历史
  7.     HumanMessage(content="翻译这句话:{input}")])# 格式化输入(模拟对话历史)
  8. formatted_messages = prompt.format_messages(
  9.     time="2024-01-01 10:00",
  10.     chat_history=[
  11.         HumanMessage(content="你好!"),
  12.         AIMessage(content="Hello!")],input="今天天气很好")# 输出 formatted_prompt:"""
  13. [
  14.     SystemMessage(content='你是一个专业翻译助手,当前时间:2024-01-01 10:00'),
  15.     HumanMessage(content='你好!'),
  16.     AIMessage(content='Hello!'),
  17.     HumanMessage(content='翻译这句话:今天天气很好')
  18. ]
  19. """
复制代码
普通 Chain

LLMChain
  1. # 注意:LangChainDeprecationWarning: The class `LLMChain` was deprecated in LangChain 0.1.17 and will be removed in 1.0. Use :meth:`~RunnableSequence, e.g., `prompt | llm`` instead.from langchain.chains import LLMChain
  2. # 支持的功能示例
  3. chain = LLMChain(
  4.     llm=llm,
  5.     prompt=prompt,
  6.     memory=memory,# 内置记忆管理
  7.     output_key="result",# 自定义输出字段名
  8.     verbose=True,# 开启详细日志
  9.     callbacks=[handler],# 回调系统.....)
复制代码
一轮问答

prompt 构造:prompt & json output parser
  1. from langchain.prompts import PromptTemplate
  2. from langchain_core.output_parsers import JsonOutputParser
  3. # 输出 json 格式(对应 partial_variables,如果不需要约束去掉就好了 )
  4. json_schema ={"type":"object","properties":{"answer":{"type":"array","items":{"type":"string"}},"reason":{"type":"array","items":{"type":"string"}}},"required":["answer","reason"]}# 输出约束器
  5. output_parser = JsonOutputParser(json_schema=json_schema)# 提示模板
  6. prompt = PromptTemplate(
  7.     template ='''
  8. Please strictly follow this format in your response, the JSON format should be:
  9. {json_schema}
  10. Example:
  11. {{
  12.         "answer": {"我的回答是..."},
  13.         "reason": {"我这样回答的的原因是..."}
  14. }}
  15. User's input: {input1}, {input2}
  16. Answer:
  17. ''',
  18.     input_variables=["input1","input2"],# 用户输入, 可变
  19.     partial_variables={"json_schema": output_parser.get_format_instructions()}# 直接在prompt模板初始化时候需要固定, 不可变)
复制代码
输入数据:
  1. input_data ={"input1": user_input1,"input2": user_input2,}
复制代码
LLM 构造:
  1. from langchain_openai import ChatOpenAI
  2. llm = ChatOpenAI(
  3.     model="",
  4.     openai_api_key="",
  5.     openai_api_base="")
复制代码
链条构造:chain
  1. # 方案1:管道式
  2. chain = prompt | llm | output_parser
  3. response = chain.invoke(input_data)# 方案2:LLMChainfrom langchain.chains import LLMChain
  4. chain = LLMChain(llm=llm, prompt=prompt, output_parser=output_parser, verbose=True)
复制代码
结合记忆的多轮问答


  • 短期记忆,内存存储ConversationBufferMemory(适合开发环境),需要使用ChatPromptTemplate
    1. from langchain.memory import ConversationBufferMemory
    2. from langchain_community.chat_message_histories import ChatMessageHistory
    3. from langchain_core.runnables import RunnablePassthrough
    4. from langchain_core.runnables.history import RunnableWithMessageHistory
    5. from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
    6. from langchain_openai import ChatOpenAI
    7. import datetime
    复制代码
    管理 memory
    1. # 创建支持多会话的存储字典
    2. store ={}defget_session_history(session_id:str)-> ChatMessageHistory:if session_id notin store:
    3.         store[session_id]= ChatMessageHistory()return store[session_id]# 初始化基础内存(可选,根据实际需求)【关键】
    4. memory = ConversationBufferMemory(
    5.     return_messages=True,
    6.     memory_key="chat_history")# 提示词模板 chat_history 对应 memory_key【关键】
    7. prompt = ChatPromptTemplate.from_messages([("system","你是一个专业助手,当前时间:{{time}}"),
    8.     MessagesPlaceholder(variable_name="chat_history"),("human","{input}")])
    复制代码
    链条构造
    1. # 基础链配置
    2. base_chain =(
    3.     RunnablePassthrough.assign(
    4.         chat_history=lambda x: x["chat_history"],# 直接从输入中获取历史
    5.         time=lambda_: datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))| prompt
    6.     | llm
    7. )# 最终链(正确配置多会话历史)
    8. chain = RunnableWithMessageHistory(
    9.     base_chain,
    10.     get_session_history,# 使用会话历史获取函数
    11.     input_messages_key="input",
    12.     history_messages_key="chat_history")# 第一轮调用
    13. response1 = chain.invoke({"input":"什么是量子叠加态?"},
    14.     config={"configurable":{"session_id":"user_123"}})print(response1)# 第二轮调用(自动携带历史)
    15. response2 = chain.invoke({"input":"它与经典叠加有何不同?"},
    16.     config={"configurable":{"session_id":"user_123"}})print(response2.content)
    复制代码
Agent

ReAct Agent

导入包
  1. from langchain.agents import AgentExecutor, create_react_agent
  2. from langchain_core.prompts import PromptTemplate
复制代码
prompt 构造
  1. template ='''
  2. You are an assistant that strictly adheres to the required format. All outputs must follow the specified format and should not include any additional explanations or descriptions.
  3. Answer the following questions as best you can. You have access to the following tools:
  4. {tools}
  5. Use the following format:
  6. Question: the input question you must answer
  7. Thought: you should always think about what to do
  8. Action: the action to take, should be one of [{tool_names}]
  9. Action Input: the input to the action
  10. Observation: the result of the action
  11. ... (this Thought/Action/Action Input/Observation can repeat N times)
  12. Thought: I now know the final answer
  13. Final Answer: the final answer to the original input question
  14. Begin!
  15. Question: {input}
  16. Thought:{agent_scratchpad}'''# from_template创造简洁的模板,或者 langchain hub 拉取
  17. prompt = PromptTemplate.from_template(template)# prompt = hub.pull("hwchase17/react")
复制代码
AgentExecutor 构造
  1. tools =[]# 空的工具列表
  2. agent = create_react_agent(llm, tools=tools, prompt=prompt)# 创建 react 代理
  3. agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)# 创建代理执行器,传递空工具列表
复制代码
AgentExecutor 调用
  1. # 形式1
  2. result = agent_executor.invoke({"input":"你是谁?你可以干什么?","chat_history":"",})# 形式2
  3. result = agent_executor.invoke({"input":"你是谁?你可以干什么?"})# 形式.....
复制代码
Planning Agent
  1. # 将复杂任务分解为可执行的子任务序列,通过工作流引擎协调多步骤执行。典型代表如 HuggingGPT,可将"生成营销方案"分解为市场分析→竞品研究→创意生成→预算分配等子任务。
  2. planning_steps =[{"step":"market_analysis","tool":"google_trends"},{"step":"competitor_research","tool":"similarweb"},{"step":"content_generation","tool":"gpt4"}]
  3. agent = create_planning_agent(
  4.     llm = llm,
  5.     workflow = planning_steps,
  6.     fallback_strategy ="human_intervention"# 异常处理策略)
复制代码
Tools 使用

简单方法: @tool 装饰器

工具定义
  1. from langchain.tools import tool
  2. from typing import Optional
  3. # 工具1:@tool(name="温度查询工具", description="输入地点名称,返回该地当前温度")defget_temperature(location:str)->str:...return"5℃"# 工具2:@tooldeftext_length(text:str)->int:"""计算输入文本的字符长度。输入应为文本内容。"""returnlen(text)# 注意
  4. 已使用 @tool 装饰器 → 无需再调用 Tool() 手动创建实例,直接引用函数即可
  5. from langchain.tools import tool
  6. textLen_tool = Tool(name="text_length", func=text_length, description="计算输入文本的字符长度"# 测试调用
  7. temperature = get_temperature("北京")
复制代码
Agent 工具使用
  1. tools =[get_temperature, text_length]
  2. agent = create_react_agent(llm, tools=tools, prompt=prompt)
  3. agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)
  4. result = agent_executor.invoke({"input":"北京现在温度多少?"})
复制代码
高级实现: BaseTool 子类化
  1. from langchain.tools import BaseTool
  2. from pydantic import BaseModel, Field
  3. # 步骤1:定义输入参数schema(支持参数验证)classWeatherQueryInput(BaseModel):
  4.     location:str= Field(..., description="需要查询天气的城市名称,如:北京")
  5.     date:str= Field(default="今天", description="查询日期,默认为今天")# 步骤2:继承BaseTool创建工具类classGetWeatherTool(BaseTool):
  6.     name:str="weather_query"
  7.     description:str="根据城市名称和日期查询天气信息"# doc_string 明确需求
  8.     args_schema: Type[BaseModel]= WeatherQueryInput  # 绑定输入schemadef_run(self, location:str, date:str="今天")->str:# doc_string, 明确工具执行逻辑"""
  9.         调用天气API并返回结构化结果(此处简化逻辑)
  10.         参数示例:
  11.             location="北京", date="明天" → 返回"北京明天晴,气温20℃~28℃"
  12.         """# 模拟数据(实际开发需替换为真实API)
  13.         mock_data ={("北京","今天"):"晴,25℃",("北京","明天"):"多云,23℃~28℃",("上海","今天"):"小雨,20℃"}return mock_data.get((location, date),"暂未获取该城市天气信息")# 步骤3:工具初始化与使用
  14. weather_tool = GetWeatherTool()# 测试调用(自动验证参数类型)print(weather_tool.run({"location":"上海","date":"今天"}))# 输出:小雨,20℃
复制代码
Agent 工具使用
  1. tools =[weather_tool]# 或 tools = [GetWeatherTool()]
  2. agent = create_react_agent(llm, tools=tools, prompt=prompt)
  3. agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, handle_parsing_errors=True)
  4. result = agent_executor.invoke({"input":"北京现在温度多少?"})
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

发布主题
阅读排行更多+

Powered by Discuz! X3.4© 2001-2013 Discuz Team.( 京ICP备17022993号-3 )