L1 Simple_ReAct_Agent

参考自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_dotenv

OPENAI_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 necessary

average_dog_weight:
e.g. average_dog_weight: Collie
returns average weight of a dog when given the breed

Example session:

Question: How much does a Bulldog weigh?
Thought: I should look the dogs weight using average_dog_weight
Action: average_dog_weight: Bulldog
PAUSE

You will be called again with this:

Observation: A Bulldog weights 51 lbs

You then output:

Answer: A bulldog weights 51 lbs
""".strip()
python 复制代码
class Agent:
    def __init__(self, system=""):
        self.system = system
        self.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 result

    def 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 = 0
    bot = Agent(prompt)
    next_prompt = question
    while i < max_turns:
        i += 1
        result = 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 run
            action, 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
相关推荐
OpenBayes贝式计算12 分钟前
教程上新丨媲美 o3-mini,开源代码推理模型 DeepCoder-14B-Preview 狂揽 3k stars
人工智能·开源·llm
拖拉机18 分钟前
Python(八)类(下)
后端·python
晓131343 分钟前
第三章 爬虫提速、selenium模块、requests模块进阶(终)
爬虫·python·selenium·测试工具·http
新智元43 分钟前
o3 全网震撼实测:AGI 真来了?最强氛围编程秒杀人类,却被曝捏造事实
人工智能·openai
新智元1 小时前
何恺明 ResNet 登顶,Transformer 加冕!Nature 独家揭秘 25 篇高被引论文
人工智能·openai
noravinsc1 小时前
python 使用rabbitmq
python·rabbitmq·ruby
新智元1 小时前
OpenAI 震撼发布 o3/o4-mini,直逼视觉推理巅峰!首用图像思考,十倍算力爆表
人工智能·openai
newxtc1 小时前
【随行付-注册安全分析报告-无验证方式导致隐患】
人工智能·安全·网易易盾·极验
计算所陈老师1 小时前
基于论文的大模型应用:基于SmartETL的arXiv论文数据接入与预处理(二)
人工智能·个人开发·信息抽取
Dlimeng1 小时前
OpenAI发布GPT-4.1系列模型——开发者可免费使用
人工智能·ai·chatgpt·openai·ai编程·agents·gpt-41