一、介绍#

这里用 ReAct 来写一个最简单的 Agent,调用 DeepSeek 的 API ,外加 CLI 进行多轮对话的 Agent。

二、ReAct 最简单介绍#

ReAct 拆开来 ,就是 Re + Act,Reasoning + Acting。

思考(我要做什么)→ 再行动(调用工具 / 回答)→ 观察结果 → 继续思考→ 再行动 → 观察结果,... ...,直到完成任务。

三、实现代码#

第一步:调用大模型API#

这类调用 DeepSeek API。

python 实现调用DeepSeek API ,代码如下:


Copy

import requests import json # ===================== 配置项 ===================== DEEPSEEK_API_KEY = "你的 DeepSeek API Key" # 替换成你的 key DEEPSEEK_API_URL = "https://api.deepseek.com/chat/completions" MODEL_NAME = "deepseek-chat" # ================================================== def deepseek_chat(messages): """调用 DeepSeek 大模型接口""" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {DEEPSEEK_API_KEY}" } data = { "model": MODEL_NAME, "messages": messages, "temperature": 0.1 # 低温度让思考更稳定 } response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data) if response.status_code != 200: return f"API 调用失败:{response.status_code},{response.text}" return response.json()["choices"][0]["message"]["content"]

第二步:实现ReAct的Agent#


Copy

def react_agent(): """ReAct 智能体主函数:多轮对话 + 思考-行动-观察""" print("=" * 50) print("🔥 ReAct 智能体(DeepSeek)已启动 | 输入 exit 退出") print("=" * 50) # 系统提示词:定义 ReAct 行为规则(核心!) system_prompt = """ 你是一个遵循 ReAct 框架的智能体。 你的工作流程严格按照: 1. 思考:我现在需要解决什么问题? 2. 行动:直接给出最终回答 3. 观察:根据结果继续优化 要求: - 保持简洁、有用、直接 - 支持多轮对话,记住上下文 - 不要输出多余格式 """ # 对话历史(保存上下文,实现多轮) messages = [{"role": "system", "content": system_prompt}] while True: # 用户输入 user_input = input("\n你:") if user_input.lower() in ["exit", "quit", "q"]: print("\n👋 智能体已退出") break # 加入用户消息 messages.append({"role": "user", "content": user_input}) # 调用模型(ReAct 思考 + 行动) print("\n🤖 智能体思考中...") response = deepseek_chat(messages) # 输出结果 print(f"智能体:{response}") # 保存回答到历史(关键:多轮对话的核心) messages.append({"role": "assistant", "content": response})

第三步:完整程序#

把上面2步中的代码合并,实现一个完整的 Agent 程序:


Copy

import requests import json # ===================== 配置项 ===================== DEEPSEEK_API_KEY = "你的 DeepSeek API Key" # 替换成你的 key DEEPSEEK_API_URL = "https://api.deepseek.com/chat/completions" MODEL_NAME = "deepseek-chat" # ================================================== def deepseek_chat(messages): """调用 DeepSeek 大模型接口""" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {DEEPSEEK_API_KEY}" } data = { "model": MODEL_NAME, "messages": messages, "temperature": 0.1 # 低温度让思考更稳定 } response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data) if response.status_code != 200: return f"API 调用失败:{response.status_code},{response.text}" return response.json()["choices"][0]["message"]["content"] def react_agent(): """ReAct 智能体主函数:多轮对话 + 思考-行动-观察""" print("=" * 50) print("🔥 ReAct 智能体(DeepSeek)已启动 | 输入 exit 退出") print("=" * 50) # 系统提示词:定义 ReAct 行为规则(核心!) system_prompt = """ 你是一个遵循 ReAct 框架的智能体。 你的工作流程严格按照: 1. 思考:我现在需要解决什么问题? 2. 行动:直接给出最终回答 3. 观察:根据结果继续优化 要求: - 保持简洁、有用、直接 - 支持多轮对话,记住上下文 - 不要输出多余格式 """ # 对话历史(保存上下文,实现多轮) messages = [{"role": "system", "content": system_prompt}] while True: # 用户输入 user_input = input("\n你:") if user_input.lower() in ["exit", "quit", "q"]: print("\n👋 智能体已退出") break # 加入用户消息 messages.append({"role": "user", "content": user_input}) # 调用模型(ReAct 思考 + 行动) print("\n🤖 智能体思考中...") response = deepseek_chat(messages) # 输出结果 print(f"智能体:{response}") # 保存回答到历史(关键:多轮对话的核心) messages.append({"role": "assistant", "content": response}) if __name__ == "__main__": react_agent()

四、程序核心特性(极简)#

  1. 真正 ReAct 框架:思考 → 行动 → 观察
  2. 多轮对话:自动保存上下文,记住之前的对话
  3. 纯 CLI:干净、轻量、无界面依赖

五、使用步骤#

1. 安装依赖#

运行


Copy

pip install requests

2. 获取 DeepSeek API Key#

需要充点钱

  • 打开 DeepSeek 平台
  • 注册 → 登录 → 创建 API Key
  • 复制 Key 替换代码里的 你的 DeepSeek API Key

3. 运行#

运行


Copy

python react_agent.py

4. CLI 使用示例#

输入:1+1等于几

agent运行

agent运行2

六、扩展:ReAct智能体 + 联网搜索工具#

把上面的程序扩展为带有联网搜索能力的 ReAct 智能体。

智能体遇到不知道的问题会自动调用搜索,知道的问题直接回答,完美遵循 ReAct 流程:

思考 → 决定是否搜索 → 调用搜索工具 → 观察结果 → 回答

这里使用 使用 DuckDuckGo 免费搜索,无需 key ,简单。

加上搜索功能#

方法 web_search 代码如下:


Copy

# 搜索工具配置(使用 DuckDuckGo 免费搜索,无需API Key) SEARCH_API_URL = "https://api.duckduckgo.com/" # ================================================== def web_search(query: str) -> str: """ 联网搜索工具DuckDuckGo,免费无需 Key :param query: 搜索关键词 :return: 搜索结果摘要 """ try: params = { "q": query, "format": "json", "no_html": 1, "skip_disambig": 1 } response = requests.get(SEARCH_API_URL, params=params, timeout=10) data = response.json() # 提取搜索结果 results = [] for item in data.get("Results", [])[:3]: # 取前3条结果 title = item.get("Text", "") url = item.get("FirstURL", "") results.append(f"【结果】{title}\n链接:{url}") if not results: return "未搜索到相关信息" return "\n".join(results) except Exception as e: return f"搜索失败:{str(e)}"

完整代码#


Copy

import requests import json # ===================== 配置项 ===================== DEEPSEEK_API_KEY = "你的 DeepSeek API Key" # 替换你的key DEEPSEEK_API_URL = "https://api.deepseek.com/chat/completions" MODEL_NAME = "deepseek-chat" # 搜索工具配置(使用 DuckDuckGo 免费搜索,无需API Key) SEARCH_API_URL = "https://api.duckduckgo.com/" # ================================================== def web_search(query: str) -> str: """ 联网搜索工具(免费无Key) :param query: 搜索关键词 :return: 搜索结果摘要 """ try: params = { "q": query, "format": "json", "no_html": 1, "skip_disambig": 1 } response = requests.get(SEARCH_API_URL, params=params, timeout=10) data = response.json() # 提取搜索结果 results = [] for item in data.get("Results", [])[:3]: # 取前3条结果 title = item.get("Text", "") url = item.get("FirstURL", "") results.append(f"【结果】{title}\n链接:{url}") if not results: return "未搜索到相关信息" return "\n".join(results) except Exception as e: return f"搜索失败:{str(e)}" def deepseek_chat(messages): """调用 DeepSeek 大模型接口""" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {DEEPSEEK_API_KEY}" } data = { "model": MODEL_NAME, "messages": messages, "temperature": 0.1 } response = requests.post(DEEPSEEK_API_URL, headers=headers, json=data) if response.status_code != 200: return f"API 调用失败:{response.status_code},{response.text}" return response.json()["choices"][0]["message"]["content"] def react_agent(): """ReAct 智能体:思考 → 行动(搜索/回答) → 观察 → 最终回答""" print("=" * 60) print("🔥 ReAct 智能体(DeepSeek + 联网搜索)已启动 | 输入 exit 退出") print("📌 功能:不知道的问题会自动联网搜索!") print("=" * 60) # 核心:ReAct 系统提示词(告诉模型什么时候用搜索) system_prompt = """ 你是一个严格遵循 ReAct 框架的智能体,必须按照固定流程执行: 流程: 1. 思考:分析用户问题,判断是否需要联网搜索 - 实时信息、最新新闻、未知数据 → 必须调用搜索 - 常识、计算、逻辑问题 → 直接回答 2. 行动: - 需要搜索:输出固定格式:【搜索】+ 搜索关键词 - 不需要搜索:直接给出答案 3. 观察:如果调用了搜索,就根据搜索结果整理回答 规则: - 只有需要实时/未知信息时才搜索,不要滥用 - 搜索格式必须严格:【搜索】xxx - 回答简洁准确 """ # 对话历史(保存上下文) messages = [{"role": "system", "content": system_prompt}] while True: user_input = input("\n👨‍💻 你:") if user_input.lower() in ["exit", "quit", "q"]: print("\n👋 智能体已退出") break messages.append({"role": "user", "content": user_input}) print("\n🤖 智能体思考中...") # 第一步:让模型思考是否需要搜索 thought_response = deepseek_chat(messages) # 判断是否触发搜索工具 if "【搜索】" in thought_response: # 提取搜索关键词 search_query = thought_response.replace("【搜索】", "").strip() print(f"🔍 正在联网搜索:{search_query}") # 调用搜索工具 search_result = web_search(search_query) print(f"✅ 搜索完成,整理结果中...") # 把搜索结果传给模型,生成最终回答 messages.append({"role": "assistant", "content": thought_response}) messages.append({"role": "system", "content": f"搜索结果:{search_result}"}) final_answer = deepseek_chat(messages) print(f"\🤖智能体:{final_answer}") messages.append({"role": "assistant", "content": final_answer}) # 不需要搜索,直接回答 else: print(f"\🤖 智能体:{thought_response}") messages.append({"role": "assistant", "content": thought_response}) if __name__ == "__main__": react_agent()

运行代码#

替换 deepseek key,把代码里的 你的 DeepSeek API Key 换成你自己的 deepseek api key。

运行:


Copy

python react_agent.py

运行Agent

询问:最近关于羽毛球亚锦赛夺冠信息有哪些

运行Agent

Logo

欢迎加入DeepSeek 技术社区。在这里,你可以找到志同道合的朋友,共同探索AI技术的奥秘。

更多推荐