L1 Simple_ReAct_Agent

news/2024/9/18 23:10:27/ 标签: python, 人工智能

参考自https://www.deeplearning.ai/short-courses/ai-agents-in-langgraph,以下为代码的实现。

Basic ReAct Agent(manual action)

python">import openai
import re
import httpx
import os
from dotenv import load_dotenv, find_dotenvOPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
from openai import OpenAI
python">client = OpenAI(api_key=OPENAI_API_KEY,base_url="https://api.chatanywhere.tech/v1"
)
python">chat_completion = client.chat.completions.create(model="gpt-3.5-turbo",messages=[{"role": "user", "content": "Hello world"}]
)
python">chat_completion.choices[0].message.content
'Hello! How can I assist you today?'
python">prompt = """
You run in a loop of Thought, Action, PAUSE, Observation.
At the end of the loop you output an Answer
Use Thought to describe your thoughts about the question you have been asked.
Use Action to run one of the actions available to you - then return PAUSE.
Observation will be the result of running those actions.Your available actions are:calculate:
e.g. calculate: 4 * 7 / 3
Runs a calculation and returns the number - uses Python so be sure to use floating point syntax if necessaryaverage_dog_weight:
e.g. average_dog_weight: Collie
returns average weight of a dog when given the breedExample session:Question: How much does a Bulldog weigh?
Thought: I should look the dogs weight using average_dog_weight
Action: average_dog_weight: Bulldog
PAUSEYou will be called again with this:Observation: A Bulldog weights 51 lbsYou then output:Answer: A bulldog weights 51 lbs
""".strip()
python">class Agent:def __init__(self, system=""):self.system = systemself.messages = []if self.system:self.messages.append({"role": "system", "content": system})def __call__(self, message):self.messages.append({"role": "user", "content": message})result = self.execute()self.messages.append({"role": "assistant", "content": result})return resultdef execute(self):completion = client.chat.completions.create(model="gpt-3.5-turbo",temperature=0,messages=self.messages)return completion.choices[0].message.content
python">def calculate(what):return eval(what)def average_dog_weight(name):if name in "Scottish Terrier":return("Scottish Terriers average 20 lbs")elif name in "Border Collie":return("a Border Collies weight is 37 lbs")elif name in "Toy Poodle":return("a toy poodles average weight is 7 lbs")else:return("An average dog weights 50 lbs")known_actions = {"calculate": calculate,"average_dog_weight": average_dog_weight
}
python">abot = Agent(prompt)
result = abot("How much does a toy poodle weigh?")
print(result)
Thought: I should look up the average weight of a Toy Poodle using the average_dog_weight action.
Action: average_dog_weight: Toy Poodle
PAUSE
python">result = average_dog_weight("Toy Poodle")
python">result
'a toy poodles average weight is 7 lbs'
python">next_prompt = "Observation: {}".format(result)
python">abot(next_prompt)
'Answer: A Toy Poodle weighs 7 lbs'
python">abot.messages
[{'role': 'system','content': 'You run in a loop of Thought, Action, PAUSE, Observation.\nAt the end of the loop you output an Answer\nUse Thought to describe your thoughts about the question you have been asked.\nUse Action to run one of the actions available to you - then return PAUSE.\nObservation will be the result of running those actions.\n\nYour available actions are:\n\ncalculate:\ne.g. calculate: 4 * 7 / 3\nRuns a calculation and returns the number - uses Python so be sure to use floating point syntax if necessary\n\naverage_dog_weight:\ne.g. average_dog_weight: Collie\nreturns average weight of a dog when given the breed\n\nExample session:\n\nQuestion: How much does a Bulldog weigh?\nThought: I should look the dogs weight using average_dog_weight\nAction: average_dog_weight: Bulldog\nPAUSE\n\nYou will be called again with this:\n\nObservation: A Bulldog weights 51 lbs\n\nYou then output:\n\nAnswer: A bulldog weights 51 lbs'},{'role': 'user', 'content': 'How much does a toy poodle weigh?'},{'role': 'assistant','content': 'Thought: I should look up the average weight of a Toy Poodle using the average_dog_weight action.\nAction: average_dog_weight: Toy Poodle\nPAUSE'},{'role': 'user','content': 'Observation: a toy poodles average weight is 7 lbs'},{'role': 'assistant', 'content': 'Answer: A Toy Poodle weighs 7 lbs'}]

A little more complex question

python">abot = Agent(prompt)
python">question = """I have 2 dogs, a border collie and a scottish terrier. \
What is their combined weight"""
abot(question)
'Thought: I can find the average weight of a Border Collie and a Scottish Terrier using the average_dog_weight action, then calculate their combined weight.\n\nAction: average_dog_weight: Border Collie\nPAUSE'
python">print(abot.messages[-1]['content'])
Thought: I can find the average weight of a Border Collie and a Scottish Terrier using the average_dog_weight action, then calculate their combined weight.Action: average_dog_weight: Border Collie
PAUSE
python">next_prompt = "Observation: {}".format(average_dog_weight("Border Collie"))
print(next_prompt)
Observation: a Border Collies weight is 37 lbs
python">abot(next_prompt)
'Action: average_dog_weight: Scottish Terrier\nPAUSE'
python">next_prompt = "Observation: {}".format(average_dog_weight("Scottish Terrier"))
print(next_prompt)
Observation: Scottish Terriers average 20 lbs
python">abot(next_prompt)
'Action: calculate: 37 + 20\nPAUSE'
python">next_prompt = "Observation: {}".format(eval("37 + 20"))
print(next_prompt)
Observation: 57
python">abot(next_prompt)
'Answer: The combined weight of a Border Collie and a Scottish Terrier is 57 lbs'

Add loop

python">action_re = re.compile(r'^Action: (\w+): (.*)$')
python">def query(question, max_turns=5):i = 0bot = Agent(prompt)next_prompt = questionwhile i < max_turns:i += 1result = bot(next_prompt)print(result)actions = [action_re.match(a) for a in result.split('\n') if action_re.match(a)] if actions:# There is an action to runaction, action_input = actions[0].groups()if action not in known_actions:raise Exception("Unknown action: {}: {}".format(action, action_input))print(" -- running {} {}".format(action, action_input))observation = known_actions[action](action_input)print("Observation:", observation)next_prompt = "Observation: {}".format(observation)else:return
python">question = """I have 2 dogs, a border collie and a scottish terrier. \
What is their combined weight"""
query(question)
Thought: I can find the average weight of a Border Collie and a Scottish Terrier using the average_dog_weight action, then calculate their combined weight.Action: average_dog_weight: Border Collie
PAUSE-- running average_dog_weight Border Collie
Observation: a Border Collies weight is 37 lbs
Action: average_dog_weight: Scottish Terrier
PAUSE-- running average_dog_weight Scottish Terrier
Observation: Scottish Terriers average 20 lbs
Action: calculate: 37 + 20
PAUSE-- running calculate 37 + 20
Observation: 57
Answer: The combined weight of a Border Collie and a Scottish Terrier is 57 lbs

http://www.ppmy.cn/news/1474582.html

相关文章

逻辑回归模型(非回归问题,而是解决二分类问题)

目录&#xff1a; 一、Sigmoid激活函数&#xff1a;二、逻辑回归介绍&#xff1a;三、决策边界四、逻辑回归模型训练过程&#xff1a;1.训练目标&#xff1a;2.梯度下降调整参数&#xff1a; 一、Sigmoid激活函数&#xff1a; Sigmoid函数是构建逻辑回归模型的重要激活函数&am…

容联云发布容犀大模型应用,重塑企业“营销服”|WAIC 2024

7月6日&#xff0c;在2024世界人工智能大会上&#xff0c;容联云成功举办主题为“数智聚合 产业向上”的生成式应用与大模型商业化实践论坛。 论坛上&#xff0c;容联云发布了容犀智能大模型应用升级&#xff0c;该系列应用包括容犀Agent Copilot、容犀Knowledge Copilot、容犀…

《C++设计模式》状态模式

文章目录 一、前言二、实现一、UML类图二、实现 一、前言 状态模式理解最基本上的我觉得应该也是够用了&#xff0c;实际用的话&#xff0c;也应该用的是Boost.MSM状态机。 相关代码可以在这里&#xff0c;如有帮助给个star&#xff01;AidenYuanDev/design_patterns_in_mode…

嵌入式Qt开发C++编程基础部分万字总结

嵌入式Qt开发C基础编程 文章目录 嵌入式Qt开发C基础编程1、初识C2、数据类型、运算符和表达式数据类型运算符表达式 3、控制结构1. 条件语句if-elseswitch 2. 循环语句forwhiledo-while 3. 跳转语句breakcontinuegoto&#xff08;不推荐使用&#xff09; 4、数组、指针、引用和…

网络协议 | 计算机网络基础学习笔记

一、网络硬件 关于计算机网络&#xff0c;没有一种被普遍接受的分类方法&#xff0c;但有两个因素非常重要&#xff1a;传输技术和距离尺度 目前普遍使用的传输技术有两种&#xff1a; &#xff08;1&#xff09;广播式连接 &#xff08;2&#xff09;点到点连接 广播式网络…

Hadoop-16-Hive HiveServer2 HS2 允许客户端远程执行HiveHQL HCatalog 集群规划 实机配置运行

章节内容 上一节我们完成了&#xff1a; Metastore的基础概念配置模式&#xff1a;内嵌模式、本地模式、远程模式实机配置远程模式 并测试 背景介绍 这里是三台公网云服务器&#xff0c;每台 2C4G&#xff0c;搭建一个Hadoop的学习环境&#xff0c;供我学习。 之前已经在 V…

python工作中遇到的坑

1. 字典拷贝 有些场景下&#xff0c;需要对字典拷贝一个副本。这个副本用于保存原始数据&#xff0c;然后原来的字典去参与其他运算&#xff0c;或者作为参数传递给一些函数。 例如&#xff0c; >>> dict_a {"name": "John", "address&q…

vue使用 “xlsx-style“: “^0.8.13“ 报错

关于jszip not a constructor报错配置config.js文件后可能还报错的问题&#xff1a; 在node_modules处找到node_modules\xlsx-style\xlsx.js 文件。 将 if(typeof jszip undefined) jszip require(./jszip).JSZip;(应该在xlsx.js文件1339行左右) 替换成 if(typeof jszip und…

黑马点评商户缓存查询作业——Redis中查询商户类型

记录下自己在gpt帮助下完成的第一个需求~~~ 1. ShopTypeController 2. IShopTypeService 3. ShopTypeServiceImpl&#xff08;模仿ShopServiceImpl来写的&#xff09; 一共分为“1.redis中查询缓存”→“2.判断缓存是否存在&#xff0c;存在直接返回”→“3.缓存不存在则去查数…

在Windows环境下安装Python 3.11的步骤

在Windows环境下安装Python 3.11的步骤相对直接。下面是详细的安装教程&#xff1a; 第一步&#xff1a;下载Python 3.11安装程序 访问Python官方网站的下载页面&#xff1a;https://www.python.org/downloads/在页面中找到适用于Windows的Python 3.11版本&#xff0c;点击下…

《基于 Kafka + Flink + ES 实现危急值处理措施推荐和范围校准》

&#x1f4e2; 大家好&#xff0c;我是 【战神刘玉栋】&#xff0c;有10多年的研发经验&#xff0c;致力于前后端技术栈的知识沉淀和传播。 &#x1f497; &#x1f33b; 近期刚转战 CSDN&#xff0c;会严格把控文章质量&#xff0c;绝不滥竽充数&#xff0c;欢迎多多交流。&am…

了解安全端口

安全端口的定义和重要性 安全端口是指在网络通信中&#xff0c;用于特定服务或应用程序的端口&#xff0c;这些端口通常被设计为在网络层面提供额外的安全性。安全端口的选择和配置对于保护网络资源免受未经授权的访问和攻击至关重要。 常见的安全端口及其用途 以下是一些常见…

【Java]认识泛型

包装类 在Java中&#xff0c;由于基本类型不是继承自Object&#xff0c;为了在泛型代码中可以支持基本类型&#xff0c;Java给每个基本类型都对应了一个包装类型。 除了 Integer 和 Character&#xff0c; 其余基本类型的包装类都是首字母大写。 泛型 泛型是在JDK1.5引入的…

python操作SQLite3数据库进行增删改查

python操作SQLite3数据库进行增删改查 1、创建SQLite3数据库 可以通过Navicat图形化软件来创建: 2、创建表 利用Navicat图形化软件来创建: 存储在 SQLite 数据库中的每个值(或是由数据库引擎所操作的值)都有一个以下的存储类型: NULL. 值是空值。 INTEGER. 值是有符…

数据库语言 GQL

什么是数据库语言 GQL&#xff1f; 一种针对属性图数据库语言的新标准&#xff0c;ISO/IEC 39075 信息技术—数据库语言—GQL&#xff0c;刚刚发布1。但GQL是什么&#xff1f;这个标准包含哪些内容&#xff1f; 这个新标准由国际标准委员会ISO/IEC JTC1 SC32 WG3 数据库语言小…

传言称 iPhone 16 Pro 将支持 40W 快速充电和 20W MagSafe

目前&#xff0c;iPhone 15 和 iPhone 15 Pro 机型使用合适的 USB-C 电源适配器可实现高达 27W 的峰值充电速度&#xff0c;而 Apple 和授权第三方的官方 MagSafe 充电器可以高达 15W 的功率为 iPhone 15 机型进行无线充电。所有四款 iPhone 15 机型均可使用 20W 或更高功率的电…

什么是区块链的“智能合约”

区块链的“智能合约”是一种存储在区块链上的计算机协议&#xff0c;它能够自动执行合约条款&#xff0c;并在满足预设条件时自动执行相关操作。智能合约通过编程语言&#xff08;如Solidity&#xff09;编写&#xff0c;可以在去中心化的环境中运行&#xff0c;无需人工干预。…

frameworks 之Zygote

frameworks 之Zygote Zygote.rc 解析Zygote 启动ZygoteInit.javaZygote.cppLiunx fork Zygote 中文意思为受精卵。 和其意思一样&#xff0c;该功能负责android系统孵化service 和 app 进程。 本文讲解Zygote的大概流程。涉及的相同的类&#xff0c;如下所示 system/core/rootd…

Python图形用户界面的文本文件加密工具

Python图形用户界面的文本文件加密工具 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-x5oEvdLE-1720676762602)(https://i-blog.csdnimg.cn/direct/ddf0cd975b2d48a9a2f3b35c55e00add.png)] 设计方案 DES.py DESAlgorithm 类负责管理密钥并提供…

FlutterWeb渲染模式及提速

背景 在使用Flutter Web开发的网站过程中&#xff0c;常常会遇到不同浏览器之间的兼容性问题。例如&#xff0c;在Google浏览器中动画和交互都非常流畅&#xff0c;但在360浏览器中却会出现卡顿现象&#xff1b;在Google浏览器中动态设置图标颜色正常显示&#xff0c;而在Safa…