1. LangChain 简介
LangChain 是一个用于开发基于语言模型(LM)的应用程序的框架。它支持创建以下类型的应用:
-
上下文感知(Context-aware):连接语言模型(LM)到上下文数据源(如提示指令、少样本示例、相关内容等)。
-
推理能力(Reasoning):依靠 LM 进行推理(根据提供的上下文决定如何回答、采取何种行动等)。
1.1 典型应用场景
-
文档问答(如法律、医学领域)
-
聊天机器人(如市场营销、HR 招聘)
-
结构化数据分析(如 SQL 查询、报告文档分析)
LangChain 主要包含以下三个核心组件:
-
LLM(大语言模型):作为核心推理引擎,理解和使用不同类型的 LM 是使用 LangChain 的基础。
-
Prompt Templates(提示模板):为 LM 提供指令,决定模型的输出。
-
Output Parsers(输出解析器):将 LLM 的原始响应转换为可用格式,方便后续使用。
2. 提示(Prompt)
提示(Prompt)是用户提供给语言模型的输入或指令,帮助其理解上下文并生成相关的语言输出。LangChain 提供了一些用于构建和处理提示的类和函数。
2.1 提示模板(Prompt Template)
提示模板是一种预定义的提示生成配方,包含 指令
、少样本示例
、特定上下文
以及 适用于特定任务的问题
。
from langchain.prompts import PromptTemplate
prompt_template = PromptTemplate(
input_variables=["adjective", "content"],
template="Tell me a {adjective} joke about {content}.",
)
print(prompt_template.format(adjective="funny", content="chickens"))
或者使用 from_template
方法(不需要显式定义 input_variables
):
prompt_template = PromptTemplate.from_template(
template="Tell me a {adjective} joke about {content}.",
)
print(prompt_template.format(adjective="funny", content="chickens"))
2.2 ChatPromptTemplate
聊天提示(ChatPromptTemplate)由一系列聊天消息组成,每条消息都有一个 role
(角色)。
在 OpenAI Chat API 中,常见的角色包括:
-
SystemMessage
:系统消息 -
AIMessage
:AI 生成的消息 -
HumanMessage
:用户输入的消息 -
FunctionMessage
:函数调用生成的消息
示例:
from langchain.prompts import ChatPromptTemplate
from langchain.schema.messages import SystemMessage, HumanMessagePromptTemplate
chat_template = ChatPromptTemplate.from_messages(
[
SystemMessage(content="""
You serve as the teacher assistant to Chaky, who instructs an NLP course.
Your primary responsibility is to assist students in successfully completing the NLP course.
"""),
HumanMessagePromptTemplate.from_template("{text}"),
]
)
messages = chat_template.format_messages(text="How to get an A if I fail every quiz?")
print(messages)
3. 附录
本篇博文介绍了 LangChain 的基本概念,以及如何使用提示模板(Prompt Templates)和聊天提示模板(ChatPromptTemplate)构建 NLP 应用。在接下来的文章中,我们将继续深入探讨 LangChain 其他核心模块的使用方法。
如果你觉得这篇博文对你有帮助,请点赞、收藏、关注我,并且可以打赏支持我!
欢迎关注我的后续博文,我将分享更多关于人工智能、自然语言处理和计算机视觉的精彩内容。
谢谢大家的支持!