Skip to main content

快速入门

LangChain

安装

要安装LangChain,请运行:

 pip install langchain 

有关更多详细信息,请参阅我们的安装指南

环境设置

使用LangChain通常需要与一个或多个模型提供者、数据存储、API等进行集成。在本示例中,我们将使用OpenAI的模型API。

首先,我们需要安装他们的Python包:

pip install openai

访问API需要一个API密钥,你可以通过创建一个帐户并前往这里来获取。当我们获得了一个密钥之后,我们需要通过运行以下命令将其设置为环境变量:

export OPENAI_API_KEY="..."

如果你不想设置环境变量,你可以在初始化OpenAI LLM类时直接通过openai_api_key命名参数传递密钥:

from langchain.llms import OpenAI

llm = OpenAI(openai_api_key="...")

构建应用程序

现在我们可以开始构建语言模型应用程序了。LangChain提供了许多可以用来构建语言模型应用程序的模块。这些模块可以作为简单应用程序中的独立模块使用,也可以组合在一起用于更复杂的用例。

LangChain应用程序的核心构建模块是LLMChain。它结合了三个方面:

  • LLM: 语言模型是核心推理引擎。要使用LangChain,您需要了解不同类型的语言模型以及如何使用它们。
  • Prompt Templates: 提供语言模型的指令。这控制了语言模型的输出,因此了解如何构建提示和不同的提示策略至关重要。
  • Output Parsers: 将LLM的原始响应转换为更易处理的格式,使得在下游使用输出变得容易。

在本入门指南中,我们将逐个介绍这三个组件,然后介绍将它们组合在一起的LLMChain。了解这些概念将使您能够很好地使用和定制LangChain应用程序。大多数LangChain应用程序允许您配置LLM和/或使用的提示,因此了解如何利用这一点将是一个很好的帮助。

LLMs

LangChain中有两种类型的语言模型,称为:

  • LLMs: 这是一个以字符串作为输入并返回字符串的语言模型
  • ChatModels: 这是一个以消息列表作为输入并返回消息的语言模型

LLMs的输入/输出简单易懂 - 字符串。但是ChatModels呢?那里的输入是一个ChatMessage列表,输出是一个单独的ChatMessage。 一个ChatMessage具有两个必需的组件:

  • content: 这是消息的内容。
  • role: 这是ChatMessage来自的实体的角色。

LangChain提供了几个对象,用于方便地区分不同的角色:

  • HumanMessage: 来自人类/用户的ChatMessage
  • AIMessage: 来自AI/助手的ChatMessage
  • SystemMessage: 来自系统的ChatMessage
  • FunctionMessage: 来自函数调用的ChatMessage

如果这些角色都不合适,还可以使用ChatMessage类手动指定角色。有关如何最有效地使用这些不同的消息的更多信息,请参阅我们的提示指南。

LangChain为两者提供了一个标准接口,但了解这种差异以便为给定的语言模型构建提示非常有用。LangChain提供的标准接口有两种方法:

  • predict: 接受一个字符串,返回一个字符串
  • predict_messages: 接受一个消息列表,返回一个消息。

让我们看看如何使用这些不同类型的模型和不同类型的输入。首先,让我们导入LLM和ChatModel。

from langchain.llms import OpenAI
from langchain.chat_models import ChatOpenAI

llm = OpenAI()
chat_model = ChatOpenAI()

llm.predict("hi!")
>>> "Hi"

chat_model.predict("hi!")
>>> "Hi"

OpenAIChatOpenAI对象基本上只是配置对象。您可以使用诸如temperature等参数对其进行初始化,并将其传递给其他对象。

接下来,让我们使用predict方法对字符串输入进行处理。

text = "What would be a good company name for a company that makes colorful socks?"

llm.predict(text)
# >> Feetful of Fun

chat_model.predict(text)
# >> Socks O'Color

最后,让我们使用predict_messages方法对消息列表进行处理。

from langchain.schema import HumanMessage

text = "制造多彩袜子的公司的好名字是什么?"
messages = [HumanMessage(content=text)]

llm.predict_messages(messages)
# >> Feetful of Fun

chat_model.predict_messages(messages)
# >> Socks O'Color

对于这两种方法,您还可以将参数作为关键字参数传递。例如,您可以传入temperature=0来调整使用的温度,该温度将覆盖对象的配置。在运行时传入的任何值都将始终覆盖对象的配置。

提示模板

大多数LLM应用程序不会直接将用户输入传递到LLM中。通常,它们会将用户输入添加到一个更大的文本片段中,称为提示模板,该模板提供了有关特定任务的附加上下文。

在前面的示例中,我们传递给模型的文本包含了生成公司名称的指令。对于我们的应用程序,如果用户只需提供公司/产品的描述而无需担心给出模型指令,那将非常好。

PromptTemplates正是为此而设计的!它们将用户输入转化为完全格式化的提示的所有逻辑绑定在一起。这可以从非常简单的开始 - 例如,产生上述字符串的提示只需是

from langchain.prompts import PromptTemplate

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?

然而,使用这些而不是原始字符串格式化的优势有几个。您可以“部分”出变量 - 例如,您可以一次只格式化某些变量。您可以将它们组合在一起,轻松地将不同的模板组合成一个单独的提示。有关这些功能的说明,请参阅提示部分以获取更多详细信息。

PromptTemplates还可以用于生成消息列表。在这种情况下,提示不仅包含有关内容的信息,还包含每个消息(其角色、其在列表中的位置等) 在这里,最常见的是ChatPromptTemplate是ChatMessageTemplate的列表。每个ChatMessageTemplate包含了格式化该ChatMessage的指令 - 其角色,以及其内容。让我们在下面看一下这个:

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.")
]

除了ChatMessageTemplate之外,ChatPromptTemplates还可以包括其他内容 - 有关更多详细信息,请参阅提示部分

输出解析器

OutputParsers将LLM的原始输出转换为可以在下游使用的格式。输出解析器有几种主要类型,包括:

  • 将LLM的文本转换为结构化信息(例如JSON)
  • 将ChatMessage转换为字符串
  • 将除消息之外的其他信息(如OpenAI函数调用)转换为字符串。

有关此方面的详细信息,请参阅输出解析器部分

在本入门指南中,我们将编写自己的输出解析器 - 将逗号分隔的列表转换为列表。

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(", ")

CommaSeparatedListOutputParser().parse("hi, bye")
# >> ['hi', 'bye']

LLMChain

现在,我们可以将所有这些组合成一个链组件。这个链组件将接收输入变量,将其传递给提示模板以创建提示,将提示传递给LLM,然后通过一个(可选的)输出解析器将输出传递出去。这是一种方便地将模块化逻辑捆绑在一起的方式。让我们看看它的作用!

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应用程序的核心构建块 - LLMChains。在所有这些组件(LLMs、prompts、输出解析器)中,还有很多微妙之处,还有很多其他不同的组件需要了解。要继续您的学习之旅: