侧边栏壁纸
博主头像
码森林博主等级

一起走进码森林,享受编程的乐趣,发现科技的魅力,创造智能的未来!

  • 累计撰写 146 篇文章
  • 累计创建 74 个标签
  • 累计收到 4 条评论

目 录CONTENT

文章目录
AI

拥抱 AI 时代:LangChain 框架快速入门指南

码森林
2023-08-24 / 0 评论 / 0 点赞 / 368 阅读 / 3,036 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2023-08-26,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

安装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="..."

如果您不想设置环境变量,也可以通过在初始化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的原始响应转换为更可行的格式,从而可以轻松使用下游的输出。

在本入门指南中,我们将分别介绍三个重要组件,即LLM、提示和LangChain。掌握这些概念将有助于您在使用和自定义LangChain应用程序时更加得心应手。值得注意的是,许多LangChain应用程序都允许您自定义LLM和/或使用提示,因此熟练掌握这些技巧将是成功应用LangChain的重要因素之一。

语言模型(Language Models)

在 LangChain 中有两种语言模型,分别是大语言模型LLMs 和聊天模型 ChatModels。

LangChain的基本构建模块是LLM,它将字符串作为输入并返回一个字符串。

from langchain.llms import OpenAI

而聊天模型是语言模型的变体。虽然聊天模型在底层使用语言模型,但它们暴露的接口有点不同:它们没有暴露“文本输入,文本输出”的API,而是将聊天消息(ChatMessage)列表作为输入和输出。

您可以通过向聊天模型传递一个或多个消息来获取聊天补全,响应将是一个消息。LangChain目前支持的消息类型有AIMessageHumanMessageSystemMessageChatMessage - ChatMessage接受一个任意的角色参数。大多数时候,您只需要处理HumanMessageAIMessageSystemMessage

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)

提示模板(Prompt Template)

大多数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。您可以使用ChatPromptTemplateformat_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.")
]

输出解析器(Output Parsers)

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

  • 将文本从LLM转换为结构化信息,如JSON、List、时间日期等。
  • 将聊天信息转换为字符串。
  • 将调用返回的额外信息转换为字符串,而不是消息(如 OpenAI 函数调用)。

下面我们使用一个列表解析器作为例子,它可以将模型返回的文本解析成列表输出:

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']

任务链(Chains)

现在我们已经有了一个模型和一个提示模板,我们将想要将两者组合起来。链(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安装和环境设置,包括可以通过运行pip、conda命令进行安装,以及 OpenAI的Python包和获取API密钥。

接下来,文章介绍了构建LangChain应用程序的核心构建块,包括LLM、提示模板和输出解析器。然后,文章介绍了两种语言模型:大语言模型和聊天模型,并给出了使用LangChain构建一个根据公司描述自动生成公司名称的示例。

同时,文章介绍了提示模板和输出解析器的概念,并给出了一些例子。

最后,介绍了LLM、提示模板和输出解析器组合成链例子。

现在我们已经掌握了如何创建 LangChain 应用程序的核心构建块 LLMChain,这是开发所有应用程序的基础。

理解新范式,拥抱新时代,把握新机会。

扫码_搜索联合传播样式-标准色版

0

评论区