langchain快速入门

快速入门指南

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

安装

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

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

环境设置

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

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

pip install openai

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

export OPENAI_API_KEY="..."

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

import osos.environ["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。

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

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

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

from langchain.prompts import PromptTemplateprompt = 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 PromptTemplatefrom langchain.llms import OpenAIllm = 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 LLMChainchain = LLMChain(llm=llm, prompt=prompt)

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

chain.run("colorful socks")# -> '\n\nSocktastic!'

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

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

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

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

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

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

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

  • 工具:执行特定任务的功能。这可以是:Google 搜索、数据库查找、Python REPL、其他链。工具的接口目前是一个函数,期望将字符串作为输入,将字符串作为输出。

  • LLM:为代理提供支持的语言模型。

  • 代理:要使用的代理。这应该是一个引用支持代理类的字符串。由于本笔记本侧重于最简单、最高级别的 API,因此仅涵盖使用标准支持的代理。如果您想实施自定义代理,请参阅自定义代理的文档(即将推出)。

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

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

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

pip install google-search-results

并设置相应的环境变量。

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

现在我们可以开始了!

from langchain.agents import load_toolsfrom langchain.agents import initialize_agentfrom langchain.agents import AgentTypefrom 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: SearchAction 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: CalculatorAction Input: 57^.023Observation: Answer: 1.0974509573251117Thought: I now know the final answerFinal 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, ConversationChainllm = 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 目前支持的消息类型有AIMessageHumanMessageSystemMessage, 和ChatMessageChatMessage接受任意角色参数。大多数时候,您只会处理HumanMessageAIMessageSystemMessage

from langchain.chat_models import ChatOpenAIfrom 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="Translate this sentence from English to French. 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="Translate this sentence from English to French. I love programming.")
    ],
    [
        SystemMessage(content="You are a helpful assistant that translates English to French."),
        HumanMessage(content="Translate this sentence from English to French. 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': 71, 'completion_tokens': 18, 'total_tokens': 89}})

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

result.llm_output['token_usage']# -> {'prompt_tokens': 71, 'completion_tokens': 18, 'total_tokens': 89}

聊天提示模板

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

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

from langchain.chat_models import ChatOpenAIfrom 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 messageschat(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 ChatOpenAIfrom langchain import LLMChainfrom 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_toolsfrom langchain.agents import initialize_agentfrom langchain.agents import AgentTypefrom langchain.chat_models import ChatOpenAIfrom 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 yearsThought:Now I need to calculate 29 raised to the 0.23 power.Action:{  "action": "Calculator",  "action_input": "29^0.23"}Observation: Answer: 2.169459462491557Thought: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 ConversationChainfrom langchain.chat_models import ChatOpenAIfrom langchain.memory import ConversationBufferMemoryprompt = 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?"

文章转自AI交流分享平台promptcan波浪客,langchain快速入门 - promptcan波浪客,随着人工智能的兴起,诞生了一种全新的职业--AI指令提示工程师,负责在AI平台设计各种各样的指令提示词,从而让AI模型生成高质量的成果,比如AI图片,文章等等,如果你擅长做AI指令(prompt)的创作,你就可以用他来赚取你的副业收入,www.promptcan.com波浪客平台是国内首家专门交易AI创作指令的平台,提供高质量的AI创作指令,减少创作成本,同时你也可以发布自己的技能服务,让客户雇佣你帮他设计AI创作指令以生成需要的成果

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值