L1 Simple_ReAct_Agent

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

Basic ReAct Agent(manual action)

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
client = OpenAI(api_key=OPENAI_API_KEY,base_url="https://api.chatanywhere.tech/v1"
)
chat_completion = client.chat.completions.create(model="gpt-3.5-turbo",messages=[{"role": "user", "content": "Hello world"}]
)
chat_completion.choices[0].message.content
'Hello! How can I assist you today?'
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()
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
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
}
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
result = average_dog_weight("Toy Poodle")
result
'a toy poodles average weight is 7 lbs'
next_prompt = "Observation: {}".format(result)
abot(next_prompt)
'Answer: A Toy Poodle weighs 7 lbs'
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

abot = Agent(prompt)
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'
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
next_prompt = "Observation: {}".format(average_dog_weight("Border Collie"))
print(next_prompt)
Observation: a Border Collies weight is 37 lbs
abot(next_prompt)
'Action: average_dog_weight: Scottish Terrier\nPAUSE'
next_prompt = "Observation: {}".format(average_dog_weight("Scottish Terrier"))
print(next_prompt)
Observation: Scottish Terriers average 20 lbs
abot(next_prompt)
'Action: calculate: 37 + 20\nPAUSE'
next_prompt = "Observation: {}".format(eval("37 + 20"))
print(next_prompt)
Observation: 57
abot(next_prompt)
'Answer: The combined weight of a Border Collie and a Scottish Terrier is 57 lbs'

Add loop

action_re = re.compile(r'^Action: (\w+): (.*)$')
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
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.mzph.cn/news/870867.shtml

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

相关文章

pip install .自己构建工程文件报错error: subprocess-exited-with-error解决办法

有时我们直接使用pip install xxx安装某个三方文件时候会发现安装不了,会报各种问题。 这时候我们只能通过下载源码自己手动编译。 等我们下好源码开始编译的时候又会出现很多问题。 下面就举一个栗子作为解决问题的思路: 比如我我想要安装diff-gaussian-rasterization,直…

python 66 个冷知识 0712

66个有趣的Python冷知识 字典合并 从Python 3.9开始&#xff0c;可以使用 | 操作符合并字典。 多继承 Python支持多继承&#xff0c;类可以继承多个父类。 ABC模块 abc 模块提供了定义抽象基类的工具。 泛型 typing 模块提供了泛型支持。 类型别名 使用 typing 模块可以创建…

DP讨论——设计模式怎么来的?

眼中没有设计模式&#xff0c;代码里就找不到设计模式 几年前还在搞c开发&#xff0c;觉得设计模式离我太遥远&#xff0c;而且觉得设计模式太复杂太高大上&#xff0c;比较恐惧。 后来接触了oopc&#xff08;接触了rtthread整个都是oopc实现的rtos&#xff09;&#xff0c;再…

LTE系统OFDM符号持续时间计算

LTE系统OFDM符号持续时间计算 给定等式&#xff1a;7个OFDM符号的持续时间 0.5ms(1个slot) - 160Ts - 6144*Ts 其中&#xff1a; 1个slot 0.5msTs是LTE系统的基本时间单位 步骤分解 理解时间资源结构&#xff1a; 1个无线帧 10ms1个子帧 1ms 2个slot1个slot 0.5ms1个…

Spring Boot Vue 毕设系统讲解 9 【Spark】

SuppressWarnings("serial") Configuration ConfigurationProperties(prefix"spark") public class SparkConfig implements Serializable {//spark的安装地址private String sparkHome ".";//应用的名称private String appName "mySpar…

图像识别和目标检测在超市电子秤上的应用

目录 前言深度学习的目标检测图像识别技术视觉秤的优势其他应用场景中的技术应用未来展望 前言 随着科技的不断发展&#xff0c;电子秤在生鲜超市中的应用也在不断升级。传统的电子秤需要打秤人员手动输入秤码&#xff0c;这不仅耗时费力&#xff0c;还需要大量的培训以记住各…

Rust编程-泛型、Trait和生命周期

泛型&#xff1a; 泛型是类型编程中的一种工具。本质上是类型的变量&#xff0c;目的是提高代码的复用。泛型是 具体类型或其他属性的抽象替代。 为了复用&#xff0c;我们会使用函数将功能封装&#xff0c;同样&#xff0c;泛型也是为了复用&#xff0c;只不过是为了类型的复用…

工业大数据是什么?应用工业大数据时面临哪些挑战?

在当今快速发展的工业领域&#xff0c;大数据已成为推动企业转型升级的核心动力。工业大数据&#xff0c;以其独特的价值和潜力&#xff0c;正逐渐改变着传统的生产、管理和决策模式。然而&#xff0c;伴随着大数据的快速发展&#xff0c;一系列挑战也随之浮现。本文将深入探讨…

算法日常练习

对于这个题&#xff0c;如何处理同一个方向的问题&#xff0c;且对于同一组的如果间隔太大如何实现离散化 #include<bits/stdc.h> using namespace std;#define int long long typedef long long ll; map<pair<int,int>,vector<pair<ll,ll>>> mp…

关于机械键盘的购买,该怎么选择?

一.关于轴体的选择。 1.青轴&#xff1a;青轴是机械键盘最有段落感的轴&#xff0c;声音比较大&#xff0c;以吵死人别人著称。有人将其比喻为Cherry的春天&#xff0c;爽快清脆的段落感如春天般舒畅。适合在宿舍、咖啡厅&#xff0c;图书馆使用。&#xff08;我装的 &#xf…

C++ STL std::lexicographical_compare用法和实现

一&#xff1a;功能 按字典顺序比较两个序列&#xff0c;判断第一个序列是否小于(或大于)第二个序列 二&#xff1a;用法 #include <compare> #include <vector> #include <string> #include <algorithm> #include <iostream> #include <fo…

linux源码安装mysql8.0的小白教程

1.下载8.x版本的mysql MySQL :: Download MySQL Community Server (Archived Versions) 2.安装linux 我安装的是Rocky Linux8.6 3.设置ip地址,方便远程连接 使用nmcli或者nmtui设置或修改ip地址 4.使用远程连接工具MobaXterm操作: (1)将mysql8版本的压缩包上传到mybaxterm…

数据建设实践之大数据平台(三)安装hadoop

安装hadoop 上传安装文件到/opt/software目录并解压 [bigdata@node101 software]$ tar -zxvf hadoop-3.3.5.tar.gz -C /opt/services/ 配置环境变量 [bigdata@node101 ~]$ sudo vim /etc/profile.d/bigdata_env.sh export JAVA_HOME=/opt/services/jdk1.8.0_161 export ZK…

一图看懂 | 蓝卓油气行业解决方案

我国是全球最大的能源消费国&#xff0c;保障国家能源安全是我国能源发展的首要任务&#xff0c;油气作为我国能源体系的重要组成部分&#xff0c;是支撑我国工业和经济社会发展的基础和“压舱石&#xff0c;也是必须筑牢的能源安全底线。 蓝卓根据油气田行业发展趋势&#xf…

前端实现一键复制功能

1、下载插件 npm i vue-clipboard32.0.0 2、在需要复制的文件中引入插件并使用&#xff1a; JS: import useClipboard from "vue-clipboard3"; const { toClipboard } useClipboard(); HTML: <el-tooltip content"复制内容" placement"top&…

算法面试题_字节

问题一&#xff1a;Transfomer矩阵维度分析及MultiHead详解&#xff1a; 细致链接1 细致链接2 问题二&#xff1a;transformer的结构&#xff0c;流程&#xff0c;维度变换&#xff0c;encoder&#xff0c;decoder&#xff1a; 多头维度怎么变化&#xff1a;先在q&#xff0…

自然语言处理基本概念

自然语言处理基本概念 所有学习循环神经网络的人都是看这一篇博客长大的&#xff1a; https://colah.github.io/posts/2015-08-Understanding-LSTMs/ import jieba import torch from torch import nns1 "我吃饭了&#xff01;" s2 "今天天气很好&#xff01…

电脑录屏软件哪个效果最好 怎么一边录屏一边直播 电脑录屏软件好用免费推荐

随着科技的发展&#xff0c;电脑的更新迭代也越来越快&#xff0c;各项功能的进步与完善使得人们的工作和生活越来越离不开电脑&#xff0c;其中录屏功能就很好的体现了网络的便利&#xff0c;人们可以将在电脑画面的变化通过录屏功能记录下来&#xff0c;以便后续学习和回顾。…

基于STM32设计的智能手环(ESP8266+华为云IOT)178

基于STM32设计的智能手环(178) 文章目录 一、前言1.1 项目介绍【1】项目功能介绍【2】项目硬件模块组成【3】ESP8266工作模式配置【4】Android手机APP开发思路【5】项目模块划分1.2 项目功能需求(1)生理参数监测(2)计步功能(3)GPS定位(4)时间显示(5)OLED显示屏展示(…

xlwings 链接到 指定sheet 从别的 excel 复制 sheet 到指定 sheet

重点 可以参考 宏录制 cell sheet.range(G4)cell.api.Hyperlinks.Add(Anchorcell.api, Address"", SubAddress"001-000-02301!A1")def deal_excel(self):with xw.App(visibleTrue) as app:wb app.books.open(self.summary_path, update_linksFalse)sheet…