个人随笔
目录
Agent学习(12):LangChain的简单使用
2026-02-10 22:09:09

LangChain 是一款专为构建大语言模型(LLM)应用设计的 Python/JavaScript 开源框架,核心目标是解决 “只用原生 LLM API 开发复杂应用太繁琐” 的问题,让开发者能快速把 LLM(比如 ChatGPT、文心一言、智谱清言等)和外部资源(数据、工具、知识库)结合起来,搭建智能对话、问答机器人、数据分析、自动化工作流等应用。

1、先安装环境

  1. conda create -n langchain python=3.11
  2. conda activate langchain
  3. pip install -U langchain
  4. pip install -U langchain-openai

2、一些简单的例子

  1. from langchain_openai import ChatOpenAI
  2. import os
  3. from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
  4. chatLLM = ChatOpenAI(
  5. api_key=os.getenv("DASHSCOPE_API_KEY"),
  6. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
  7. model="qwen-plus", # 此处以qwen-plus为例,您可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
  8. # other params...
  9. )
  10. #简单示例
  11. def test1():
  12. messages = [
  13. {"role": "system", "content": "You are a helpful assistant."},
  14. {"role": "user", "content": "你是谁?"}]
  15. response = chatLLM.invoke(messages)
  16. print(response)
  17. #多轮对话
  18. def test2():
  19. messages = [
  20. SystemMessage(content="你是聚客AI大模型课的课程助理。"),
  21. HumanMessage(content="我是聚客AI学员,我叫小聚。"),
  22. AIMessage(content="欢迎!"),
  23. HumanMessage(content="我是谁?")
  24. ]
  25. ret = chatLLM.invoke(messages)
  26. print(ret.content)
  27. #流式输出
  28. def test3():
  29. for token in chatLLM.stream("你是谁"):
  30. print(token.content, end="")
  31. # 程序入口:只有直接运行这个文件时,才执行游戏
  32. if __name__ == "__main__":
  33. test3()

3、模板格式限定相关的例子

  1. from langchain_core.prompts import PromptTemplate
  2. from langchain_openai import ChatOpenAI
  3. import os
  4. from pydantic import BaseModel, Field
  5. from langchain_core.prompts import (
  6. ChatPromptTemplate,
  7. HumanMessagePromptTemplate,
  8. SystemMessagePromptTemplate,
  9. )
  10. from langchain_core.output_parsers import JsonOutputParser
  11. from langchain_core.output_parsers import PydanticOutputParser
  12. chatLLM = ChatOpenAI(
  13. api_key=os.getenv("DASHSCOPE_API_KEY"),
  14. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
  15. model="qwen-plus", # 此处以qwen-plus为例,您可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
  16. # other params...
  17. )
  18. #模板替换
  19. def test1():
  20. template = PromptTemplate.from_template("给我讲个关于{subject}的笑话")
  21. print("===Template===")
  22. print(template)
  23. print("===Prompt===")
  24. print(template.format(subject='小明'))
  25. def test2():
  26. # 通过 Prompt 调用 LLM
  27. template = PromptTemplate.from_template("给我讲个关于{subject}的笑话")
  28. ret = chatLLM.invoke(template.format(subject='小明'))
  29. # 打印输出
  30. print(ret.content)
  31. def test3():
  32. template = ChatPromptTemplate.from_messages(
  33. [
  34. SystemMessagePromptTemplate.from_template("你是{product}的客服助手。你的名字叫{name}"),
  35. HumanMessagePromptTemplate.from_template("{query}")
  36. ]
  37. )
  38. prompt = template.format_messages(
  39. product="AI大模型课程",
  40. name="小林",
  41. query="你是谁"
  42. )
  43. print(prompt)
  44. ret = chatLLM.invoke(prompt)
  45. print(ret.content)
  46. #从文件中加载
  47. def test4():
  48. template = PromptTemplate.from_file("G:\\AI\\workspace\\vscode\\202602\\prompt.txt", encoding="utf-8")
  49. print("===Template===")
  50. print(template)
  51. print("===Prompt===")
  52. print(template.format(topic='黑色幽默'))
  53. # 定义你的输出对象
  54. class Date(BaseModel):
  55. year: int = Field(description="Year")
  56. month: int = Field(description="Month")
  57. day: int = Field(description="Day")
  58. era: str = Field(description="BC or AD")
  59. #结构化输出
  60. def test5():
  61. # 定义结构化输出的模型
  62. structured_llm = chatLLM.with_structured_output(Date)
  63. template = """提取用户输入中的日期。
  64. 用户输入:
  65. {query}"""
  66. prompt = PromptTemplate(
  67. template=template,
  68. )
  69. query = "2023年四月6日天气晴..."
  70. input_prompt = prompt.format_prompt(query=query)
  71. ret = structured_llm.invoke(input_prompt)
  72. print(ret)
  73. #输出指定格式的json
  74. def test6():
  75. json_schema = {
  76. "title": "Date",
  77. "description": "Formated date expression",
  78. "type": "object",
  79. "properties": {
  80. "year": {
  81. "type": "integer",
  82. "description": "year, YYYY",
  83. },
  84. "month": {
  85. "type": "integer",
  86. "description": "month, MM",
  87. },
  88. "day": {
  89. "type": "integer",
  90. "description": "day, DD",
  91. },
  92. "era": {
  93. "type": "string",
  94. "description": "BC or AD",
  95. },
  96. },
  97. }
  98. # 定义结构化输出的模型
  99. structured_llm = chatLLM.with_structured_output(json_schema)
  100. template = """提取用户输入中的日期。
  101. 用户输入:
  102. {query}"""
  103. prompt = PromptTemplate(
  104. template=template,
  105. )
  106. query = "2023年四月6日天气晴..."
  107. input_prompt = prompt.format_prompt(query=query)
  108. ret = structured_llm.invoke(input_prompt)
  109. print(ret)
  110. #JsonOutputParser指定输出格式
  111. def test7():
  112. parser = JsonOutputParser(pydantic_object=Date)
  113. prompt = PromptTemplate(
  114. template="提取用户输入中的日期。\n用户输入:{query}\n{format_instructions}",
  115. input_variables=["query"],
  116. partial_variables={"format_instructions": parser.get_format_instructions()},
  117. )
  118. query = "2023年四月6日天气晴..."
  119. input_prompt = prompt.format_prompt(query=query)
  120. output = chatLLM.invoke(input_prompt)
  121. print("原始输出:")
  122. print(output)
  123. print("解析后:")
  124. print(parser.invoke(output))
  125. #PydanticOutputParser指定输出格式
  126. def test8():
  127. parser = PydanticOutputParser(pydantic_object=Date)
  128. prompt = PromptTemplate(
  129. template="提取用户输入中的日期。\n用户输入:{query}\n{format_instructions}",
  130. input_variables=["query"],
  131. partial_variables={"format_instructions": parser.get_format_instructions()},
  132. )
  133. query = "2023年四月6日天气晴..."
  134. input_prompt = prompt.format_prompt(query=query)
  135. output = chatLLM.invoke(input_prompt)
  136. print("原始输出:")
  137. print(output)
  138. print("解析后:")
  139. print(parser.invoke(output))
  140. # 程序入口:只有直接运行这个文件时,才执行游戏
  141. if __name__ == "__main__":
  142. test8()

4、回调本地方法的一些例子

  1. from langchain_openai import ChatOpenAI
  2. from langchain_core.messages import HumanMessage
  3. import os
  4. import json
  5. from langchain_core.tools import tool
  6. @tool
  7. def add(a: int, b: int) -> int:
  8. """Add two integers.
  9. Args:
  10. a: First integer
  11. b: Second integer
  12. """
  13. return a + b
  14. @tool
  15. def multiply(a: float, b: float) -> float:
  16. """Multiply two integers.
  17. Args:
  18. a: First integer
  19. b: Second integer
  20. """
  21. return a * b
  22. chatLLM = ChatOpenAI(
  23. api_key=os.getenv("DASHSCOPE_API_KEY"),
  24. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
  25. model="qwen-plus", # 此处以qwen-plus为例,您可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
  26. # other params...
  27. )
  28. #简单示例
  29. def test1():
  30. llm_with_tools = chatLLM.bind_tools([add, multiply])
  31. query = "3.5的4倍是多少?"
  32. messages = [HumanMessage(query)]
  33. output = llm_with_tools.invoke(messages)
  34. print(output)
  35. print("\n")
  36. print(json.dumps(output.tool_calls, indent=4))
  37. # 程序入口:只有直接运行这个文件时,才执行游戏
  38. if __name__ == "__main__":
  39. test1()

5、LCEL流式调用的一些例子

LCEL(LangChain Expression Language)是 LangChain 推出的声明式链式编程语法,核心目标是让开发者用极简的代码,把 LangChain 的各种组件(比如提示词、LLM、输出解析器)拼接成可执行的 “链”,而且自带异步、批处理、缓存等能力,不用自己写复杂的拼接逻辑。
可以把 LCEL 理解为:专门为 LangChain 组件设计的 “管道语法” —— 就像把不同功能的水管接在一起,数据从一端流入,经过各个组件处理后从另一端流出。

  1. from langchain_core.prompts import ChatPromptTemplate
  2. from langchain_core.output_parsers import StrOutputParser
  3. from langchain_core.runnables import RunnablePassthrough
  4. from pydantic import BaseModel, Field
  5. from typing import List, Dict, Optional
  6. from enum import Enum
  7. from langchain_openai import ChatOpenAI
  8. import json
  9. import os
  10. from langchain.chat_models import init_chat_model
  11. # 输出结构
  12. class SortEnum(str, Enum):
  13. data = 'data'
  14. price = 'price'
  15. class OrderingEnum(str, Enum):
  16. ascend = 'ascend'
  17. descend = 'descend'
  18. class Semantics(BaseModel):
  19. name: Optional[str] = Field(description="流量包名称", default=None)
  20. price_lower: Optional[int] = Field(description="价格下限", default=None)
  21. price_upper: Optional[int] = Field(description="价格上限", default=None)
  22. data_lower: Optional[int] = Field(description="流量下限", default=None)
  23. data_upper: Optional[int] = Field(description="流量上限", default=None)
  24. sort_by: Optional[SortEnum] = Field(description="按价格或流量排序", default=None)
  25. ordering: Optional[OrderingEnum] = Field(
  26. description="升序或降序排列", default=None)
  27. # Prompt 模板
  28. prompt = ChatPromptTemplate.from_messages(
  29. [
  30. ("system", "你是一个语义解析器。你的任务是将用户的输入解析成JSON表示。不要回答用户的问题。"),
  31. ("human", "{text}"),
  32. ]
  33. )
  34. # 模型
  35. llm = ChatOpenAI(
  36. api_key=os.getenv("DASHSCOPE_API_KEY"),
  37. base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
  38. model="qwen-plus", # 此处以qwen-plus为例,您可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models
  39. # other params...
  40. )
  41. structured_llm = llm.with_structured_output(Semantics)
  42. # LCEL 表达式
  43. runnable = (
  44. {"text": RunnablePassthrough()} | prompt | structured_llm
  45. )
  46. # 直接运行
  47. ret = runnable.invoke("不超过100元的流量大的套餐有哪些")
  48. print(
  49. json.dumps(
  50. ret.model_dump(),
  51. indent = 4,
  52. ensure_ascii=False
  53. )
  54. )

6、LangChain 与 LlamaIndex 的错位竞争

  • LangChain 侧重与 LLM 本身交互的封装
    • Prompt、LLM、Message、OutputParser 等工具丰富
    • 在数据处理和 RAG 方面提供的工具相对粗糙
    • 主打 LCEL 流程封装
    • 配套 Agent、LangGraph 等智能体与工作流工具
    • 另有 LangServe 部署工具和 LangSmith 监控调试工具
  • LlamaIndex 侧重与数据交互的封装
    • 数据加载、切割、索引、检索、排序等相关工具丰富
    • Prompt、LLM 等底层封装相对单薄
    • 配套实现 RAG 相关工具
    • 同样配套智能体与工作流工具
    • 提供 LlamaDeploy 部署工具,通过与三方合作提供过程监控调试工具
 2

啊!这个可能是世界上最丑的留言输入框功能~


当然,也是最丑的留言列表

有疑问发邮件到 : suibibk@qq.com 侵权立删
Copyright : 个人随笔   备案号 : 粤ICP备18099399号-2