当前位置:   article > 正文

构建LangChain应用程序的示例代码:19、自定义多动作代理教程(Custom multi-action agent)_serpapiwrapper

serpapiwrapper

自定义多动作代理

概述

这个笔记本介绍了如何创建您自己的自定义代理。

代理由两部分组成:

  • 工具(Tools):代理可以使用的工具。
  • 代理类本身:决定采取哪个动作。

在这个笔记本中,我们将通过创建一个自定义代理来演示如何预测/一次性执行多个步骤。

Python 代码及注释

from langchain.agents import AgentExecutor, BaseMultiActionAgent, Tool
from langchain_community.utilities import SerpAPIWrapper

# 定义一个返回随机单词的函数
def random_word(query: str) -> str:
    print("\nNow I'm doing this!")  # 打印一条消息,表示正在执行操作
    return "foo"  # 返回一个随机单词,这里固定返回"foo"

# 初始化一个SerpAPIWrapper对象,用于执行搜索操作
search = SerpAPIWrapper()

# 定义代理可以使用的工具列表
tools = [
    Tool(
        name="Search",  # 工具名称为"Search"
        func=search.run,  # 工具的功能函数是search.run
        description="useful for when you need to answer questions about current events",  # 工具描述
    ),
    Tool(
        name="RandomWord",  # 工具名称为"RandomWord"
        func=random_word,  # 工具的功能函数是random_word
        description="call this to get a random word.",  # 工具描述
    ),
]

# 从langchain_core库导入所需的类
from typing import Any, List, Tuple, Union
from langchain_core.agents import AgentAction, AgentFinish

# 定义一个自定义的代理类,继承自BaseMultiActionAgent
class FakeAgent(BaseMultiActionAgent):
    """Fake Custom Agent."""  # 类的描述

# 创建自定义代理的实例
agent = FakeAgent()

# 从AgentExecutor类创建一个执行器,传入代理实例和工具列表,并设置verbose为True以显示详细输出
agent_executor = AgentExecutor.from_agent_and_tools(
    agent=agent, 
    tools=tools, 
    verbose=True
)

# 使用执行器运行一个查询,例如查询2023年加拿大的人口数量
agent_executor.run("How many people live in canada as of 2023?")
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

总结

本文介绍了如何创建一个自定义的多动作代理,包括定义工具和代理类。通过示例代码,我们展示了如何使用AgentExecutor来执行代理操作,并运行一个简单的查询。代码中包含了对每个部分的详细注释,以便更好地理解每个步骤的功能和目的。自定义代理可以扩展和适应各种不同的应用场景,通过组合不同的工具来实现复杂的任务。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/883973
推荐阅读
相关标签
  

闽ICP备14008679号