langchain agent
zero-shot-react-description
代码
from langchain.agents import initialize_agent
from langchain.llms import OpenAI
from langchain.tools import BaseTool
import os
os.environ['OPENAI_API_KEY']="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"# 搜索工具
class SearchTool(BaseTool):name = "Search"description = "如果我想知道天气,'鸡你太美'这两个问题时,请使用它"return_direct = True # 直接返回结果def _run(self, query: str) -> str:print("\nSearchTool query: " + query)return "这个是一个通用的返回"async def _arun(self, query: str) -> str:raise NotImplementedError("暂时不支持异步")# 计算工具
class CalculatorTool(BaseTool):name = "Calculator"description = "如果是关于数学计算的问题,请使用它"def _run(self, query: str) -> str:print("\nCalculatorTool query: " + query)return "100"async def _arun(self, query: str) -> str:raise NotImplementedError("暂时不支持异步")llm = OpenAI(temperature=0.5)
tools = [SearchTool(), CalculatorTool()]
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)print("问题:")
print("答案:" + agent.run("查询这周天气"))
print("问题:")
print("答案:" + agent.run("告诉我'鸡你太美'是什么意思"))
print("问题:")
print("答案:" + agent.run("告诉我'hello world'是什么意思"))
print("问题:")
print("答案:" + agent.run("告诉我10的3次方是多少?"))
以上代码构造如下prompt
Answer the following questions as best you can. You have access to the following tools:Search: 如果我想知道天气,'鸡你太美'这两个问题时,请使用它
Calculator: 如果是关于数学计算的问题,请使用它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 [Search, Calculator]
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!Question: 查询这周天气
Thought:
prompt模板:
PREFIX = """Answer the following questions as best you can. You have access to the following tools:"""
FORMAT_INSTRUCTIONS = """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"""
SUFFIX = """Begin!Question: {input}
Thought:{agent_scratchpad}"""
示例二
代码
import os
os.environ['SERPAPI_API_KEY']="xxx"from langchain.agents import Tool
from langchain.agents import AgentType
from langchain.memory import ConversationBufferMemory
from langchain import OpenAI
from langchain.utilities import SerpAPIWrapper
from langchain.agents import initialize_agent
import os
os.environ['OPENAI_API_KEY']="sk-xxx"
search = SerpAPIWrapper()
tools = [Tool(name = "Current Search",func=search.run,description="useful for when you need to answer questions about current events or the current state of the world"),
]memory = ConversationBufferMemory(memory_key="chat_history")llm=OpenAI(temperature=0)
agent_chain = initialize_agent(tools, llm, agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory)
agent_chain.run(input="hi, i am bob")
agent_chain.run(input="what's my name?")
agent_chain.run("what are some good dinners to make this week, if i like thai food?")
agent_chain.run(input="tell me the last letter in my name, and also tell me who won the world cup in 1978?")
agent_chain.run(input="whats the current temperature in pomfret?")
以上代码使用如下的prompt
Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.TOOLS:
------Assistant has access to the following tools:> Current Search: useful for when you need to answer questions about current events or the current state of the worldTo use a tool, please use the following format:```
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [Current Search]
Action Input: the input to the action
Observation: the result of the action
```When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:```
Thought: Do I need to use a tool? No
AI: [your response here]
```Begin!Previous conversation history:
Human: hi, i am bob
AI: Hi Bob, nice to meet you! How can I help you today?
Human: what's my name?
AI: Your name is Bob!New input: what are some good dinners to make this week, if i like thai food?
prompt 模板:
# flake8: noqa
PREFIX = """Assistant is a large language model trained by OpenAI.Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.TOOLS:
------Assistant has access to the following tools:"""
FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:```
Thought: Do I need to use a tool? Yes
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
```When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:```
Thought: Do I need to use a tool? No
{ai_prefix}: [your response here]
```"""SUFFIX = """Begin!Previous conversation history:
{chat_history}New input: {input}
{agent_scratchpad}"""
llm_math_chain
每一步action,可以是另外一个chain,
代码示例:
# Import things that are needed generically
import os
os.environ['SERPAPI_API_KEY']="111xxxx"
os.environ['OPENAI_API_KEY']="sk-xxxxxx"
from langchain import LLMMathChain, SerpAPIWrapper
from langchain.agents import AgentType, initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain.tools import BaseTool, StructuredTool, Tool, tool
from pydantic import BaseModel, Field
llm = ChatOpenAI(temperature=0)# Load the tool configs that are needed.
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm, verbose=True)from typing import Optional, Typefrom langchain.callbacks.manager import (AsyncCallbackManagerForToolRun,CallbackManagerForToolRun,
)class CustomSearchTool(BaseTool):name = "custom_search"description = "useful for when you need to answer questions about current events"def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:"""Use the tool."""return search.run(query)async def _arun(self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:"""Use the tool asynchronously."""raise NotImplementedError("custom_search does not support async")class CalculatorInput(BaseModel):question: str = Field()class CustomCalculatorTool(BaseTool):name = "Calculator"description = "useful for when you need to answer questions about math"args_schema: Type[BaseModel] = CalculatorInputdef _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:"""Use the tool."""return llm_math_chain.run(query)async def _arun(self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:"""Use the tool asynchronously."""raise NotImplementedError("Calculator does not support async")
tools = [CustomSearchTool(), CustomCalculatorTool()]
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?"
)
prompt
Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question.Question: ${Question with math problem.}
```text
${single line mathematical expression that solves the problem}
```
...numexpr.evaluate(text)...
```output
${Output of running the code}
```
Answer: ${Answer}Begin.Question: What is 37593 * 67?
```text
37593 * 67
```
...numexpr.evaluate("37593 * 67")...
```output
2518731
```
Answer: 2518731Question: 37593^(1/5)
```text
37593**(1/5)
```
...numexpr.evaluate("37593**(1/5)")...
```output
8.222831614237718
```
Answer: 8.222831614237718Question: 19 ^ 0.43
prompt模板:
"""Translate a math problem into a expression that can be executed using Python's numexpr library. Use the output of running this code to answer the question.Question: ${{Question with math problem.}}
```text
${{single line mathematical expression that solves the problem}}
```
...numexpr.evaluate(text)...
```output
${{Output of running the code}}
```
Answer: ${{Answer}}Begin.Question: What is 37593 * 67?
```text
37593 * 67
```
...numexpr.evaluate("37593 * 67")...
```output
2518731
```
Answer: 2518731Question: 37593^(1/5)
```text
37593**(1/5)
```
...numexpr.evaluate("37593**(1/5)")...
```output
8.222831614237718
```
Answer: 8.222831614237718Question: {question}
"""
STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION
核心思想:工具如果需要多种输入,也需要将参数一起构建进prompt当中
代码示例
import os
os.environ['SERPAPI_API_KEY']="23123"
os.environ['OPENAI_API_KEY']="sk-232323"
os.environ["LANGCHAIN_TRACING"] = "true"
from langchain import OpenAI
from langchain.agents import initialize_agent, AgentTypellm = OpenAI(temperature=0)
from langchain.tools import StructuredTooldef multiplier(a: float, b: float) -> float:"""Multiply the provided floats."""return a * btool = StructuredTool.from_function(multiplier)
# Structured tools are compatible with the STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION agent type.
agent_executor = initialize_agent([tool],llm,agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,verbose=True,
)agent_executor.run("What is 3 times 4")
prompt
System: Respond to the human as helpfully and accurately as possible. You have access to the following tools:multiplier: multiplier(a: float, b: float) -> float - Multiply the provided floats., args: {{'a': {{'title': 'A', 'type': 'number'}}, 'b': {{'title': 'B', 'type': 'number'}}}}Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).Valid "action" values: "Final Answer" or multiplierProvide only ONE action per $JSON_BLOB, as shown:```
{"action": $TOOL_NAME,"action_input": $INPUT
}
```Follow this format:Question: input question to answer
Thought: consider previous and subsequent steps
Action:
```
$JSON_BLOB
```
Observation: action result
... (repeat Thought/Action/Observation N times)
Thought: I know what to respond
Action:
```
{"action": "Final Answer","action_input": "Final response to human"
}
```Begin! Reminder to ALWAYS respond with a valid json blob of a single action. Use tools if necessary. Respond directly if appropriate. Format is Action:```$JSON_BLOB```then Observation:.
Thought:
Human: What is 3 times 4This was your previous work (but I haven't seen any of it! I only see what you return as final answer):
Action:
```
{"action": "multiplier","action_input": {"a": 3, "b": 4}
}
```Observation: 12.0
Thought:
相关文章:
langchain agent
zero-shot-react-description 代码 from langchain.agents import initialize_agent from langchain.llms import OpenAI from langchain.tools import BaseTool import os os.environ[OPENAI_API_KEY]"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"# 搜索…...

Zabbix下载安装及SNMP Get使用
帮助文档:6. Zabbix Appliance 一、zabbix下载安装 1、获取Zabbix Appliance镜像 Download Zabbix appliance 2、使用该镜像创建虚拟机 3、打开虚拟机控制台自动安装,等待安装完成即可 默认配置 系统/数据库:root:zabbix Zabbix 前端&am…...

freee Programming Contest 2023(AtCoder Beginner Contest 310)
文章目录 A - Order Something Else(模拟)B - Strictly Superior(模拟)C - Reversible(模拟)D - Peaceful Teams(DFS状压)E - NAND repeatedly(普通dp)F - Make 10 Again(状态压缩概率dp&#x…...

恒运资本:概念股是什么意思
概念股是指在特定的经济布景、方针环境、职业远景或社会热点等方面具有某种特别的发展远景和投资价值的股票。在投资者心目中,概念股的危险较大,可是或许带来高于商场平均水平的收益率。那么,概念股到底是什么意思?在本文中&#…...

十九、状态模式
一、什么是状态模式 状态(State)模式的定义:对有状态的对象,把复杂的“判断逻辑”提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为。 状态模式包含以下主要角色: 环境类(…...

MySQL用navicat工具对表进行筛选查找
这个操作其实很简单,但是对于没操作的人来说,就是不会呀。所以小编出这一个详细图解,希望能够帮助到大家。话不多说看图。 第一步: 点进一张表,点击筛选。 第二步: 点击添加 第三步: 选择要…...
音视频 ffplay简单过滤器
视频旋转 ffplay -i test.mp4 -vf transpose1视频反转 ffplay test.mp4 -vf hflip ffplay test.mp4 -vf vflip视频旋转和反转 ffplay test.mp4 -vf hflip,transpose1音频变速播放 ffplay -i test.mp4 -af atempo2视频变速播放 ffplay -i test.mp4 -vf setptsPTS/2音视频同…...
索引 事务 存储引擎
################索引##################### 一、索引的概念 ●索引是一个排序的列表,在这个列表中存储着索引的值和包含这个值的数据所在行的物理地址(类似于C语言的链表通过指针指向数据记录的内存地址)。 ●使用索引后可以不用扫描全表来…...

MySQL— 基础语法大全及操作演示!!!(事务)
MySQL—— 基础语法大全及操作演示(事务) 六、事务6.1 事务简介6.2 事务操作6.2.1 未控制事务6.2.2 控制事务一6.2.3 控制事务二 6.3 事务四大特性6.4 并发事务问题6.5 事务隔离级别 MySQL— 基础语法大全及操作演示!!!…...

xsschallenge1~13通关详细教程
文章目录 XSS 挑战靶场通关level1level2level3level4level5level6level7level8level9level10level11level12level13 XSS 挑战靶场通关 level1 通过观察发现这个用户信息可以修改 那么我们直接输入攻击代码 <script>alert(/wuhu/)</script>弹框如下: …...

考生作弊行为分析算法
考生作弊行为分析系统利用pythonyolo系列网络模型算法框架,考生作弊行为分析算法利用图像处理和智能算法对考生的行为进行分析和识别,经过算法服务器的复杂计算和逻辑判断,算法将根据考生行为的特征和规律,判定是否存在作弊行为。…...
Python 操作 Redis 数据库介绍
Redis 作为常用的 NoSql 数据库,主要用于缓存数据,提高数据读取效率,那在 Python 中应该如果连接和操作 Redis 呢?今天就为大概简单介绍下,在 Python 中操作 Redis 常用命令。 安装 redis 首先还是需要先安装 redis …...
十年JAVA搬砖路——软件工程概述
软件工程是一门关注软件开发过程的学科,它涉及到软件的设计、开发、测试、部署和维护等方面。软件工程的目标是通过系统化的方法和工具,以确保软件项目能够按时、按预算和按要求完成。 • 软件工程的7个基本概念: 软件生命周期:软…...

前后端项目部署上线详细笔记
部署 参考文章:如何部署网站?来比比谁的方法多 - 哔哩哔哩大家好,我是鱼皮,不知道朋友们有没有试着部署过自己开发的网站呢?其实部署网站非常简单,而且有非常多的花样。这篇文章就给大家分享几种主流的前端…...

Android 蓝牙开发( 二 )
前言 上一篇文章给大家分享了Android蓝牙的基础知识和基础用法,不过上一篇都是一些零散碎片化的程序,这一篇给大家分享Android蓝牙开发实战项目的初步使用 效果演示 : Android蓝牙搜索,配对,连接,通信 Android蓝牙实…...

C#调用barTender打印标签示例
使用的电脑需要先安装BarTender 我封装成一个类 using System; using System.Windows.Forms;namespace FT_Tools {public class SysContext{public static BarTender.Application btapp new BarTender.Application();public static BarTender.Format btFormat;public void Q…...

Spring——Spring读取文件
文章目录 1.通过 value 读取比较简单的配置信息2.通过ConfigurationProperties读取并与 bean 绑定3.通过ConfigurationProperties读取并校验4. PropertySource 读取指定 properties 文件5.题外话:Spring加载配置文件的优先级 很多时候我们需要将一些常用的配置信息比如阿里云os…...

这是一条求助贴(postman测试的时候一直是404)
看到这个问题是404的时候总感觉不该求助大家,404多常见一看就是简单的路径问题,我的好像不是,我把我的问题奉上。 首先我先给出我的url http://10.3.22.195:8080/escloud/rest/escloud_contentws/permissionStatistics/jc-haojl/sz 这是我…...

信号完整性分析基础知识之有损传输线、上升时间衰减和材料特性(四):有损传输线建模
传输线中信号衰减的两个损耗过程是通过信号和返回路径导体的串联电阻以及通过有损耗介电材料的分流电阻。这两个电阻器的电阻都与频率相关。 值得注意的是,理想电阻器的电阻随频率恒定。我们已经证明,在理想的有损传输线中,用于描述损耗的两个…...

elk日志收集系统
目录 前言 一、概述 二、案例 (一)、环境配置 安装node1与node2节点的elasticsearch node1的elasticsearch-head插件 (二)、node1服务器安装logstash 测试1: 标准输入与输出 测试2:使用rubydebug解…...
在鸿蒙HarmonyOS 5中实现抖音风格的点赞功能
下面我将详细介绍如何使用HarmonyOS SDK在HarmonyOS 5中实现类似抖音的点赞功能,包括动画效果、数据同步和交互优化。 1. 基础点赞功能实现 1.1 创建数据模型 // VideoModel.ets export class VideoModel {id: string "";title: string ""…...

2025年能源电力系统与流体力学国际会议 (EPSFD 2025)
2025年能源电力系统与流体力学国际会议(EPSFD 2025)将于本年度在美丽的杭州盛大召开。作为全球能源、电力系统以及流体力学领域的顶级盛会,EPSFD 2025旨在为来自世界各地的科学家、工程师和研究人员提供一个展示最新研究成果、分享实践经验及…...
在 Nginx Stream 层“改写”MQTT ngx_stream_mqtt_filter_module
1、为什么要修改 CONNECT 报文? 多租户隔离:自动为接入设备追加租户前缀,后端按 ClientID 拆分队列。零代码鉴权:将入站用户名替换为 OAuth Access-Token,后端 Broker 统一校验。灰度发布:根据 IP/地理位写…...

多模态大语言模型arxiv论文略读(108)
CROME: Cross-Modal Adapters for Efficient Multimodal LLM ➡️ 论文标题:CROME: Cross-Modal Adapters for Efficient Multimodal LLM ➡️ 论文作者:Sayna Ebrahimi, Sercan O. Arik, Tejas Nama, Tomas Pfister ➡️ 研究机构: Google Cloud AI Re…...
全面解析各类VPN技术:GRE、IPsec、L2TP、SSL与MPLS VPN对比
目录 引言 VPN技术概述 GRE VPN 3.1 GRE封装结构 3.2 GRE的应用场景 GRE over IPsec 4.1 GRE over IPsec封装结构 4.2 为什么使用GRE over IPsec? IPsec VPN 5.1 IPsec传输模式(Transport Mode) 5.2 IPsec隧道模式(Tunne…...
【Go语言基础【13】】函数、闭包、方法
文章目录 零、概述一、函数基础1、函数基础概念2、参数传递机制3、返回值特性3.1. 多返回值3.2. 命名返回值3.3. 错误处理 二、函数类型与高阶函数1. 函数类型定义2. 高阶函数(函数作为参数、返回值) 三、匿名函数与闭包1. 匿名函数(Lambda函…...
Java编程之桥接模式
定义 桥接模式(Bridge Pattern)属于结构型设计模式,它的核心意图是将抽象部分与实现部分分离,使它们可以独立地变化。这种模式通过组合关系来替代继承关系,从而降低了抽象和实现这两个可变维度之间的耦合度。 用例子…...
LangFlow技术架构分析
🔧 LangFlow 的可视化技术栈 前端节点编辑器 底层框架:基于 (一个现代化的 React 节点绘图库) 功能: 拖拽式构建 LangGraph 状态机 实时连线定义节点依赖关系 可视化调试循环和分支逻辑 与 LangGraph 的深…...
绕过 Xcode?使用 Appuploader和主流工具实现 iOS 上架自动化
iOS 应用的发布流程一直是开发链路中最“苹果味”的环节:强依赖 Xcode、必须使用 macOS、各种证书和描述文件配置……对很多跨平台开发者来说,这一套流程并不友好。 特别是当你的项目主要在 Windows 或 Linux 下开发(例如 Flutter、React Na…...
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
文章目录 1. 题目描述1.1 链表节点定义 2. 理解题目2.1 问题可视化2.2 核心挑战 3. 解法一:HashSet 标记访问法3.1 算法思路3.2 Java代码实现3.3 详细执行过程演示3.4 执行结果示例3.5 复杂度分析3.6 优缺点分析 4. 解法二:Floyd 快慢指针法(…...