AI
Phase1 如何理解reAct,CoT,rewoo,plan-and-execute
Nanlan2026年4月20日编辑于 2026年4月26日8 min
CoT(Chain of Thought, 思维链)
- 定义:提示技术,引导模型分步推理,输出中间步骤再给答案。
- 核心:拆解复杂问题为子步骤,提升多步推理(数学、逻辑、代码)准确性。
- 流程:问题 → 步骤 1→步骤 2→…→结论。
- 适用:纯推理、无需工具 / 实时数据的任务。
reAct(Reasoning + Acting, 推理+行动)
- 定义:迭代框架,模型思考→行动→观察循环,动态调用工具(搜索、API、文档)。
- 核心:突破模型固有知识,用外部信息 / 工具解决交互任务。
- 流程:问题 → 推理 → 行动(调工具)→ 观察反馈 → 再推理 → 最终答案。
- 适用:需实时信息、工具调用、多步骤决策(查行情、查邮编、查政策)
from openai import OpenAI
import requests
# ---------- 1. 配置大模型(DeepSeek 国内稳定)----------
client = OpenAI(
api_key="sk-6ab15d31f74642d288e42ebf43afdb93", base_url="https://api.deepseek.com"
)
# ---------- 2. 定义【天气工具】----------
def get_weather(city: str):
"""
查询指定城市实时天气
:param city: 城市名,例如:北京、上海、广州
"""
# 免费公开天气接口
url = f"https://wttr.in/{city}?format=j1"
res = requests.get(url, timeout=10)
data = res.json()
area = data["nearest_area"][0]["areaName"][0]["value"]
temp = data["current_condition"][0]["temp_C"]
weather = data["current_condition"][0]["weatherDesc"][0]["value"]
wind = data["current_condition"][0]["windspeedKmph"]
return f"""
【{area} 实时天气】
天气状况:{weather}
当前温度:{temp}℃
风速:{wind} km/h
"""
# ---------- 3. 告诉大模型:我有一个天气工具 ----------
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "用于查询任意城市的实时天气,用户问天气时必须调用此工具",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "需要查询的城市名称"}
},
"required": ["city"],
},
},
}
]
# ---------- 4. 主逻辑:Agent 自动决策 ----------
def run_agent(user_input):
messages = [{"role": "user", "content": user_input}]
# 第一轮:大模型判断要不要调用工具
resp = client.chat.completions.create(
model="deepseek-chat", messages=messages, tools=tools
)
msg = resp.choices[0].message
# 需要调用天气工具
if msg.tool_calls:
tool_call = msg.tool_calls[0]
func_name = tool_call.function.name
# 解析城市参数
import json
args = json.loads(tool_call.function.arguments)
city_name = args["city"]
# 执行工具,拿到天气结果
if func_name == "get_weather":
weather_result = get_weather(city_name)
# 把工具结果丢给大模型,让它整理成自然语言回答
messages.append(msg)
messages.append(
{
"role": "tool",
"tool_call_id": tool_call.id,
"name": func_name,
"content": weather_result,
}
)
final_resp = client.chat.completions.create(
model="deepseek-chat", messages=messages
)
print("🤖 Agent 回答:")
print(final_resp.choices[0].message.content)
# 不需要工具,直接聊天
else:
print("🤖 Agent 回答:")
print(msg.content)
# ---------- 5. 启动 Agent ----------
if __name__ == "__main__":
# 你可以改成任意城市:上海、成都、深圳
question = "杭州今天天气怎么样?"
run_agent(question)