AI创想

标题: LangChain 使用教程(简单入门) [打印本页]

作者: yitiaocong    时间: 2025-9-7 23:38
标题: LangChain 使用教程(简单入门)
提示模板

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

适用场景
特点
  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

适用场景
特点
  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)
复制代码
结合记忆的多轮问答

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":"北京现在温度多少?"})
复制代码





欢迎光临 AI创想 (http://llms-ai.com/) Powered by Discuz! X3.4