LangChain 框架快速入门指南
安装 LangChain
要安装 LangChain,请运行以下命令:
LangChain 是一个用于构建语言模型应用程序的框架。本文介绍了 LangChain 的安装与环境设置,包括使用 pip 或 conda 安装以及配置 OpenAI API 密钥。核心内容涵盖语言模型(LLM 与 ChatModels)的区别、提示模板(Prompt Template)的使用、输出解析器(Output Parsers)的功能以及链(Chains)的组合方式。通过示例展示了如何利用这些组件构建自动生成公司名称、翻译及列表生成的应用流程。文章还补充了记忆(Memory)和代理(Agents)等进阶特性的概念与代码示例,帮助开发者全面理解 LangChain 的核心架构与应用场景。

要安装 LangChain,请运行以下命令:
Pip
pip install langchain
Conda
conda install langchain -c conda-forge
更多详情,请查看官方安装指南。
使用 LangChain 通常需要与一个或多个模型提供商、数据存储、API 等集成。对于这个例子,我们将使用 OpenAI 的模型 API。
首先,我们需要安装 OpenAI 的 Python 包:
pip install openai
访问 API 需要一个 API 密钥,您可以通过创建一个帐户并前往官网获取。获取 API 密钥后,我们可以通过运行以下命令将其设置为环境变量:
export OPENAI_API_KEY="your_api_key_here"
如果您不想设置环境变量,也可以通过在初始化 OpenAI LLM 类时的 openai_api_key 命名参数直接传入密钥:
from langchain.llms import OpenAI
llm = OpenAI(openai_api_key="your_api_key_here")
现在我们可以开始构建语言模型应用程序了。LangChain 提供了许多模块来构建语言模型应用程序。模块可以作为简单应用程序中的独立部分使用,也可以组合用于更复杂的用例。
LangChain 应用程序的核心构建块是 LLMChain。这结合了以下三个组件:
在本入门指南中,我们将分别介绍三个重要组件,即 LLM、提示和 LangChain。掌握这些概念将有助于您在使用和自定义 LangChain 应用程序时更加得心应手。值得注意的是,许多 LangChain 应用程序都允许您自定义 LLM 和/或使用提示,因此熟练掌握这些技巧将是成功应用 LangChain 的重要因素之一。
在 LangChain 中有两种语言模型,分别是大语言模型 LLMs 和聊天模型 ChatModels。
LangChain 的基本构建模块是 LLM,它将字符串作为输入并返回一个字符串。
from langchain.llms import OpenAI
而聊天模型是语言模型的变体。虽然聊天模型在底层使用语言模型,但它们暴露的接口有点不同:它们没有暴露'文本输入,文本输出'的 API,而是将聊天消息(ChatMessage)列表作为输入和输出。
您可以通过向聊天模型传递一个或多个消息来获取聊天补全,响应将是一个消息。LangChain 目前支持的消息类型有 AIMessage、HumanMessage、SystemMessage 和 ChatMessage - ChatMessage 接受一个任意的角色参数。大多数时候,您只需要处理 HumanMessage、AIMessage 和 SystemMessage。
from langchain.chat_models import ChatOpenAI
from langchain.schema import (
AIMessage,
HumanMessage,
SystemMessage
)
现在假设我们正在构建一个应用程序,可以根据公司的描述自动生成公司名称。为了让生成的公司名称更加随机,我们需要初始化模型封装器,并使用高温度的参数来进行初始化,这将确保我们生成的名称更具创造性和多样性。
llm = OpenAI(temperature=0.9)
chat = ChatOpenAI(temperature=0.9)
LangChain 为两者公开了一个标准接口,但了解这种差异以便为给定语言模型构造提示很有用。LangChain 公开的标准接口有两种方法:
predict:接受字符串,返回字符串。predict_messages:接收消息列表,返回消息。现在我们可以传入文本并获得预测了:
text = "What would be a good company name for a company that makes colorful socks?"
llm.predict(text)
# '\n\nLivelySox.'
chat.predict(text)
# 'VividSocks'
最后,让我们使用 predict_messages 该方法运行消息列表。
chat_messages = [HumanMessage(content="What would be a good company name for a company that makes colorful socks?")]
llm.predict_messages(chat_messages)
# AIMessage(content='\n\nFancyFeets', additional_kwargs={}, example=False)
chat.predict_messages(chat_messages)
# AIMessage(content='Rainbow Feet', additional_kwargs={}, example=False)
对于这两种方法,还可以将参数作为关键字参数传入。例如,您可以传入 temperature=0 以根据对象的配置调整使用的温度。在运行时传入的任何值都将始终覆盖对象配置的内容。
llm.predict(text=text, temperature=0)
# '\n\nRainbow Socks Co.'
chat.predict(text=text, temperature=0)
# 'VibrantSox'
llm.predict_messages(messages=chat_messages, temperature=0)
# AIMessage(content='\n\nSocktastic!', additional_kwargs={}, example=False)
chat.predict_messages(messages=chat_messages, temperature=0)
# AIMessage(content='VibrantSock Co.', additional_kwargs={}, example=False)
大多数 LLM 应用程序不会将用户输入直接传入 LLM。它们通常会将用户输入添加到一个更大的文本片段中,称为提示模板(Prompt Template),以提供有关特定任务的附加上下文。
在之前的示例中,我们传递给模型的文本包含生成公司名称的说明。对于我们的应用程序,最好的是用户只需要提供公司/产品的描述,而不必担心向模型提供说明。
提示模板捆绑了从用户输入到完全格式化的提示的所有逻辑,使用 PromptTemplate 非常容易:
from langchain.prompts import PromptTemplate
# prompt 模板
prompt = PromptTemplate.from_template("What is a good name for a company that makes {product}?")
# 通过模板变量渲染模板
prompt.format(product="colorful socks")
# 'What is a good name for a company that makes colorful socks?'
提示模板还可以用于生成消息列表。在这种情况下,提示不仅包含有关内容的信息,还包含每条消息在列表中的位置等信息。最常见的是聊天提示模板,它是一个聊天消息模板列表,每个模板都包含有关如何格式化该聊天消息的说明,包括其角色和内容。
您可以通过使用 MessagePromptTemplate 来利用模板。您可以从一个或多个 MessagePromptTemplate 构建一个 ChatPromptTemplate。您可以使用 ChatPromptTemplate 的 format_messages 方法来生成格式化的消息。
因为这是生成一系列消息,所以它比只生成一个字符串的正常提示模板稍微复杂一些。聊天提示模板还可以包括聊天消息模板以外的其他内容,在后续篇章中会详细讲解。
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
# 定义模板
template = "You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
# 设置模板变量值
chat_prompt.format_messages(input_language="English", output_language="French", text="I love programming.")
[
SystemMessage(content="You are a helpful assistant that translates English to French.", additional_kwargs={}),
HumanMessage(content="I love programming.")
]
输出解析器将 LLM 的原始输出转换为可以在下游使用的格式。输出分析器的主要类型很少,包括:
下面我们使用一个列表解析器作为例子,它可以将模型返回的文本解析成列表输出:
from langchain.output_parsers import CommaSeparatedListOutputParser
output_parser = CommaSeparatedListOutputParser()
format_instructions = output_parser.get_format_instructions()
prompt = PromptTemplate(
template="List 5 {subject}.\n{format_instructions}",
input_variables=["subject"],
partial_variables={"format_instructions": format_instructions}
)
model = OpenAI(temperature=0)
_input = prompt.format(subject="country names")
output = model(_input)
output_parser.parse(output)
# ['China', 'India', 'United States', 'Brazil', 'Japan']
现在我们已经有了一个模型和一个提示模板,我们将想要将两者组合起来。链(Chain)为我们提供了一种将 (或链式地) 多个基础模块 (如模型、提示和其他链) 链接起来的方式。
最简单也最常见的链类型是 LLMChain,它首先将输入传递给一个 PromptTemplate,然后传递给一个 LLM。我们可以从现有的模型和提示模板构造一个 LLM 链。
直接使用 llm 的例子:
llm.predict("What would be a good company name for a company that makes colorful socks?")
使用 LLMChain 的等价例子:
from langchain.chains import LLMChain
prompt = PromptTemplate.from_template("What is a good name for a company that makes {product}?")
chain = LLMChain(llm=llm, prompt=prompt)
chain.run("colorful socks")
# '\n\nBrightly Toed Socks.'
这是我们的第一个链,理解这个简单链的工作原理会很好地为使用更复杂的链做准备。
LLMChain 也可以与聊天模型一起使用:
from langchain import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
chat = ChatOpenAI(temperature=0)
template = "You are a helpful assistant that translates {input_language} to {output_language}."
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
chain = LLMChain(llm=chat, prompt=chat_prompt)
chain.run(input_language="English", output_language="French", text="I love programming.")
# "J'adore la programmation."
我们可以将语言模型、提示模板和输出解析器组合成一个流畅的链。该链首先接收输入变量,并将这些变量传递给提示模板以生成提示。然后,这些提示将被传递给语言模型进行分析和预测。最后,通过(可选)输出分析器,将输出结果传递给用户。这种模块化的链条结构使得这一流程更加高效和方便。
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.chains import LLMChain
from langchain.schema import BaseOutputParser
class CommaSeparatedListOutputParser(BaseOutputParser):
"""Parse the output of an LLM call to a comma-separated list."""
def parse(self, text: str):
"""Parse the output of an LLM call."""
return text.strip().split(", ")
template = """You are a helpful assistant who generates comma separated lists.
A user will pass in a category, and you should generate 5 objects in that category in a comma separated list.
ONLY return a comma separated list, and nothing more."""
system_message_prompt = SystemMessagePromptTemplate.from_template(template)
human_template = "{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
chain = LLMChain(
llm=ChatOpenAI(),
prompt=chat_prompt,
output_parser=CommaSeparatedListOutputParser()
)
chain.run("colors")
# >> ['red', 'blue', 'green', 'yellow', 'orange']
在实际应用中,简单的链往往不足以处理多轮对话或复杂任务。LangChain 提供了 Memory 和 Agents 机制来增强应用的能力。
记忆组件允许链记住之前的交互历史。这对于聊天机器人尤为重要,因为它可以基于之前的对话上下文进行回答。
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationChain
memory = ConversationBufferMemory()
conversation = ConversationChain(
llm=chat,
memory=memory,
verbose=True
)
conversation.predict(input="你好,我想买一双袜子。")
conversation.predict(input="什么颜色的?")
代理允许 LLM 自主决定调用哪些工具。结合 LangChain 的工具库,可以实现自动搜索、计算等功能。
from langchain.agents import initialize_agent, Tool
from langchain.utilities import GoogleSearchAPIWrapper
search = GoogleSearchAPIWrapper()
tools = [
Tool(
name="Search",
func=search.run,
description="useful for when you need to answer questions about current events"
)
]
agent = initialize_agent(tools, chat, agent="zero-shot-react-description", verbose=True)
agent.run("谁是美国现任总统?")
本文详细介绍了 LangChain 的安装与环境配置,重点讲解了构建语言模型应用的核心组件:语言模型、提示模板和输出解析器。通过代码示例展示了如何利用 LLMChain 将这些组件串联起来,实现从简单问答到结构化数据生成的多种功能。此外,还简要介绍了记忆和代理等进阶特性,为开发者构建更智能的应用提供了方向。掌握这些基础概念和模式,是开发高质量 AI 应用的关键第一步。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML转Markdown 互为补充。 在线工具,Markdown转HTML在线工具,online