LangChain中文手册之快速入门指南

快速入门指南

本教程让您快速了解如何使用 LangChain 构建端到端语言模型应用程序。

安装

首先,使用以下命令安装 LangChain:

pip install langchain
# or
conda install langchain -c conda-forge

环境设置

使用 LangChain 通常需要与一个或多个模型提供者、数据存储、api 等集成。

对于这个例子,我们将使用 OpenAI 的 API,所以我们首先需要安装他们的 SDK:

pip install openai

然后我们需要在终端中设置环境变量。

export OPENAI_API_KEY="..."

或者,您可以从 Jupyter notebook(或 Python 脚本)中执行此操作:

import os
os.environ["OPENAI_API_KEY"] = "..."

如果要动态设置 API 密钥,可以在启动 OpenAI 类时使用 openai_api_key 参数——例如,每个用户的 API 密钥。

from langchain.llms import OpenAI
llm = OpenAI(openai_api_key="OPENAI_API_KEY")

构建语言模型应用程序:LLM

现在我们已经安装了 LangChain 并设置了我们的环境,我们可以开始构建我们的语言模型应用程序了。

LangChain 提供了很多可以用来构建语言模型应用的模块。模块可以组合起来创建更复杂的应用程序,或者单独用于简单的应用程序。

LLM:从语言模型中获取预测

LangChain 最基本的构建块是在某些输入上调用 LLM。让我们通过一个简单的例子来说明如何做到这一点。为此,假设我们正在构建一项服务,该服务会根据公司的产品生成公司名称。

为此,我们首先需要导入 LLM 包装器。

from langchain.llms import OpenAI

然后我们可以用任何参数初始化包装器。在此示例中,我们可能希望输出更加随机,因此我们将使用高温对其进行初始化。

llm = OpenAI(temperature=0.9)

我们现在可以根据一些输入调用它!

text = "What would be a good company name for a company that makes colorful socks?"
print(llm(text))
Feetful of Fun

有关如何在 LangChain 中使用 LLM 的更多详细信息,请参阅LLM 入门指南。

提示模板:管理 LLM 的提示

申请 LLM 是重要的第一步,但这仅仅是个开始。通常,当您在应用程序中使用 LLM 时,您不会将用户输入直接发送到 LLM。相反,您可能正在接受用户输入并构建提示,然后将其发送给 LLM。

例如,在前面的示例中,我们传入的文本被硬编码为要求一家生产彩色袜子的公司的名称。在这个假想的服务中,我们想要做的是只接受描述公司所做的用户输入,然后用该信息格式化提示。

使用 LangChain 很容易做到这一点!

首先让我们定义提示模板:

from langchain.prompts import PromptTemplate

prompt = PromptTemplate(
    input_variables=["product"],
    template="What is a good name for a company that makes {product}?",
)

现在让我们看看这是如何工作的!我们可以调用该.format方法对其进行格式化。

print(prompt.format(product="colorful socks"))
What is a good name for a company that makes colorful socks?

有关更多详细信息,请查看入门指南以获取提示。

Chains:在多步骤工作流程中结合 LLM 和提示

到目前为止,我们一直在单独使用 PromptTemplate 和 LLM 原语。但是,当然,真正的应用程序不仅仅是一个原语,而是它们的组合。

LangChain 中的一条链由链接组成,链接可以是像 LLM 这样的原始链,也可以是其他链。

最核心的链类型是 LLMChain,它由 PromptTemplate 和 LLM 组成。

扩展前面的示例,我们可以构建一个 LLMChain,它接受用户输入,使用 PromptTemplate 对其进行格式化,然后将格式化的响应传递给 LLM。

from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI

llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
    input_variables=["product"],
    template="What is a good name for a company that makes {product}?",
)

我们现在可以创建一个非常简单的链,它将接受用户输入,用它格式化提示,然后将它发送到 LLM:

from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)

现在我们可以仅指定产品来运行该链!

chain.run("colorful socks")
# -> '

Socktastic!'

我们开始了!这是第一个链 - LLM 链。这是一种较简单的链类型,但了解它的工作原理将为您处理更复杂的链做好准备。

有关更多详细信息,请查看链的入门指南。

代理:基于用户输入的动态调用链

到目前为止,我们所看到的链条以预定的顺序运行。

代理人不再这样做:他们使用 LLM 来确定采取哪些行动以及采取何种顺序。动作可以是使用工具并观察其输出,也可以是返回给用户。

如果使用得当,代理可以非常强大。在本教程中,我们将向您展示如何通过最简单、最高级别的 API 轻松使用代理。

为了加载代理,您应该了解以下概念:

代理:有关受支持代理及其规范的列表,请参见此处。

工具:有关预定义工具及其规范的列表,请参见此处。

对于此示例,您还需要安装 SerpAPI Python 包。

pip install google-search-results

并设置相应的环境变量。

import os
os.environ["SERPAPI_API_KEY"] = "..."

现在我们可以开始了!

from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI

# First, let's load the language model we're going to use to control the agent.
llm = OpenAI(temperature=0)

# Next, let's load some tools to use. Note that the `llm-math` tool uses an LLM, so we need to pass that in.
tools = load_tools(["serpapi", "llm-math"], llm=llm)


# Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

# Now let's test it out!
agent.run("What was the high temperature in SF yesterday in Fahrenheit? What is that number raised to the .023 power?")
> Entering new AgentExecutor chain...
 I need to find the temperature first, then use the calculator to raise it to the .023 power.
Action: Search
Action Input: "High temperature in SF yesterday"
Observation: San Francisco Temperature Yesterday. Maximum temperature yesterday: 57 °F (at 1:56 pm) Minimum temperature yesterday: 49 °F (at 1:56 am) Average temperature ...
Thought: I now have the temperature, so I can use the calculator to raise it to the .023 power.
Action: Calculator
Action Input: 57^.023
Observation: Answer: 1.0974509573251117

Thought: I now know the final answer
Final Answer: The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117.

> Finished chain.

内存:将状态添加到链和代理中

到目前为止,我们所经历的所有链和代理都是无状态的。但通常,您可能希望链或代理具有某种“记忆”概念,以便它可以记住有关其先前交互的信息。最清晰和简单的例子是在设计聊天机器人时——您希望它记住以前的消息,以便它可以使用上下文来进行更好的对话。这将是一种“短期记忆”。在更复杂的方面,你可以想象一个链/代理随着时间的推移记住关键信息——这将是一种“长期记忆”。有关后者的更具体想法,请参阅这篇很棒的论文。

LangChain 专门为此提供了几个专门创建的链。本笔记本介绍了如何使用这些链中的一个 (the ConversationChain) 和两种不同类型的内存。

默认情况下,ConversationChain有一种简单类型的内存,可以记住所有以前的输入/输出并将它们添加到传递的上下文中。让我们来看看使用这个链(设置verbose=True以便我们可以看到提示)。

from langchain import OpenAI, ConversationChain

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

output = conversation.predict(input="Hi there!")
print(output)
> 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?'
output = conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
print(output)
> 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?"

构建语言模型应用程序:聊天模型

同样,您可以使用聊天模型而不是 LLM。聊天模型是语言模型的变体。虽然聊天模型在底层使用语言模型,但它们公开的接口有点不同:它们公开的不是“文本输入、文本输出”API,而是“聊天消息”作为输入和输出的接口。

聊天模型 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([HumanMessage(content="Translate this sentence from English to French. I love programming.")])
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})

您还可以为 OpenAI 的 gpt-3.5-turbo 和 gpt-4 模型传入多条消息。

messages = [
    SystemMessage(content="You are a helpful assistant that translates English to French."),
    HumanMessage(content="I love programming.")
]
chat(messages)
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})

您可以更进一步,使用 为多组消息生成补全generate。这将返回LLMResult带有附加message参数的 :

batch_messages = [
    [
        SystemMessage(content="You are a helpful assistant that translates English to French."),
        HumanMessage(content="I love programming.")
    ],
    [
        SystemMessage(content="You are a helpful assistant that translates English to French."),
        HumanMessage(content="I love artificial intelligence.")
    ],
]
result = chat.generate(batch_messages)
result
# -> LLMResult(generations=[[ChatGeneration(text="J'aime programmer.", generation_info=None, message=AIMessage(content="J'aime programmer.", additional_kwargs={}))], [ChatGeneration(text="J'aime l'intelligence artificielle.", generation_info=None, message=AIMessage(content="J'aime l'intelligence artificielle.", additional_kwargs={}))]], llm_output={'token_usage': {'prompt_tokens': 57, 'completion_tokens': 20, 'total_tokens': 77}})

您可以从此 LLMResult 中恢复诸如令牌使用之类的内容:

result.llm_output['token_usage']
# -> {'prompt_tokens': 57, 'completion_tokens': 20, 'total_tokens': 77}

聊天提示模板

与 LLM 类似,您可以通过使用MessagePromptTemplate. 您可以ChatPromptTemplate从一个或多个MessagePromptTemplates 构建一个。您可以使用ChatPromptTemplate's format_prompt– 这将返回一个PromptValue,您可以将其转换为字符串或Message对象,具体取决于您是否要将格式化值用作 llm 或聊天模型的输入。

为方便起见,from_template模板上公开了一个方法。如果您要使用此模板,它会是这样的:

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

# get a chat completion from the formatted messages
chat(chat_prompt.format_prompt(input_language="English", output_language="French", text="I love programming.").to_messages())
# -> AIMessage(content="J'aime programmer.", additional_kwargs={})

带有聊天模型的链

上一节中讨论的内容LLMChain也可以与聊天模型一起使用:

from langchain.chat_models import ChatOpenAI
from langchain import LLMChain
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'aime programmer."

具有聊天模型的代理

代理也可以与聊天模型一起使用,您可以初始化一个AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION作为代理类型。

from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI

# First, let's load the language model we're going to use to control the agent.
chat = ChatOpenAI(temperature=0)

# Next, let's load some tools to use. Note that the `llm-math` tool uses an LLM, so we need to pass that in.
llm = OpenAI(temperature=0)
tools = load_tools(["serpapi", "llm-math"], llm=llm)


# Finally, let's initialize an agent with the tools, the language model, and the type of agent we want to use.
agent = initialize_agent(tools, chat, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

# Now let's test it out!
agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")

> Entering new AgentExecutor chain...
Thought: I need to use a search engine to find Olivia Wilde's boyfriend and a calculator to raise his age to the 0.23 power.
Action:
{
  "action": "Search",
  "action_input": "Olivia Wilde boyfriend"
}

Observation: Sudeikis and Wilde's relationship ended in November 2020. Wilde was publicly served with court documents regarding child custody while she was presenting Don't Worry Darling at CinemaCon 2022. In January 2021, Wilde began dating singer Harry Styles after meeting during the filming of Don't Worry Darling.
Thought:I need to use a search engine to find Harry Styles' current age.
Action:
{
  "action": "Search",
  "action_input": "Harry Styles age"
}

Observation: 29 years
Thought:Now I need to calculate 29 raised to the 0.23 power.
Action:
{
  "action": "Calculator",
  "action_input": "29^0.23"
}

Observation: Answer: 2.169459462491557

Thought:I now know the final answer.
Final Answer: 2.169459462491557

> Finished chain.
'2.169459462491557'

内存:将状态添加到链和代理中

您可以将内存与使用聊天模型初始化的链和代理一起使用。这与 Memory for 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.")
# -> "Sure! I am an AI language model created by OpenAI. I was trained on a large dataset of text from the internet, which allows me to understand and generate human-like language. I can answer questions, provide information, and even have conversations like this one. Is there anything else you'd like to know about me?"
展开阅读全文

页面更新:2024-03-15

标签:示例   字符串   中文   应用程序   入门   模型   内存   提示   快速   语言   消息   手册   简单   指南   用户

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2020-2024 All Rights Reserved. Powered By 71396.com 闽ICP备11008920号-4
闽公网安备35020302034903号

Top