1.概述
先理解这个ReAct是什么东西,一般意义上是这样的,
ReAct = Rea soning(推理) + Acting(行动)
这是目前最主流的Agent设计模式,让Agent能够:
-
思考:分析当前情况,决定做什么
-
行动:执行具体操作(调用工具、查询记忆等)
-
观察:分析行动结果,决定下一步
不难理解,不过还是没那么清楚,可以这么理解:
用户提问 → AI判断需要什么工具 → 执行工具 → 返回结果
那现在我们可能就有一个新的疑问了,ReAct模式就是去设定一个工具,那不是和Function Calling一样的了,意义差不多,但是方式上有区别的,下面会说到。
再简单描述下:代码先让AI判断用户想要什么(工具判断),然后Python执行具体的函数(工具执行),最后把结果返回给用户,中间最关键的就是需要我们自己设定一个模版提示词交给AI判断,然后返回设定好的结果,再去调用写好的工具。
2.实例
2.1 制定提示词
这个是关键,AI会根据你的提示选择工具的信息:
python
detect_prompt = f"""
判断用户需要什么工具,只返回工具名和参数,不要其他内容。
用户输入:{user_input}
可用工具:
1. weather - 查天气,需要城市名
2. time - 查时间,不需要参数
3. calc - 计算,需要算式
4. chat - 普通聊天,不需要参数
返回格式(JSON):
{{"tool": "工具名", "param": "参数值"}}
示例:
"北京天气" → {{"tool": "weather", "param": "北京"}}
"现在几点" → {{"tool": "time", "param": ""}}
"1+2等于多少" → {{"tool": "calc", "param": "1+2"}}
"你好" → {{"tool": "chat", "param": ""}}
"""
能到到描述中已经设定了能用的工具类型,然后还有返回的数据,好让我们知道选择的是哪个工具,下面直接去链接模型,这块代码不写了,最后会全部贴出;
2.2 分析结果
拿到结果需要我们自己分析,然后去选择相应的工具,并执行返回设定好的信息:
python
# 解析结果
try:
content = response.choices[0].message.content
# 提取 JSON
json_match = re.search(r'\{.*\}', content, re.DOTALL)
if json_match:
import json
result = json.loads(json_match.group())
tool = result.get("tool", "chat")
param = result.get("param", "")
else:
tool, param = "chat", ""
except:
tool, param = "chat", ""
# 第二步:执行工具
if tool == "weather":
answer = self.get_weather(param)
elif tool == "time":
answer = self.get_time()
elif tool == "calc":
answer = self.calculate(param)
else:
# 普通聊天
chat_response = self.client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": user_input}]
)
answer = chat_response.choices[0].message.content
return answer
大概就是这样,看看运行的结果:

很明显第一条不用工具,后面三条是需要工具的;
3.总结
我觉得还是需要理解,普通对话、function Calling和ReAct模式之间的异同,举个例子问今天天气:
python
# 普通对话
response = client.chat.completions.create(
messages=[{"role": "user", "content": "北京天气"}]
)
# AI返回: "抱歉,我无法获取实时天气"
# Function Calling(API内置工具)
response = client.chat.completions.create(
messages=[{"role": "user", "content": "北京天气"}],
tools=[{...}] # ← 关键:有tools参数
)
# AI返回: tool_calls = [{"name": "get_weather", ...}]
# ReAct模式(自定义文本解析)
prompt = "如果需要工具,输出TOOL:weather(城市)"
response = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}]
)
# AI返回: "TOOL:weather(北京)"
这就比较清晰一点了,算是有了初步了解,下面再总结下:
|----------------------------|--------------------------|
| 普通对话不包括Function Calling吧? | ✅ 对! 普通对话没有tools参数 |
| 普通对话和ReAct是一回事吗? | ❌ 不是,ReAct有自定义工具格式 |
| Function Calling和ReAct的区别? | 一个API内置,一个自己写提示词解析 |
最后贴上代码:
python
from openai import OpenAI
import os
import re
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
class ReActAgent:
def __init__(self):
self.client = OpenAI(
api_key=os.getenv("DEEPSEEK_API_KEY"),
base_url="https://api.deepseek.com"
)
def get_weather(self, city):
"""天气工具"""
weather_data = {
"北京": "晴天 25°C",
"上海": "多云 22°C",
"广州": "阵雨 28°C",
"深圳": "晴天 27°C"
}
return weather_data.get(city, f"{city}:晴天 20°C")
def get_time(self):
"""时间工具"""
return datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")
def calculate(self, expr):
"""计算工具"""
try:
# 只允许数字和基本运算符
if re.match(r'^[\d\s\+\-\*\/\(\)\.]+$', expr):
result = eval(expr)
return f"{expr} = {result}"
return "表达式格式不对"
except:
return "计算错误"
def run(self, user_input):
"""主入口"""
# 第一步:判断需要什么工具
detect_prompt = f"""
判断用户需要什么工具,只返回工具名和参数,不要其他内容。
用户输入:{user_input}
可用工具:
1. weather - 查天气,需要城市名
2. time - 查时间,不需要参数
3. calc - 计算,需要算式
4. chat - 普通聊天,不需要参数
返回格式(JSON):
{{"tool": "工具名", "param": "参数值"}}
示例:
"北京天气" → {{"tool": "weather", "param": "北京"}}
"现在几点" → {{"tool": "time", "param": ""}}
"1+2等于多少" → {{"tool": "calc", "param": "1+2"}}
"你好" → {{"tool": "chat", "param": ""}}
"""
response = self.client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": detect_prompt}],
temperature=0
)
# 解析结果
try:
content = response.choices[0].message.content
# 提取 JSON
json_match = re.search(r'\{.*\}', content, re.DOTALL)
if json_match:
import json
result = json.loads(json_match.group())
tool = result.get("tool", "chat")
param = result.get("param", "")
else:
tool, param = "chat", ""
except:
tool, param = "chat", ""
# 第二步:执行工具
if tool == "weather":
answer = self.get_weather(param)
elif tool == "time":
answer = self.get_time()
elif tool == "calc":
answer = self.calculate(param)
else:
# 普通聊天
chat_response = self.client.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": user_input}]
)
answer = chat_response.choices[0].message.content
return answer
# 测试
if __name__ == "__main__":
agent = ReActAgent()
tests = [
"你好",
"北京天气怎么样",
"现在几点了",
"123 + 456 等于多少"
]
for t in tests:
print(f"\n用户: {t}")
print(f"助手: {agent.run(t)}")
print("-" * 40)