大模型从入门到应用——LangChain:代理(Agents)-[带有ChatModel的LLM聊天自定义代理和自定义多操作代理(Custom MultiAction Agent)]

本文档详细介绍了LangChain框架,用于开发基于大型语言模型(LLM)的应用。内容涵盖从安装配置到自定义代理的创建,包括PromptTemplate、ChatModel、记忆管理、检索式问答和多操作代理的实现。通过示例展示了如何创建能够同时执行多个步骤的自定义代理FakeAgent。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分类目录:《大模型从入门到应用》总目录

LangChain系列文章:


带有ChatModel的LLM聊天自定义代理(Custom LLM Chat Agent)

本部分将介绍如何基于聊天模型创建自己的自定义代理。LLM聊天代理由三个部分组成:

  • PromptTemplate:这是用于指示语言模型该做什么的提示模板
  • ChatModel:这是驱动代理的语言模型
  • Stop序列:指示LLM在找到此字符串时停止生成
  • OutputParser:确定如何将LLM输出解析为AgentActionAgentFinish对象。

LLMAgent用于代理执行器。这个代理执行器在很大程度上可以看作是一个循环:

  • 将用户输入和任何先前的步骤传递给代理(在这种情况下是LLMAgent)
  • 如果代理返回AgentFinish,则将其直接返回给用户

自定义多操作代理(Custom MultiAction Agent)

本教程介绍如何创建您自己的自定义代理。

代理由两部分组成:

  • 工具:代理可以使用的工具。
  • 代理类本身:这决定了要采取哪个操作。

在本文中,我们将介绍如何创建一个自定义代理,该代理可以预测或同时执行多个步骤:

from langchain.agents import Tool, AgentExecutor, BaseMultiActionAgent
from langchain import OpenAI, SerpAPIWrapper
 

def random_word(query: str) -> str:
    print("\n现在我正在做这个!")
    return "foo"
 

search = SerpAPIWrapper()
tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events"
    ),
    Tool(
        name = "RandomWord",
        func=random_word,
        description="call this to get a random word."
    
    )
]

from typing import List, Tuple, Any, Union
from langchain.schema import AgentAction, AgentFinish
 
class FakeAgent(BaseMultiActionAgent):
    """Fake Custom Agent."""
    
    
    def input_keys(self):
        return ["input"]
    
    def plan(
        self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
    ) -> Union[List[AgentAction], AgentFinish]:
        """Given input, decided what to do.
 
        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations
            **kwargs: User inputs.
 
        Returns:
            Action specifying what tool to use.
        """
        if len(intermediate_steps) == 0:
            return [
                AgentAction(tool="Search", tool_input=kwargs["input"], log=""),
                AgentAction(tool="RandomWord", tool_input=kwargs["input"], log=""),
            ]
        else:
            return AgentFinish(return_values={"output": "bar"}, log="")
 
    async def aplan(
        self, intermediate_steps: List[Tuple[AgentAction, str]], **kwargs: Any
    ) -> Union[List[AgentAction], AgentFinish]:
        """Given input, decided what to do.
 
        Args:
            intermediate_steps: Steps the LLM has taken to date,
                along with observations
            **kwargs: User inputs.
 
        Returns:
            Action specifying what tool to use.
        """
        if len(intermediate_steps) == 0:
            return [
                AgentAction(tool="Search", tool_input=kwargs["input"], log=""),
                AgentAction(tool="RandomWord", tool_input=kwargs["input"], log=""),
            ]
        else:
            return AgentFinish(return_values={"output": "bar"}, log="")

agent = FakeAgent()

agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)

agent_executor.run("How many people live in canada as of 2023?")

输出:

> Entering new AgentExecutor chain...
The current population of Canada is 38,669,152 as of Monday, April 24, 2023, based on Worldometer elaboration of the latest United Nations data.
Now I'm doing this!
foo
 
> Finished chain.

'bar'

参考文献:
[1] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/
[2] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

von Neumann

您的赞赏是我创作最大的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值