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

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

相关文章:

Simple_ReAct_Agent

参考自https://www.deeplearning.ai/short-courses/ai-agents-in-langgraph&#xff0c;以下为代码的实现。 Basic ReAct Agent(manual action) import openai import re import httpx import os from dotenv import load_dotenv, find_dotenvOPENAI_API_KEY os.getenv(OPEN…...

window wsl安装ubuntu

文章目录 wsl安装ubuntu什么是wsl安装wsl检查运行 WSL 2 的要求将 WSL 2 设置为默认版本查看并安装linux WSL2的使用如何查看linux文件wsl如何使用代理:方法1&#xff1a;方法2&#xff1a;通过 DNS 隧道来配置 WSL 的网络 如何将 WSL 接入局域网并与宿主机同网段使用VScode连接…...

postmessage()在同一域名下,传递消息给另一个页面

这里是同域名下&#xff0c;getmessage.html&#xff08;发送信息&#xff09;传递消息给index.html&#xff08;收到信息&#xff0c;并回传收到信息&#xff09; index.html页面 <!DOCTYPE html> <html><head><meta http-equiv"content-type"…...

初始redis:在Ubuntu上安装redis

1.先切换到root用户 使用su命令切换到root 2.使用apt命令来搜索redis相关的软件包 命令&#xff1a;apt search redis 3.下载redis 命令&#xff1a; apt install redis 在Ubuntu 20.04中 &#xff0c;下载的redis版本是redis5 4.查看redis状态 命令&#xff1a; netst…...

生物素结合金纳米粒子(Bt@Au-NPs ) biotin-conjugated Au-NPs

一、定义与特点 定义&#xff1a;生物素结合金纳米粒子&#xff0c;简称BtAu-NPs或biotin-conjugated Au-NPs&#xff0c;是指通过特定的化学反应或物理方法将生物素修饰到金纳米粒子表面&#xff0c;形成稳定的纳米复合材料。 特点&#xff1a; 高稳定性&#xff1a;生物素的修…...

LeetCode热题100刷题9:25. K 个一组翻转链表、101. 对称二叉树、543. 二叉树的直径、102. 二叉树的层序遍历

25. K 个一组翻转链表 /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), nex…...

PyJWT,一个基于JSON的轻量级安全通信方式的python库

目录 什么是JWT&#xff1f; JWT的构成 PyJWT库简介 安装PyJWT 生成JWT 验证JWT 使用PyJWT的高级功能 自定义Claims 错误处理 结语 什么是JWT&#xff1f; 在介绍PyJWT这个Python库之前&#xff0c;我们首先需要了解什么是JWT。JWT&#xff0c;全称JSON Web Token&am…...

Golang | Leetcode Golang题解之第223题矩形面积

题目&#xff1a; 题解&#xff1a; func computeArea(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 int) int {area1 : (ax2 - ax1) * (ay2 - ay1)area2 : (bx2 - bx1) * (by2 - by1)overlapWidth : min(ax2, bx2) - max(ax1, bx1)overlapHeight : min(ay2, by2) - max(ay1, by1)…...

新手怎么使用GitLab?

GitLab新手指南: GitLab 是一个非常强大的版本控制和项目管理平台&#xff0c;对于新手来说&#xff0c;开始使用可能会有些许挑战&#xff0c;但只要跟着以下步骤&#xff0c;相信你就能很快上手。 1. 注册与登录 访问网站&#xff1a;打开浏览器&#xff0c;访问 GitLab官网…...

表情包原理

https://unicode.org/Public/emoji/12.1/emoji-zwj-sequences.txt emoji 编码规则介绍_emoji编码-CSDN博客 UTS #51: Unicode Emoji C UTF-8编解码-CSDN博客 创作不易&#xff0c;小小的支持一下吧&#xff01;...

技术难点思考SpringBoot如何集成Jmeter开发

技术难点思考SpringBoot如何集成Jmeter开发 需求概述 构建一个高性能的压测平台&#xff0c;该平台需通过Spring Boot框架调用JMeter进行自动化压力测试。 解决方案一&#xff1a;使用Runtime类调用外部进程 技术概述 Java的Runtime类提供了与操作系统交互的接口&#xff0…...

如何快速使用C语言操作sqlite3

itopen组织1、提供OpenHarmony优雅实用的小工具2、手把手适配riscv qemu linux的三方库移植3、未来计划riscv qemu ohos的三方库移植 小程序开发4、一切拥抱开源&#xff0c;拥抱国产化 一、sqlite3库介绍 sqlite3库可从官网下载&#xff0c;当前版本为sqlite3 3.45.3ht…...

网络模型介绍

网络模型在网络领域中主要指的是用于描述计算机网络系统功能的各种框架&#xff0c;其中最具代表性的两种模型是OSI七层参考模型和TCP/IP四层参考模型。以下是对这两种网络模型的详细解析&#xff1a; 一、OSI七层参考模型 OSI&#xff08;Open System Interconnection&#…...

Codeforces Round #956 (Div. 2) and ByteRace 2024

A题&#xff1a;Array Divisibility 思路&#xff1a; 大水题 code&#xff1a; inline void solve() {int n; cin >> n;for (int i 1; i < n; i ) {cout << i << " \n"[i n];}return; } B题&#xff1a;Corner Twist 思路&#xff1…...

域名、网页、HTTP概述

目录 域名 概念 域名空间结构 域名注册 网页 概念 网站 主页 域名 HTTP URL URN URI HTML 超链接 发布 HTML HTML的结构 静态网页 特点 动态网页 特点 Web HTTP HTTP方法 GET方法 POST方法 HTTP状态码 生产环境下常见的HTTP状态码 域名 概念 IP地…...

Redisson分布式锁、可重入锁

介绍Redisson 什么是 Redisson&#xff1f;来自于官网上的描述内容如下&#xff01; Redisson 是一个在 Redis 的基础上实现的 Java 驻内存数据网格客户端&#xff08;In-Memory Data Grid&#xff09;。它不仅提供了一系列的 redis 常用数据结构命令服务&#xff0c;还提供了…...

适合宠物饮水机的光电传感器有哪些

如今&#xff0c;随着越来越多的人选择养宠物&#xff0c;宠物饮水机作为一种便捷的饮水解决方案日益受到欢迎。为了确保宠物随时能够获得足够的水源&#xff0c;宠物饮水机通常配备了先进的光电液位传感器技术。 光电液位传感器在宠物饮水机中起着关键作用&#xff0c;主要用…...

『Python学习笔记』Python运行设置PYTHONPATH环境变量!

Python运行设置PYTHONPATH环境变量&#xff01; 文章目录 一. Python运行设置PYTHONPATH环境变量&#xff01;1. 解释2. 为什么有用3. 示例4. vscode配置 一. Python运行设置PYTHONPATH环境变量&#xff01; export PYTHONPATH$(pwd) 是一个命令&#xff0c;用于将当前目录添…...

2024年06月CCF-GESP编程能力等级认证Python编程三级真题解析

本文收录于专栏《Python等级认证CCF-GESP真题解析》&#xff0c;专栏总目录&#xff1a;点这里&#xff0c;订阅后可阅读专栏内所有文章。 一、单选题&#xff08;每题 2 分&#xff0c;共 30 分&#xff09; 第 1 题 小杨父母带他到某培训机构给他报名参加CCF组织的GESP认证…...

代码随想录算法训练营:20/60

非科班学习算法day20 | LeetCode235:二叉搜索树的最近公共祖先 &#xff0c;Leetcode701:二叉树的插入操作 &#xff0c;Leetcode450:删除二叉搜索树的节点 介绍 包含LC的两道题目&#xff0c;还有相应概念的补充。 相关图解和更多版本&#xff1a; 代码随想录 (programmer…...

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…...

以下是对华为 HarmonyOS NETX 5属性动画(ArkTS)文档的结构化整理,通过层级标题、表格和代码块提升可读性:

一、属性动画概述NETX 作用&#xff1a;实现组件通用属性的渐变过渡效果&#xff0c;提升用户体验。支持属性&#xff1a;width、height、backgroundColor、opacity、scale、rotate、translate等。注意事项&#xff1a; 布局类属性&#xff08;如宽高&#xff09;变化时&#…...

.Net框架,除了EF还有很多很多......

文章目录 1. 引言2. Dapper2.1 概述与设计原理2.2 核心功能与代码示例基本查询多映射查询存储过程调用 2.3 性能优化原理2.4 适用场景 3. NHibernate3.1 概述与架构设计3.2 映射配置示例Fluent映射XML映射 3.3 查询示例HQL查询Criteria APILINQ提供程序 3.4 高级特性3.5 适用场…...

LLM基础1_语言模型如何处理文本

基于GitHub项目&#xff1a;https://github.com/datawhalechina/llms-from-scratch-cn 工具介绍 tiktoken&#xff1a;OpenAI开发的专业"分词器" torch&#xff1a;Facebook开发的强力计算引擎&#xff0c;相当于超级计算器 理解词嵌入&#xff1a;给词语画"…...

使用LangGraph和LangSmith构建多智能体人工智能系统

现在&#xff0c;通过组合几个较小的子智能体来创建一个强大的人工智能智能体正成为一种趋势。但这也带来了一些挑战&#xff0c;比如减少幻觉、管理对话流程、在测试期间留意智能体的工作方式、允许人工介入以及评估其性能。你需要进行大量的反复试验。 在这篇博客〔原作者&a…...

CRMEB 中 PHP 短信扩展开发:涵盖一号通、阿里云、腾讯云、创蓝

目前已有一号通短信、阿里云短信、腾讯云短信扩展 扩展入口文件 文件目录 crmeb\services\sms\Sms.php 默认驱动类型为&#xff1a;一号通 namespace crmeb\services\sms;use crmeb\basic\BaseManager; use crmeb\services\AccessTokenServeService; use crmeb\services\sms\…...

作为测试我们应该关注redis哪些方面

1、功能测试 数据结构操作&#xff1a;验证字符串、列表、哈希、集合和有序的基本操作是否正确 持久化&#xff1a;测试aof和aof持久化机制&#xff0c;确保数据在开启后正确恢复。 事务&#xff1a;检查事务的原子性和回滚机制。 发布订阅&#xff1a;确保消息正确传递。 2、性…...

【Linux系统】Linux环境变量:系统配置的隐形指挥官

。# Linux系列 文章目录 前言一、环境变量的概念二、常见的环境变量三、环境变量特点及其相关指令3.1 环境变量的全局性3.2、环境变量的生命周期 四、环境变量的组织方式五、C语言对环境变量的操作5.1 设置环境变量&#xff1a;setenv5.2 删除环境变量:unsetenv5.3 遍历所有环境…...

9-Oracle 23 ai Vector Search 特性 知识准备

很多小伙伴是不是参加了 免费认证课程&#xff08;限时至2025/5/15&#xff09; Oracle AI Vector Search 1Z0-184-25考试&#xff0c;都顺利拿到certified了没。 各行各业的AI 大模型的到来&#xff0c;传统的数据库中的SQL还能不能打&#xff0c;结构化和非结构的话数据如何和…...

[论文阅读]TrustRAG: Enhancing Robustness and Trustworthiness in RAG

TrustRAG: Enhancing Robustness and Trustworthiness in RAG [2501.00879] TrustRAG: Enhancing Robustness and Trustworthiness in Retrieval-Augmented Generation 代码&#xff1a;HuichiZhou/TrustRAG: Code for "TrustRAG: Enhancing Robustness and Trustworthin…...