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

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

文章目录

  • 代理类型
    • react
    • plan&execute
    • structured-chat
  • 自定义代理

代理类型

react

from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAIllm = 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 questionBegin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"sQuestion: {input}
{agent_scratchpad}"""from typing import Callable
# Set up a prompt template
class CustomPromptTemplate(StringPromptTemplate):# The template to usetemplate: str############## NEW ####################### The list of tools availabletools_getter: Callabledef format(self, **kwargs) -> str:# Get the intermediate steps (AgentAction, Observation tuples)# Format them in a particular wayintermediate_steps = kwargs.pop("intermediate_steps")thoughts = ""for action, observation in intermediate_steps:thoughts += action.logthoughts += f"\nObservation: {observation}\nThought: "# Set the agent_scratchpad variable to that valuekwargs["agent_scratchpad"] = thoughts############## NEW ######################tools = self.tools_getter(kwargs["input"])# Create a tools variable from the list of tools providedkwargs["tools"] = "\n".join([f"{tool.name}: {tool.description}" for tool in tools])# Create a list of tool names for the tools providedkwargs["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 neededinput_variables=["input", "intermediate_steps"]
)class CustomOutputParser(AgentOutputParser):def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:# Check if agent should finishif "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 inputregex = 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 inputreturn 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)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/619805.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

计算机体系结构----缓存一致性/多处理机

本文严禁转载,仅供学习使用。参考资料来自中国科学院大学计算机体系结构课程PPT以及《Digital Design and Computer Architecture》、《超标量处理器设计》、同济大学张晨曦教授资料。如有侵权,联系本人修改。 本文衔接上文计算机体系结构----存储系统 …

python爬虫,验证码识别,携带cookies请求

古诗词网案例!!! 识别验证码类型: # 此处用到的图片验证码识别网址为:http://ttshitu.com/ 图鉴 import base64 import json import requests # 一、图片文字类型(默认 3 数英混合): # 1 : 纯数字 # 1001:纯数字2 # 2 : 纯英文 # 1002:纯英文2 # 3 : 数英混合 # 1003:…

用通俗易懂的方式讲解:大模型微调方法总结

大家好,今天给大家分享大模型微调方法:LoRA,Adapter,Prefix-tuning,P-tuning,Prompt-tuning。 文末有大模型一系列文章及技术交流方式,传统美德不要忘了,喜欢本文记得收藏、关注、点赞。 文章目录 1、LoRA…

轻松查看WiFi密码的神奇脚本,让你忘记密码也不再是问题

说在前面 🎈本文介绍了一个便捷的脚本,可以帮助你获取电脑中保存的所有Wi-Fi网络的密码。不再需要担心忘记Wi-Fi密码或手动查找密码的麻烦,只需运行脚本即可一键获取。 一、引言 互联网的普及让我们离不开Wi-Fi网络,但忘记密码时…

怎么安装es、kibana(单点安装)

1.部署单点es 1.1.创建网络 因为我们还需要部署kibana容器,因此需要让es和kibana容器互联。这里先创建一个网络: docker network create es-net1.2.加载镜像 这里我们采用elasticsearch的7.12.1版本的镜像,这个镜像体积非常大&#xff0c…

用C语言采集亚马逊amazon产品数据

上一篇文章我是用C写的一个爬取亚马逊的爬虫程序,相信大家已经看过了,这次呢,我依然使用C语言来写一个爬虫,大体上思路是和之前一样,只是支持的库以及语法有些区别,具体的呢我会一一解释出来,方…

android自定义来电秀UI

简单来电秀功能,效果如图: 底部附上demo 一、新建一个PhoneCallService服务,在服务中监听来电等状态,且控制UI显示 public class PhoneCallService extends InCallService {private final Call.Callback callback new Call.Ca…

仿真机器人-深度学习CV和激光雷达感知(项目2)day01

文章目录 前言项目介绍功能与技术简介硬件要求环境配置虚拟机运行项目demo 前言 💫你好,我是辰chen,本文旨在准备考研复试或就业 💫本文内容是我为复试准备的第二个项目 💫欢迎大家的关注,我的博客主要关注…

如何给AI下达精准的指令,哪些提示词对于AI是有效的?

刚上手那会,我倾向于将 prompt 翻译为“指令”,但这并不精确。“指令”通常对应instructions,属于 prompt 中的纯指令部分,通常是一个动宾结构(做什么)。剩下的部分更多是描述(describe&#xf…

Open3D 不规则点云体积计算 (15)

Open3D 不规则点云体积计算 (15) 一、算法介绍二、算法实现1.代码2.结果黑暗笼罩万物,我将是黑暗中最后的那道曙光,以雷霆,击碎黑暗!!! 一、算法介绍 点云往往是不规则的,利用别的包围盒方法获取的体积可能不太准确,如果希望获取更准确的体积,这里介绍一种基于体素…

stable-diffusion 学习笔记

从效果看Stable Diffusion中的采样方法 参考:Ai 绘图日常 篇二:从效果看Stable Diffusion中的采样方法_软件应用_什么值得买 大概示例:

arm64架构编译electron长征路

文章目录 1. gn工具生成1.1 问题,找不到last_commit_position.h文件问题描述如下:解决方法1.2 ninja文件不是对应架构问题问题描述:解决方法1.3 问题3:clang++找不到问题描述解决方法2. electron 编译参数生成2.1 下载对应版本debian_bullseye_arm64-sysroot错误描述

Linux:信号

目录 1.信号 2.信号的过程 a.信号的产生 1:键盘产生, 异常产生 2:系统调用产生信号 3.软件条件产生信号 4.硬件异常产生信号 b.信号的发送 c.信号的处理 d.总结与思考 3.信号保存 1.信号及其它相关常见概念 2.在内核中的表示 3.sigset_t 4. 信号集操作函数 4.信…

【读书笔记】网空态势感知理论与模型(十)

网络安全的认知科学:一个推进社会-网络系统研究的框架 1.引言 网空安全理念、策略和操作的核心是对抗性的规则,对于攻击方来说,这个规则会推动一个威胁去夺取重要数据或文件的所有权。 2. 网空安全作为一个跨学科的超系统,其中…

Arduino开发实例-AS608光学指纹传感器驱动

AS608光学指纹传感器驱动 文章目录 AS608光学指纹传感器驱动1、AS608光学指纹传感器介绍2、硬件准备及接线3、代码实现3.1 指纹录入3.2 指纹匹配验证1、AS608光学指纹传感器介绍 AS608 光学指纹传感器可用于扫描指纹,它也可以通过串行通信将处理后的数据发送到微控制器。 所有…

50天精通Golang(第16天)

beego框架介绍和流程分析 beego官方文档:https://beego.me/ 一、beego框架介绍 1.1 beego框架介绍–beego简介 1.1.1 什么是beego beego是一个使用Go语言来开发WEB引用的GoWeb框架,该框架起始于2012年,由一位中国的程序员编写并进行公开…

gem5学习(12):理解gem5 统计信息和输出——Understanding gem5 statistics and output

目录 一、config.ini 二、config.json 三、stats.txt 官方教程:gem5: Understanding gem5 statistics and output 在运行 gem5 之后,除了仿真脚本打印的仿真信息外,还会在根目录中名为 m5out 的目录中生成三个文件: config.i…

第六篇 提升网页性能:深入解析HTTP请求优化策略(一)

深入浅出HTTP请求前后端交互系列专题 第一章 引言-HTTP协议基础概念和前后端分离架构请求交互概述 第二章 HTTP请求方法、状态码详解与缓存机制解析 第三章 前端发起HTTP请求 第四章 前后端数据交换格式详解 第五章 跨域资源共享(CORS):现代W…

水仙花数(Java解法)

什么是水仙花数? 水仙花数是指一个 3 位数,它每位上的数字的 3 次幂之和等于它本身(例如: 1 5 3 153 ),水仙花数的取值范围在 100~1000 之间。 解题思路: 这个题需要把所以的数字都拿到&…

Egg框架搭建后台服务【2】

前言 接上文 Egg框架搭建后台服务【1】,继续优化后台服务,之前直接用 SQL 语句调用的数据库数据,既不安全,也比较麻烦,当然最重要的是“显着不专业”。 所以本文仍然是增删改查,重点是将原本 SQL 语句操作…