前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LangChain系列】第三节:Agent代理

【LangChain系列】第三节:Agent代理

原创
作者头像
Freedom123
发布2024-05-19 13:24:10
1960
发布2024-05-19 13:24:10
举报
文章被收录于专栏:AIGCAIGC

toc


大型语言模型 (LLM) 已成为能够理解和生成类似人类文本的有用 AI 系统。然而,它们的真正潜力在于它们能够充当推理引擎,处理新信息和回答复杂问题。LangChain的代理通过允许LLM与各种工具和数据库进行交互,协助推理和决策任务来释放这种潜力。在这篇博文中,我们将深入探讨LangChain的代理,探索如何使用内置工具配置它们并创建自定义工具来扩展其功能。

一、LLM Agents

1.LLM Agents是什么

LLM 代理的核心是 LLM 和一组工具(如搜索引擎、API 或数据存储)的组合。LLM充当推理引擎,利用这些工具和可用信息来解决复杂的任务。想象一下,拥有一个私人助理,他不仅可以理解您的人类语言指令,还可以访问和处理来自各种来源的信息,以帮助您做出明智的决定。简而言之,这就是 LLM Agents 的强大功能。

2.LLM Agents 的好处

  • 利用 LLM 的自然语言理解和生成能力:LLM 擅长处理和生成类似人类的文本,使其非常适合自然语言交互。
  • 访问和处理来自各种来源的外部信息:通过与搜索引擎、API 和数据库等工具集成,LLM 代理可以检索和处理超出其初始训练数据的信息。
  • 将推理与复杂任务的工具交互相结合:LLM 代理可以对检索到的信息进行推理,并使用它来做出决策、回答问题,甚至通过与集成工具交互来采取行动。

二、通过LangChain 工具 构建Agent

LangChain预装了一系列内置工具,您可以轻松地将其与LLM代理集成。我们来学习两个例子:DuckDuckGo Search 和 Wikipedia。

1.集成 DuckDuckGo 搜索和维基百科

代码语言:python
复制
import os
from dotenv import load_dotenv, find_dotenv

_ = load_dotenv(find_dotenv())

#!pip install -U wikipedia

from langchain_experimental.agents.agent_toolkits import create_python_agent
from langchain_experimental.tools.python.tool import PythonREPLTool
from langchain.agents import load_tools
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain import hub

prompt = (
    hub.pull("hwchase17/react")
    + " once you have final answer just exit chain do not continue"
)
llm_model = "gpt-3.5-turbo"
llm = ChatOpenAI(temperature=0, model=llm_model)

tools = load_tools(["llm-math", "wikipedia"], llm=llm)

agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    features="html.parser",
    handle_parsing_errors=True,
    verbose=True,
)

在此代码片段中,我们将导入必要的库和依赖项,配置 LLM 和代理设置,并加载 DuckDuckGo 搜索和 Wikipedia 工具。通过集成这些内置工具,我们的 LLM 代理现在可以使用 DuckDuckGo 在网络上搜索信息并检索相关的维基百科文章以帮助回答问题或解决任务。

代码语言:python
复制
agent_executor.invoke({"input": "How old is stephan hawkings"})
代码语言:shell
复制
> Entering new AgentExecutor chain...
I need to find out Stephen Hawking's age.
Action: wikipedia
Action Input: Stephen Hawking
Page: Stephen Hawking
Summary: Stephen William Hawking (8 January 1942 – 14 March 2018) was an English theoretical physicist, cosmologist, and author who was director of research at the Centre for Theoretical Cosmology at the University of Cambridge. Between 1979 and 2009, he was the Lucasian Professor of Mathematics at Cambridge, widely viewed as one of the most prestigious academic posts in the world.

...

I now know Stephen Hawking's age.
Final Answer: Stephen Hawking was 76 years old when he died in 2018.

> Finished chain.
代码语言:shell
复制
{'input': 'How old is stephan hawkings',
 'output': 'Stephen Hawking was 76 years old when he died in 2018.'}

在此示例中,代理使用维基百科工具搜索有关斯蒂芬霍金的信息,检索他的传记并确定他去世时的年龄。

2.Python Agent

LangChain 还提供了一个 Python REPL工具,允许您的 LLM 代理执行 Python 代码并执行各种编程任务。

代码语言:python
复制
agent = create_python_agent(llm, tool=PythonREPLTool(), verbose=True)

customer_list = [
    ["Harrison", "Chase"],
    ["Lang", "Chain"],
    ["Dolly", "Too"],
    ["Elle", "Elem"],
    ["Geoff", "Fusion"],
    ["Trance", "Former"],
    ["Jen", "Ayai"],
]

agent.invoke(
    f"""Sort these customers by
last name and then first name
and print the output: {customer_list}"""
)
代码语言:shell
复制
> Entering new AgentExecutor chain...
We can use the `sorted()` function in Python to sort the list of customers based on their last name and then first name.
Action: Python_REPL
Action Input: customers = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]
sorted_customers = sorted(customers, key=lambda x: (x[1], x[0]))
print(sorted_customers)
Observation: [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]

Thought: I now know the final answer
Final Answer: [['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]

> Finished chain.
代码语言:shell
复制
{'input': "Sort these customers by last name and then first name and print the output: [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Fusion'], ['Trance', 'Former'], ['Jen', 'Ayai']]",
 'output': "[['Jen', 'Ayai'], ['Lang', 'Chain'], ['Harrison', 'Chase'], ['Elle', 'Elem'], ['Trance', 'Former'], ['Geoff', 'Fusion'], ['Dolly', 'Too']]"}

在此示例中,代理使用 Python REPL 工具根据客户的姓氏和名字对客户列表进行排序,执行 Python 代码以实现所需的结果。

三、自定义工具

虽然LangChain提供了一系列内置工具,但真正的力量在于能够创建适合您特定需求的自定义工具。这允许您将 LLM 代理连接到所需的任何数据库、API 或函数。

1.通过LangChain Tool装饰器构建自定义工具

代码语言:python
复制
from langchain.agents import tool
from datetime import date

@tool
def time(text: str) -> str:
    """Returns todays date, use this for any
    questions related to knowing todays date.
    The input should always be an empty string,
    and this function will always return todays
    date - any date mathmatics should occur
    outside this function."""
    return str(date.today())

在此代码片段中,我们将使用 LangChain 的工具装饰器创建一个名为 time 的自定义工具。此工具在调用时返回当前日期,其行为在文档字符串中定义。

2.将工具与代理集成

在定义了自定义时间工具后,我们需要将其与我们的 LLM 代理集成。为此,我们在创建 create_react_agent 和 AgentExecutor 时将时间工具添加到工具列表中。

代码语言:python
复制
agent = create_react_agent(llm=llm, tools=tools + [time], prompt=prompt)
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools + [time],
    features="html.parser",
    handle_parsing_errors=True,
    verbose=True,
)

现在,我们的 LLM 代理配备了时间工具以及我们之前加载的其他内置工具。要查看我们的自定义工具的运行情况,我们可以向代理询问与当前日期相关的问题:

代码语言:python
复制
try:
    agent_executor.invoke({"input": "whats the date today?"})
except:
    print("exception on external access")
代码语言:shell
复制
> Entering new AgentExecutor chain...
Action: time
Action Input: ""
2024-05-11
Final Answer: 2024-05-11

> Finished chain.

如您所见,代理认识到它需要使用时间工具来检索当前日期,并且它提供了正确的答案,而无需任何其他提示。这个例子演示了自定义工具在LangChain的代理中的有用性。通过创建自己的工具,您可以将 LLM 代理连接到所需的任何数据源、API 或函数,从而扩展其功能以满足您的特定需求。

小结

LangChain的代理彻底改变了我们对大型语言模型的思考方式。通过将 LLM 与外部工具和数据源相结合,该框架使我们能够处理复杂的推理任务并做出明智的决策。无论您是使用 DuckDuckGo Search 和 Wikipedia 等内置工具,还是根据您的特定需求创建自定义工具,LangChain 的代理都提供了灵活且可扩展的解决方案,用于将 LLM 集成到您的应用程序中。

小编是一名热爱人工智能的专栏作者,致力于分享人工智能领域的最新知识、技术和趋势。这里,你将能够了解到人工智能的最新应用和创新,探讨人工智能对未来社会的影响,以及探索人工智能背后的科学原理和技术实现。欢迎大家点赞,评论,收藏,让我们一起探索人工智能的奥秘,共同见证科技的进步!

我正在参与2024腾讯技术创作特训营最新征文,快来和我瓜分大奖!

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、LLM Agents
    • 1.LLM Agents是什么
      • 2.LLM Agents 的好处
      • 二、通过LangChain 工具 构建Agent
        • 1.集成 DuckDuckGo 搜索和维基百科
          • 2.Python Agent
          • 三、自定义工具
            • 1.通过LangChain Tool装饰器构建自定义工具
              • 2.将工具与代理集成
              • 小结
              相关产品与服务
              数据保险箱
              数据保险箱(Cloud Data Coffer Service,CDCS)为您提供更高安全系数的企业核心数据存储服务。您可以通过自定义过期天数的方法删除数据,避免误删带来的损害,还可以将数据跨地域存储,防止一些不可抗因素导致的数据丢失。数据保险箱支持通过控制台、API 等多样化方式快速简单接入,实现海量数据的存储管理。您可以使用数据保险箱对文件数据进行上传、下载,最终实现数据的安全存储和提取。
              领券
              问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档