Simple_ReAct_Agent

news/2024/12/23 1:19:46/

参考自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/1474078.html

相关文章

【区块链+基础设施】蜀信链 | FISCO BCOS应用案例

蜀信链是在四川省经济和信息化厅指导下&#xff0c;在四川省区块链行业协会组织下&#xff0c;由全省区块链相关从业与应用机构 共同参与建设和运营的区域性区块链基础设施&#xff0c;通过多方协同&#xff0c;共同打造合作共赢的区块链产业生态。 蜀信链区块链服务生态秉承“…

武汉免费 【FPGA实战训练】 Vivado入门与设计师资课程

一&#xff0e;背景介绍 当今高度数字化和智能化的工业领域&#xff0c;对高效、灵活且可靠的技术解决方案的需求日益迫切。随着工业 4.0 时代的到来&#xff0c;工业生产过程正经历着前所未有的变革&#xff0c;从传统的机械化、自动化逐步迈向智能化和信息化。在这一背景下&…

Unity--异步加载场景

Unity–异步加载场景 异步加载场景其实和异步加载资源是一样的,只是加载的内容比较特殊而已. 也可以将场景视为特殊资源. 1.SceneManager.LoadScene 加载场景的方式,在Unity 中加载场景是通过SceneManager.LoadScene("场景名称"); 来实现加载场景,这和UE4中的Open…

关于ORACLE单例数据库中的logfile的切换、删除以及添加

一、有关logfile的状态解释 UNUSED&#xff1a; 尚未记录change的空白group&#xff08;一般会出现在loggroup刚刚被添加&#xff0c;或者刚刚使用了reset logs打开数据库&#xff0c;或者使用clear logfile后&#xff09; CURRENT: 当前正在被LGWR使用的gro…

Qt扫盲-QRect矩形描述类

QRect矩形描述总结 一、概述二、常用函数1. 移动类2. 属性函数3. 判断4. 比较计算 三、渲染三、坐标 一、概述 QRect类使用整数精度在平面中定义一个矩形。在绘图的时候经常使用&#xff0c;作为一个二维的参数描述类。 一个矩形主要有两个重要属性&#xff0c;一个是坐标&am…

HBuilder X 小白日记03-用css制作简单的交互动画

:hover选择器&#xff0c;用于选择鼠标指针浮动在上面的元素。 :hover选择器可用于所有元素&#xff0c;不只是链接 :link选择器 设置指向未被访问页面的链接的样式 :visited选择器 用于设置指向已被访问的页面的链接 :active选择器 用于活动链接

爬虫逆向之常见的JS Hook示例

爬虫逆向之常见的JS Hook示例 在JavaScript中&#xff0c;hook通常指的是通过替换或修改函数、属性或对象来拦截或修改程序行为的技术。 以下是一些常见的hook示例&#xff1a; 函数挂钩&#xff08;Function Hooking&#xff09;: // 原始函数 function originalFunction() …

【面试题】串联探针和旁挂探针有什么区别?

在网络安全领域中&#xff0c;串联探针和旁挂探针&#xff08;通常也被称为旁路探针&#xff09;是两种不同部署方式的监控设备&#xff0c;它们各自具有独特的特性和应用场景。以下是它们之间的主要区别&#xff1a; 部署方式 串联探针&#xff1a;串联探针一般通过网关或者…