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/pingmian/43087.shtml

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

相关文章

java 实现人脸特征提取

1. 安装必要的库 确保你已经安装了JPEG库、BLAS和LAPACK库。在Ubuntu或Debian系统上&#xff0c;可以使用以下命令安装&#xff1a; sudo apt-get update sudo apt-get install libjpeg-dev libblas-dev liblapack-dev 在CentOS或Fedora系统上&#xff0c;可以使用以下命令安…

Numpy数组基础操作

1.创建数组 import numpy as np # ————创建数组———— np.array([1,2,3,4]) np.array(range(10))# 迭代对象 np.array([i for i in range(10) if i%20]) #列表&#xff0c;[]列表推导式返回列表 np.array([i for i in range(10) if i%20]) #()# 生成器&#xff0c;列表推…

Pytorch框架权重文件转onnx格式

Pytorch框架权重文件转onnx格式 代码案例 import torch import torchvision.models as modelsmodel models.resnet50() model.load_state_dict(torch.load("./model/pytorch-resnet50.pth"))model.eval() example_input torch.randn(32, 3, 224, 224) # 根据模型…

transformer网络学习

Transformer encoder-decoder模型之间共享的是Encoder最后一层输出的hidden-state。 GitHub - huggingface/transformers: &#x1f917; Transformers: State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX. Bert2Bert中&#xff0c;Encoder的hidden-state同…

昇思25天学习打卡营第10天|ShuffleNet图像分类

ShuffleNet网络结构 ShuffleNet是一种专为移动设备设计的、计算效率极高的卷积神经网络&#xff08;CNN&#xff09;架构。其网络结构的设计主要围绕减少计算复杂度和提高模型效率展开&#xff0c;通过引入逐点分组卷积&#xff08;Pointwise Group Convolution&#xff09;和…

AutoX.js从某音分享链接解析出视频ID

背景 从某音分享的链接中解析出数字的videoID&#xff0c;用来做评论Intent跳转 思路 基本所有的短链接都是302跳转或者js跳转&#xff0c;熟悉http协议都知道&#xff0c;当状态码为302&#xff0c;从headers中提取Location即刻获得视频的原链接 链接中就带有videoId 要注意…

【大模型LLM面试合集】大语言模型基础_Word2Vec

Word2Vec 文章来源&#xff1a;Word2Vec详解 - 知乎 (zhihu.com) 1.Word2Vec概述 Word2Vec是google在2013年推出的一个NLP工具&#xff0c;它的特点是能够将单词转化为向量来表示&#xff0c;这样词与词之间就可以定量的去度量他们之间的关系&#xff0c;挖掘词之间的联系。 …

Java之父James Gosling宣布正式退休 创造无数人的饭碗

编程语言Java的创始人&#xff0c;被誉为“Java之父”的James Gosling&#xff0c;近日在社交媒体上宣布了自己正式退休的消息。Gosling表示&#xff1a;“我终于退休了。做了这么多年的软件工程师&#xff0c;现在是时候享受人生了。”他透露&#xff0c;在亚马逊的过去7年是非…

提高LabVIEW软件通用性的方法

提高LabVIEW软件通用性的方法 在使用LabVIEW开发软件时&#xff0c;提高软件的通用性非常重要。通用性意味着软件可以在不同的应用场景中使用&#xff0c;具备高度的适应性和灵活性&#xff0c;从而提高软件的价值和用户满意度。以下从多个角度详细探讨如何提高LabVIEW软件的通…

Java 反射相关的面试题

Java 创建对象有几种方式&#xff1f; new 创建新对象 通过反射创建对象 采用 clone 机制 通过序列化机制 使用 new 关键字 public class MyClass {public MyClass() {System.out.println("MyClass object created!");} }public class Main {public static voi…

太实用了吧?手把手教你华为eNSP模拟器桥接真实网络!

号主&#xff1a;老杨丨11年资深网络工程师&#xff0c;更多网工提升干货&#xff0c;请关注公众号&#xff1a;网络工程师俱乐部 晚上好&#xff0c;我的网工朋友。 今天聊聊eNSP桥接正式网络&#xff0c;就是把eNSP桥接进真实的网络&#xff0c;利用我们的物理网卡通过实体路…

Unity Text Mesh Pro 中英文混编自动换行问题

问题描述 使用TextMeshPro 输入中英文时&#xff0c;在一行内 输入中英文&#xff0c;当英文部分超过第一行剩余位置时&#xff0c;整个英文部分都会自动换行 问题截图&#xff1a; 期待截图&#xff1a; 问题说明 因为 TextMeshPro识别中文后会带换行符。 解决方案 修改…

GEE代码实例教程详解:降水量异常分析

简介 在本篇博客中&#xff0c;我们将通过Google Earth Engine (GEE) 分析特定区域内的降水量异常。利用UCSB-CHG提供的CHIRPS&#xff08;Climate Hazards Group InfraRed Precipitation with Station data&#xff09;数据集&#xff0c;我们可以监测2000年至2020年期间的降…

人员定位系统的功能,你知道多少呢?

在此前的文章中&#xff0c;说到了人员定位系统用于化工厂定位这一用途来完善工厂管理&#xff0c;但同时&#xff0c;基于人员定位系统的强大功能&#xff0c;该系统的应用范围也要宽范的多&#xff0c;那么&#xff0c;本篇文章就来为大家介绍一下吧。 人员定位系统的功能简介…

C++、QT企业管理系统

目录 一、项目介绍 二、项目展示 三、源码获取 一、项目介绍 人事端&#xff1a; 1、【产品中心】产品案列、新闻动态的发布&#xff1b; 2、【员工管理】新增、修改、删除、搜索功能&#xff1b;合同以图片的方式上传 3、【考勤总览】根据日期显示所有员工上班、下班时间…

[每周一更]-(第104期):Go中使用Makefile的经验

文章目录 1. 项目结构2. Makefile的基础知识什么是 Makefile 3. Go项目的Makefile示例4. 详细解释每个Makefile目标5. 使用Makefile执行常见任务 在Go项目中&#xff0c;使用Makefile可以简化和自动化常见的开发和部署任务&#xff0c;如编译、测试、格式化和清理。深入认识及实…

javascript如何实现两个变量值互换

javascript如何实现两个变量值互换。 核心思路是在定义第三个变量 第一个变量值赋值给第三个变量 第二个变量赋值给第一个变量 第三个变量值赋值给第二个变量 代码如下 var a10 var b20 var c ca ab bc

SRS流媒体服务器概述

SRS/5.0(Bee) is a simple, high efficiency and realtime video server, supports RTMP, WebRTC, HLS, HTTP-FLV, SRT, MPEG-DASH and GB28181. 翻译&#xff1a;SRS/5.0(Bee)是一款简洁、高效、实时的视频服务器&#xff0c;支持RTMP、WebRTC、HLS、HTTP-FLV、SRT、MPEG-DAS…

Ubuntu开源软件LibreOffice将Excel多表转PDF多目录示例

一、实现的起因&#xff1a; Windows平台下&#xff0c;常见的WPS办公自动化套件中电子表格软件&#xff0c;其中具备将Excel工作表中数据转为PDF文档表格的功能。现在进一步的需求是&#xff1a;像PDF标准的电子书那样&#xff0c;具备一本书的目录结构或章节结构&#xff0c…

怎么才能选到好的猫咪主食冻干?公认顶尖优秀主食冻干总结

如今&#xff0c;主食冻干市场纷繁多样&#xff0c;质量水平却大相径庭。部分品牌盲目追求高营养值和利润增长&#xff0c;却忽略了猫咪健康饮食的本质需求&#xff0c;导致市场上充斥着以次充好、虚假标注日期等不法行为。更有甚者&#xff0c;部分产品未经权威第三方检测便匆…