当前位置: 首页 > news >正文

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)模式的定义:对有状态的对象,把复杂的“判断逻辑”提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为。 状态模式包含以下主要角色: 环境类&#xff08…...

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— 基础语法大全及操作演示!!&#xff01…...

xsschallenge1~13通关详细教程

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

考生作弊行为分析算法

考生作弊行为分析系统利用pythonyolo系列网络模型算法框架&#xff0c;考生作弊行为分析算法利用图像处理和智能算法对考生的行为进行分析和识别&#xff0c;经过算法服务器的复杂计算和逻辑判断&#xff0c;算法将根据考生行为的特征和规律&#xff0c;判定是否存在作弊行为。…...

Python 操作 Redis 数据库介绍

Redis 作为常用的 NoSql 数据库&#xff0c;主要用于缓存数据&#xff0c;提高数据读取效率&#xff0c;那在 Python 中应该如果连接和操作 Redis 呢&#xff1f;今天就为大概简单介绍下&#xff0c;在 Python 中操作 Redis 常用命令。 安装 redis 首先还是需要先安装 redis …...

十年JAVA搬砖路——软件工程概述

软件工程是一门关注软件开发过程的学科&#xff0c;它涉及到软件的设计、开发、测试、部署和维护等方面。软件工程的目标是通过系统化的方法和工具&#xff0c;以确保软件项目能够按时、按预算和按要求完成。 • 软件工程的7个基本概念&#xff1a; 软件生命周期&#xff1a;软…...

前后端项目部署上线详细笔记

部署 参考文章&#xff1a;如何部署网站&#xff1f;来比比谁的方法多 - 哔哩哔哩大家好&#xff0c;我是鱼皮&#xff0c;不知道朋友们有没有试着部署过自己开发的网站呢&#xff1f;其实部署网站非常简单&#xff0c;而且有非常多的花样。这篇文章就给大家分享几种主流的前端…...

Android 蓝牙开发( 二 )

前言 上一篇文章给大家分享了Android蓝牙的基础知识和基础用法&#xff0c;不过上一篇都是一些零散碎片化的程序&#xff0c;这一篇给大家分享Android蓝牙开发实战项目的初步使用 效果演示 : Android蓝牙搜索&#xff0c;配对&#xff0c;连接&#xff0c;通信 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的时候总感觉不该求助大家&#xff0c;404多常见一看就是简单的路径问题&#xff0c;我的好像不是&#xff0c;我把我的问题奉上。 首先我先给出我的url http://10.3.22.195:8080/escloud/rest/escloud_contentws/permissionStatistics/jc-haojl/sz 这是我…...

信号完整性分析基础知识之有损传输线、上升时间衰减和材料特性(四):有损传输线建模

传输线中信号衰减的两个损耗过程是通过信号和返回路径导体的串联电阻以及通过有损耗介电材料的分流电阻。这两个电阻器的电阻都与频率相关。 值得注意的是&#xff0c;理想电阻器的电阻随频率恒定。我们已经证明&#xff0c;在理想的有损传输线中&#xff0c;用于描述损耗的两个…...

elk日志收集系统

目录 前言 一、概述 二、案例 &#xff08;一&#xff09;、环境配置 安装node1与node2节点的elasticsearch node1的elasticsearch-head插件 &#xff08;二&#xff09;、node1服务器安装logstash 测试1&#xff1a; 标准输入与输出 测试2&#xff1a;使用rubydebug解…...

观成科技:隐蔽隧道工具Ligolo-ng加密流量分析

1.工具介绍 Ligolo-ng是一款由go编写的高效隧道工具&#xff0c;该工具基于TUN接口实现其功能&#xff0c;利用反向TCP/TLS连接建立一条隐蔽的通信信道&#xff0c;支持使用Let’s Encrypt自动生成证书。Ligolo-ng的通信隐蔽性体现在其支持多种连接方式&#xff0c;适应复杂网…...

FFmpeg 低延迟同屏方案

引言 在实时互动需求激增的当下&#xff0c;无论是在线教育中的师生同屏演示、远程办公的屏幕共享协作&#xff0c;还是游戏直播的画面实时传输&#xff0c;低延迟同屏已成为保障用户体验的核心指标。FFmpeg 作为一款功能强大的多媒体框架&#xff0c;凭借其灵活的编解码、数据…...

STM32+rt-thread判断是否联网

一、根据NETDEV_FLAG_INTERNET_UP位判断 static bool is_conncected(void) {struct netdev *dev RT_NULL;dev netdev_get_first_by_flags(NETDEV_FLAG_INTERNET_UP);if (dev RT_NULL){printf("wait netdev internet up...");return false;}else{printf("loc…...

将对透视变换后的图像使用Otsu进行阈值化,来分离黑色和白色像素。这句话中的Otsu是什么意思?

Otsu 是一种自动阈值化方法&#xff0c;用于将图像分割为前景和背景。它通过最小化图像的类内方差或等价地最大化类间方差来选择最佳阈值。这种方法特别适用于图像的二值化处理&#xff0c;能够自动确定一个阈值&#xff0c;将图像中的像素分为黑色和白色两类。 Otsu 方法的原…...

苍穹外卖--缓存菜品

1.问题说明 用户端小程序展示的菜品数据都是通过查询数据库获得&#xff0c;如果用户端访问量比较大&#xff0c;数据库访问压力随之增大 2.实现思路 通过Redis来缓存菜品数据&#xff0c;减少数据库查询操作。 缓存逻辑分析&#xff1a; ①每个分类下的菜品保持一份缓存数据…...

sqlserver 根据指定字符 解析拼接字符串

DECLARE LotNo NVARCHAR(50)A,B,C DECLARE xml XML ( SELECT <x> REPLACE(LotNo, ,, </x><x>) </x> ) DECLARE ErrorCode NVARCHAR(50) -- 提取 XML 中的值 SELECT value x.value(., VARCHAR(MAX))…...

VTK如何让部分单位不可见

最近遇到一个需求&#xff0c;需要让一个vtkDataSet中的部分单元不可见&#xff0c;查阅了一些资料大概有以下几种方式 1.通过颜色映射表来进行&#xff0c;是最正规的做法 vtkNew<vtkLookupTable> lut; //值为0不显示&#xff0c;主要是最后一个参数&#xff0c;透明度…...

代理篇12|深入理解 Vite中的Proxy接口代理配置

在前端开发中,常常会遇到 跨域请求接口 的情况。为了解决这个问题,Vite 和 Webpack 都提供了 proxy 代理功能,用于将本地开发请求转发到后端服务器。 什么是代理(proxy)? 代理是在开发过程中,前端项目通过开发服务器,将指定的请求“转发”到真实的后端服务器,从而绕…...

七、数据库的完整性

七、数据库的完整性 主要内容 7.1 数据库的完整性概述 7.2 实体完整性 7.3 参照完整性 7.4 用户定义的完整性 7.5 触发器 7.6 SQL Server中数据库完整性的实现 7.7 小结 7.1 数据库的完整性概述 数据库完整性的含义 正确性 指数据的合法性 有效性 指数据是否属于所定…...

【Linux手册】探秘系统世界:从用户交互到硬件底层的全链路工作之旅

目录 前言 操作系统与驱动程序 是什么&#xff0c;为什么 怎么做 system call 用户操作接口 总结 前言 日常生活中&#xff0c;我们在使用电子设备时&#xff0c;我们所输入执行的每一条指令最终大多都会作用到硬件上&#xff0c;比如下载一款软件最终会下载到硬盘上&am…...