[LangChain]简介&快速入门

⭐作者介绍:大二本科网络工程专业在读,持续学习Java,努力输出优质文章
⭐作者主页:@逐梦苍穹
⭐所属专栏:人工智能

1、简介

LangChain 是一个基于语言模型开发应用程序的框架。它可以实现以下功能:
● 数据感知:将语言模型与其他数据源连接起来
● 主动性:允许语言模型与其环境进行交互
LangChain 的主要价值在于:

  1. 组件:用于处理语言模型的抽象,以及每个抽象的一系列实现。无论您是否使用 LangChain 框架的其他部分,组件都是模块化且易于使用的
  2. 现成的链式组装:用于完成特定高级任务的结构化组件组装
    现成的链式组装使得入门变得很容易。对于更复杂的应用程序和细致入微的用例,组件可以轻松自定义现有的链式组装或构建新的链式组装。

2、快速入门

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

2.1、LLMs

从语言模型获取预测结果:
LangChain的基本构建模块是LLM,它接受文本并生成更多的文本。
例如,假设我们正在构建一个根据公司描述生成公司名称的应用程序。为了做到这一点,我们需要初始化一个OpenAI模型封装器。在这种情况下,由于我们希望输出更随机,我们将使用较高的温度来初始化我们的模型。

现在我们可以传入文本并获得预测结果了!
在这里插入图片描述

2.2、聊天模型

聊天模型是语言模型的一种变体。
虽然聊天模型在内部使用语言模型,但其公开的接口略有不同:它们不是提供“文本输入,文本输出”的API,而是提供了一个“聊天消息”作为输入和输出的接口。
您可以通过将一个或多个消息传递给聊天模型来获取聊天补全。响应将是一条消息。
LangChain当前支持的消息类型有AIMessage、HumanMessage、SystemMessage和ChatMessage – ChatMessage接受一个任意的角色参数。
大多数情况下,只需要处理HumanMessage、AIMessage和SystemMessage。

from langchain.chat_models import ChatOpenAI
from langchain.schema import (
    AIMessage,
    HumanMessage,
    SystemMessage
)

chat = ChatOpenAI(temperature=0)
chat.predict_messages([HumanMessage(content="Translate this sentence from English to French. I love programming.")])
# >> AIMessage(content="J'aime programmer.", additional_kwargs={})
from langchain.chat_models import ChatOpenAI
from langchain.schema import HumanMessage,SystemMessage,AIMessage
chat = ChatOpenAI(temperature=.7,openai_api_key = openai_api_key)
chat(
    [
        SystemMessage(content="你是一个很棒的粤菜点餐的人工智能机器人,可以帮助用户在一个简短的句子中弄清楚该吃什么"),
        HumanMessage(content="我喜欢西红柿,我应该吃什么?")
    ]
)
chat(
    [
        SystemMessage(content="你是一个很好的 AI 机器人,可以帮助用户在一个简短的句子中找出去哪里旅行"),
        HumanMessage(content="我喜欢海滩,我应该去哪里?"),
        AIMessage(content="你应该去广东深圳"),
        HumanMessage(content="当我在那里时我还应该做什么?")
    ]
)

在这里插入图片描述

了解聊天模型与普通LLM的区别是有用的,但有时候能够将它们视为相同也很方便。 LangChain通过还提供了一个接口,通过该接口您可以像操作普通LLM一样与聊天模型进行交互。 您可以通过predict接口进行访问。

chat.predict("Translate this sentence from English to French. I love programming.")
>> J'aime programmer

2.3、提示模板

大多数LLM应用程序不会直接将用户输入传递给LLM。通常,它们会将用户输入添加到一个更大的文本片段中,称为提示模板,在特定任务上提供额外的上下文。
在前面的示例中,我们传递给模型的文本包含了生成公司名称的指令。对于我们的应用程序来说,如果用户只需要提供公司/产品的描述,而不必担心给模型提供指令,那就太好了。
LLMs:
使用PromptTemplates非常简单!在这种情况下,我们的模板将非常简单:
首先,我们需要安装他们的Python包: 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”)
Chat Models:
与LLMs类似,您可以使用MessagePromptTemplate来使用模板。您可以从一个或多个MessagePromptTemplate构建一个ChatPromptTemplate。您可以使用ChatPromptTemplate的format_messages方法来生成格式化的消息。
因为这是生成消息列表,所以它比普通的提示模板稍微复杂一些,普通的提示模板只生成一个字符串。请参阅有关提示的详细指南,了解此处可用的更多选项。
首先,我们需要安装他们的Python包: from langchain.prompts.chat import ( ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, ) 访问API需要一个API密钥。
在初始化OpenAI LLM类时直接通过 openai_api_key 命名参数传递密钥:
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.")
]

2.4、链

现在,我们已经有了一个模型和一个提示模板,我们将希望将两者结合起来。链提供了一种将多个原语(如模型、提示和其他链)链接(或链)在一起的方法。
LLMs:
最简单、最常见的链类型是LLMChain,它首先将输入传递给PromptTemplate,然后再传递给LLM。我们可以从现有的模型和提示模板构建一个LLM链。
使用这个我们可以替换

llm.predict("What would be a good company name for a company that makes colorful socks?")

from langchain.chains import LLMChain

chain = LLMChain(llm=llm, prompt=prompt)
chain.run("colorful socks")
Feetful of Fun

这就是我们的第一个链!理解这个简单链的工作原理将为您处理更复杂的链提供良好的基础。

Chat Models:
from langchain import LLMChain
要安装LangChain,请运行:
from langchain.prompts.chat import ( import Tabs from ‘@theme/Tabs’; import TabItem from ‘@theme/TabItem’; import CodeBlock from “@theme/CodeBlock”; )
pip install langchain
conda install langchain -c conda-forge
这将安装LangChain的最低要求。

2.5、代理

我们的第一个链运行了一个预定的步骤序列。为了处理复杂的工作流程,我们需要能够根据输入动态选择操作。
代理正是这样做的:它们使用语言模型来确定要采取的动作及其顺序。代理可以访问工具,并反复选择工具、运行工具并观察输出,直到得出最终答案。
要加载一个代理,您需要选择一个:
● LLM/Chat模型:为代理提供动力的语言模型。
● 工具:执行特定任务的函数。这可以是诸如:Google搜索、数据库查找、Python REPL、其他链等。有关预定义工具及其规范的列表,请参阅工具文档
● 代理名称:一个字符串,用于引用支持的代理类。代理类主要由语言模型用于确定要采取的动作的提示参数化。因为本笔记本专注于最简单、最高级别的API,所以这只涵盖了使用标准支持的代理的情况。如果您想实现自定义代理,请参阅这里。有关支持的代理及其规范的列表,请参阅这里
在本示例中,我们将使用SerpAPI来查询搜索引擎。
您需要安装SerpAPI Python包:
pip install google-search-results
并设置SERPAPI_API_KEY环境变量。

2.6、内存

到目前为止,我们所看到的链和代理都是无状态的,但对于许多应用程序来说,引用过去的交互是必要的。一个明显的例子是聊天机器人,你希望它能够在过去的消息上下文中理解新的消息。
内存模块提供了一种维护应用程序状态的方法。基本的内存接口很简单:它允许您根据最新的运行输入和输出更新状态,并使用存储的状态修改(或上下文化)下一个输入。
有许多内置的内存系统。其中最简单的是缓冲内存,它只是将最近的几个输入/输出添加到当前输入的前面 - 我们将在下面的示例中使用它。
LLMs:

from langchain import OpenAI, ConversationChain

llm = OpenAI(temperature=0)
conversation = ConversationChain(llm=llm, verbose=True)

conversation.run("Hi there!")

这是在引擎盖下面发生的事情:

Entering new chain…
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: Hi there!
AI:
Finished chain.
‘Hello! How are you today?’

现在,如果我们再次运行这个链:

conversation.run("I'm doing well! Just having a conversation with an AI.")

我们会看到传递给模型的完整提示包含了我们第一次交互的输入和输出,以及我们最新的输入:

Entering new chain…
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: Hi there!
AI: Hello! How are you today?
Human: I’m doing well! Just having a conversation with an AI.
AI:
Finished chain.
“That’s great! What would you like to talk about?”

Chat models:
您可以将内存与使用聊天模型初始化的链和代理一起使用。与用于LLM的内存不同之处在于,我们可以将它们保留为自己独特的内存对象,而不是尝试将所有先前的消息压缩成一个字符串。

from langchain.prompts import (
    ChatPromptTemplate,
    MessagesPlaceholder,
    SystemMessagePromptTemplate,
    HumanMessagePromptTemplate
现在我们可以传入文本并获得预测结果了!
from langchain.chains import ConversationChain
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory

prompt = ChatPromptTemplate.from_messages([
    SystemMessagePromptTemplate.from_template(
        "The following is a friendly conversation between a human and an AI. The AI is talkative and "
        "provides lots of specific details from its context. If the AI does not know the answer to a "
        "question, it truthfully says it does not know."
    ),
    MessagesPlaceholder(variable_name="history"),
    HumanMessagePromptTemplate.from_template("{input}")
])

llm = ChatOpenAI(temperature=0)
memory = ConversationBufferMemory(return_messages=True)
conversation = ConversationChain(memory=memory, prompt=prompt, llm=llm)

conversation.predict(input="Hi there!")

Hello! How can I assist you today?

conversation.predict(input="I'm doing well! Just having a conversation with an AI.")

That sounds like fun! I’m happy to chat with you. Is there anything specific you’d like to talk about?

conversation.predict(input="Tell me about yourself.")

猜你喜欢

转载自blog.csdn.net/qq_60735796/article/details/131505284