langchain-Agent-Agent类型和自定义Agent(代码)

本文介绍了如何在Python中使用不同的代理类型,如React、Plan&Execute以及结构化聊天代理,展示了如何加载工具、初始化代理并执行任务,以及如何自定义代理模板和输出解析。

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

本篇主要用于记忆Agent相关代码,不对各个类型Agent的功能和原理进行描述。

代理类型

react

from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI

llm = OpenAI(temperature=0)
tools = load_tools(["serpapi", "llm-math"], llm=llm)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("目前市场上玫瑰花的平均价格是多少?如果我在此基础上加价15%卖出,应该如何定价?")

plan&execute

model = ChatOpenAI(temperature=0)
planner = load_chat_planner(model)
executor = load_agent_executor(model, tools, verbose=True)
agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)

agent.run("在纽约,100美元能买几束玫瑰?")

structured-chat

结构化工具聊天代理能够使用多输入工具。

旧代理配置为将动作输入指定为单个字符串,但是该代理可以使用提供的工具的args_schema来填充动作输入。

这个功能可以使用代理类型 structured-chat-zero-shot-react-description 或 AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION 来实现

自定义代理

tools = get_tools("What is today weather")

# Set up the base template
template = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:
 
{tools}
 
Use the following format:
 
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
 
Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s
 
Question: {input}
{agent_scratchpad}"""

from typing import Callable
# Set up a prompt template
class CustomPromptTemplate(StringPromptTemplate):
    # The template to use
    template: str
    ############## NEW ######################
    # The list of tools available
    tools_getter: Callable
 
    def format(self, **kwargs) -> str:
        # Get the intermediate steps (AgentAction, Observation tuples)
        # Format them in a particular way
        intermediate_steps = kwargs.pop("intermediate_steps")
        thoughts = ""
        for action, observation in intermediate_steps:
            thoughts += action.log
            thoughts += f"\nObservation: {observation}\nThought: "
        # Set the agent_scratchpad variable to that value
        kwargs["agent_scratchpad"] = thoughts
        ############## NEW ######################
        tools = self.tools_getter(kwargs["input"])
        # Create a tools variable from the list of tools provided
        kwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in tools])
        # Create a list of tool names for the tools provided
        kwargs["tool_names"] = ", ".join([tool.name for tool in tools])
        return self.template.format(**kwargs)

prompt = CustomPromptTemplate(
    template=template,
    tools_getter=tools,
    # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically
    # This includes the `intermediate_steps` variable because that is needed
    input_variables=["input", "intermediate_steps"]
)
 
class CustomOutputParser(AgentOutputParser):
    def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:
        # Check if agent should finish
        if "Final Answer:" in llm_output:
            return AgentFinish(
                # Return values is generally always a dictionary with a single `output` key
                # It is not recommended to try anything else at the moment :)
                return_values={"output": llm_output.split("Final Answer:")[-1].strip()},
                log=llm_output,
            )
        # Parse out the action and action input
        regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"
        match = re.search(regex, llm_output, re.DOTALL)
        if not match:
            raise ValueError(f"Could not parse LLM output: `{llm_output}`")
        action = match.group(1).strip()
        action_input = match.group(2)
        # Return the action and action input
        return AgentAction(tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output)

output_parser = CustomOutputParser()

llm = ChatOpenAI(temperature=0)
# LLM chain consisting of the LLM and a prompt
llm_chain = LLMChain(llm=llm, prompt=prompt)

tool_names = [tool.name for tool in tools]
agent = LLMSingleActionAgent(
    llm_chain=llm_chain, 
    output_parser=output_parser,
    stop=["\nObservation:"], 
    allowed_tools=tool_names
)
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
agent_executor.run("What's the weather in SF?")

如果想将plan&execute中的Agent执行器替换为上面自己定义的Agent,可以使用下面代码:

model = ChatOpenAI(temperature=0)
planner = load_chat_planner(model)
executor = load_agent_executor(model, tools, verbose=True)
executor.chain.agent = agent_executor
agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)
<think>嗯,用户想在Langchain-Chatchat的0.3.0版本中自定义Agent,需要示例方法。首先,我需要回忆一下Langchain-Chatchat的文档结构,尤其是关于Agent的部分。根据提供的引用内容,引用[2]提到了L3.1 Agent模型框架,这可能与自定义Agent相关。用户需要具体的步骤,所以应该分步骤说明。 首先,安装库。根据引用[1],用户需要安装特定版本,可能需要使用pip install命令。然后,可能需要导入相关模块,比如AgentExecutor或BaseTool。接下来,创建工具类,这部分可能需要继承BaseTool,并实现必要的接口,比如_run方法。然后,注册工具到Agent,可能需要使用装饰器或者配置文件。接着,初始化Agent并运行,可能需要加载模型,设置参数等。示例代码应该用Python展示,并且符合用户的代码格式要求。 另外,用户可能需要了解如何扩展工具调整策略,比如添加新工具或者修改提示模板。需要注意用户提到的版本是0.3.0,所以需要确保提供的方法适用于该版本。同时,需要检查是否有相关引用支持,比如引用[3]提到本地部署可能需要模型路径,但用户的问题更多是关于自定义Agent,所以可能引用[2][1]更相关。 最后,生成相关问题时要围绕自定义Agent的深入问题,比如性能优化、工具扩展、模型集成等。需要确保回答结构清晰,步骤正确,并且代码示例无误。需要确认所有LaTeX格式是否正确,比如行内公式用$...$,独立公式用$$...$$,但在这个问题中可能数学公式较少,但还是要检查是否有需要的地方。使用中文回答,保持自然流畅。</think>以下是在LangChain-Chatchat 0.3.0版本中自定义Agent的详细步骤及示例: ### 一、环境准备 1. 安装指定版本库(基于引用[1]): ```bash pip install langchain-chatchat==0.3.0 -U ``` ### 二、自定义Agent开发流程 #### 步骤1:创建工具类 ```python from langchain.tools import BaseTool class CustomCalculator(BaseTool): name = "数学计算器" description = "执行基础算术运算" def _run(self, expression: str) -> str: try: return str(eval(expression)) except Exception as e: return f"计算错误:{e}" ``` #### 步骤2:注册Agent工具 ```python from langchain.agents import tool @tool def weather_query(city: str) -> str: """获取指定城市的天气信息""" # 实现API调用逻辑 return f"{city}:晴,25℃" ``` #### 步骤3:构建Agent执行器(基于引用[2]的L3.1框架) ```python from langchain.agents import AgentExecutor from langchain.chat_models import ChatOpenAI def create_agent(): tools = [CustomCalculator(), weather_query] llm = ChatOpenAI(temperature=0) return AgentExecutor.from_agent_and_tools( agent="zero-shot-react-description", tools=tools, llm=llm, verbose=True ) ``` ### 三、运行示例 ```python agent = create_agent() result = agent.run("北京气温是多少?计算(3^2 + 4)*5的值") print(result) ``` ### 四、扩展方法(基于引用[3]的部署经验) 1. **工具扩展**:继承`BaseTool`类可添加任意功能模块 2. **策略调整**:通过修改`prompt_template`实现交互逻辑定制 3. **模型集成**:可替换LLM为ChatGLM等本地模型
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值