赞
踩
www.aidoczh.com已经系统的将LangChain官网文档翻译成中文,您可以去http://www.aidoczh.com/langchain/v0.2/docs/introduction/ 查看文档,该网站www.aidoczh.com主要是将AI工具官方文档翻译成中文,还有其他工具文档可以看。
原文:Building a Math Application with LangChain Agents
代码:https://github.com/tahreemrasul/math_app_langchain
在本教程中,我将演示如何使用 LangChain agents 来创建一个自定义数学应用程序,利用 OpenAI 的 GPT3.5 模型。对于应用程序的前端,我将使用 Chainlit,这是一个易于使用的开源 Python 框架。这个生成式数学应用程序,让我们称之为“数学大师”,旨在帮助用户解决数学或推理/逻辑问题。
“数学大师”应用程序架构。作者绘制的插图。
大型语言模型(LLMs)在数学以及推理任务上表现不佳,这是许多语言模型的共同特点。这其中有几个不同的原因:
这使得“数学问题”成为利用 LangChain agents 的理想候选者。Agents 是使用语言模型与其他工具进行交互以分解复杂问题的系统(稍后详细介绍)。本教程的代码可在我的 GitHub 上找到。
我们可以从创建一个新的 conda
环境开始,使用 python=3.11.
conda create -n math_assistant python=3.11
激活环境:
conda activate math_assistant
接下来,让我们安装所有必要的库:
pip install -r requirements.txt
在 OpenAI 注册并获取您自己的密钥以开始调用 gpt 模型。一旦您获得密钥,就在您的存储库中创建一个 .env
文件并存储 OpenAI 密钥:
OPENAI_API_KEY="your_openai_api_key"
“数学大师”应用程序的流程如下图所示。我们的管道中的 agent 将拥有一组工具,它可以使用这些工具来回答用户的查询。大型语言模型(LLM)充当 agent 的“大脑”,指导其决策。当用户提交问题时,agent 使用 LLM 选择最合适的工具或一组工具来提供答案。如果 agent 确定需要多个工具,它还将指定工具的使用顺序。
LangChain Agents 解构。作者绘制的插图。
我们的“数学大师”应用程序的 agent 将使用以下工具:
现在我们有了一个大致的应用程序设计,我们可以开始考虑构建这个应用程序。
LangChain agents 旨在通过提供更复杂和交互式任务的接口来增强与语言模型的交互。我们可以将 agent 视为用户和大型语言模型之间的中介。Agents 旨在将一个看似复杂的用户查询(我们的 LLM 可能无法单独处理)分解为更简单、可操作的步骤。
在我们的应用程序流程中,我们定义了几种不同的工具,我们希望在我们的数学应用程序中使用这些工具。根据用户输入,agent 应决定使用这些工具中的哪一个。如果不需要某个工具,则不应使用它。LangChain agents 可以简化这一过程。这些 agents 使用语言模型选择要采取的一系列操作。本质上,LLM 充当 agent 的“大脑”,指导其决定为特定查询使用哪个工具以及使用的顺序。这与 LangChain chains 不同,后者的操作顺序是在代码中硬编码的。LangChain 提供了一系列可以与 agent 集成的工具。这些工具包括但不限于在线搜索工具、基于 API 的工具、基于链的工具等。有关 LangChain agents 及其类型的更多信息,请参阅此处。
创建一个 chatbot.py
脚本并导入必要的依赖项:
from langchain_openai import OpenAI
from langchain.chains import LLMMathChain, LLMChain
from langchain.prompts import PromptTemplate
from langchain_community.utilities import WikipediaAPIWrapper
from langchain.agents.agent_types import AgentType
from langchain.agents import Tool, initialize_agent
from dotenv import load_dotenv
load_dotenv()
接下来,我们将定义基于 OpenAI 的语言模型。LangChain 提供了 langchain-openai
包,可用于定义 OpenAI 模型的实例。我们将使用 OpenAI 的 gpt-3.5-turbo-instruct
模型。dotenv
包已经处理了 API 密钥,因此您无需在此明确定义它:
llm = OpenAI(model='gpt-3.5-turbo-instruct',
temperature=0)
我们将在我们的数学和推理链中都使用这个 LLM,并将其作为我们的 agent 的决策者。
在构建自己的 agent 时,您需要为其提供一个工具列表,它可以使用这些工具。除了被调用的实际函数之外,Tool
还包括一些其他参数:
name
(str),是必需的,并且在提供给 agent 的一组工具中必须是唯一的description
(str),是可选的,但建议使用,因为 agent 使用它来确定工具的使用现在我们将创建我们的三个工具。第一个将是使用维基百科 API 包装器的在线工具:
wikipedia = WikipediaAPIWrapper()
wikipedia_tool = Tool(name="Wikipedia",
func=wikipedia.run,
description="A useful tool for searching the Internet
to find information on world events, issues, dates, years, etc. Worth
using for general topics. Use precise questions.")
在上面的代码中,我们定义了维基百科 API 包装器的一个实例。然后,我们将其包装在 LangChain 的 Tool
中,包括名称、函数和描述。
接下来,让我们定义用于计算任何数值表达式的工具。LangChain 提供了 LLMMathChain
,它使用 numexpr
Python 库来计算数学表达式。我们还需要清楚地定义此工具将用于什么目的。描述对于 agent 来说在决定从一组工具中为特定用户查询使用哪个工具时可能会有帮助。对于我们基于链的工具,我们将使用 Tool.from_function()
方法。
problem_chain = LLMMathChain.from_llm(llm=llm)
math_tool = Tool.from_function(name="Calculator",
func=problem_chain.run,
description="Useful for when you need to answer questions
about math. This tool is only for math questions and nothing else. Only input
math expressions.")
最后,我们将定义用于逻辑/推理查询的工具。我们将首先创建一个提示来指导模型执行特定任务。然后我们将为此工具创建一个简单的 LLMChain
,向其传递 LLM 和提示。
word_problem_template = """You are a reasoning agent tasked with solving the user's logic-based questions. Logically arrive at the solution, and be factual. In your answers, clearly detail the steps involved and give the final answer. Provide the response in bullet points. Question {question} Answer""" math_assistant_prompt = PromptTemplate(input_variables=["question"], template=word_problem_template ) word_problem_chain = LLMChain(llm=llm, prompt=math_assistant_prompt) word_problem_tool = Tool.from_function(name="Reasoning Tool", func=word_problem_chain.run, description="Useful for when you need to answer logic-based/reasoning questions.", )
现在我们将使用上面创建的工具初始化我们的 agent。我们还将指定 LLM 来帮助它选择要使用的工具以及使用的顺序:
agent = initialize_agent(
tools=[wikipedia_tool, math_tool, word_problem_tool],
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=False,
handle_parsing_errors=True
)
print(agent.invoke(
{"input": "I have 3 apples and 4 oranges. I give half of my oranges
away and buy two dozen new ones, alongwith three packs of
strawberries. Each pack of strawberry has 30 strawberries.
How many total pieces of fruit do I have at the end?"}))
应用程序对逻辑问题的响应
我们将使用 Chainlit,一个开源的 Python 框架,来构建我们的应用程序。使用 Chainlit,您可以用几行简单的代码构建会话式人工智能应用程序。要深入了解 Chainlit 的功能以及应用程序的设置,请查看我的这篇文章:
medium.com
我们将为我们的应用程序使用两个装饰器函数。这些将是 @cl.on_chat_start
和 @cl.on_message
装饰器函数。@cl.on_chat_start
将负责包装所有应在用户会话启动时执行的代码。@cl.on_message
将包含我们希望在用户发送查询时执行的代码片段。
让我们使用这两个装饰器函数重构我们的 chatbot.py
脚本。让我们从将 chainlit
包导入到我们的 chatbot.py
脚本开始:
import chainlit as cl
接下来,让我们编写围绕 @cl.on_chat_start
装饰器函数的包装函数。我们将在此函数中添加我们的 LLM、工具和代理初始化代码。我们将把我们的 agent
存储在用户会话内的一个变量中,以便在用户发送消息时检索。
@cl.on_chat_start def math_chatbot(): llm = OpenAI(model='gpt-3.5-turbo-instruct', temperature=0) # 基于推理的工具提示 word_problem_template = """You are a reasoning agent tasked with solving t he user's logic-based questions. Logically arrive at the solution, and be factual. In your answers, clearly detail the steps involved and give the final answer. Provide the response in bullet points. Question {question} Answer""" math_assistant_prompt = PromptTemplate( input_variables=["question"], template=word_problem_template ) # 基于推理的工具链 word_problem_chain = LLMChain(llm=llm, prompt=math_assistant_prompt) # 基于推理的工具 word_problem_tool = Tool.from_function(name="Reasoning Tool", func=word_problem_chain.run, description="Useful for when you need to answer logic-based/reasoning questions." ) # 算术计算器工具 problem_chain = LLMMathChain.from_llm(llm=llm) math_tool = Tool.from_function(name="Calculator", func=problem_chain.run, description="Useful for when you need to answer numeric questions. This tool is only for math questions and nothing else. Only input math expressions, without text", ) # 维基百科工具 wikipedia = WikipediaAPIWrapper() wikipedia_tool = Tool( name="Wikipedia", func=wikipedia.run, description="A useful tool for searching the Internet to find information on world events, issues, dates, " "years, etc. Worth using for general topics. Use precise questions.", ) # 代理 agent = initialize_agent( tools=[wikipedia_tool, math_tool, word_problem_tool], llm=llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=False, handle_parsing_errors=True ) cl.user_session.set("agent", agent)
接下来,让我们为 @cl.on_message
装饰器定义包装函数。这将包含用户向我们的应用程序发送查询时的代码。我们将首先检索会话开始时设置的代理,然后异步调用用户查询。
@cl.on_message
async def process_user_query(message: cl.Message):
agent = cl.user_session.get("agent")
response = await agent.acall(message.content,
callbacks=[cl.AsyncLangchainCallbackHandler()])
await cl.Message(response["output"]).send()
我们可以使用以下命令运行我们的应用程序:
chainlit run chatbot.py
应用程序应该在 https://localhost:8000 上可用。
让我们还编辑我们存储库中的 chainlit.md
文件。当您运行上述命令时,此文件会自动生成。
# 欢迎来到 Math Wiz!声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。