100多行代码实现一个最简单的Agent(用ReAct)

100多行代码实现一个最简单的Agent(用ReAct)这里用 ReAct 来写一个最简单的 Agent 调用 DeepSeek 的 API 外加 CLI 进行多轮对话的 Agent ReAct 拆开来 就是 Re Act Reasoning Acting 先思考 我要做什么 再行动 调用工具 回答 观察结果 继续思考 再行动 观察结果 直到完成任务 这类调用 DeepSeek

大家好,我是讯享网,很高兴认识大家。这里提供最前沿的Ai技术和互联网信息。



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

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

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

这类调用 DeepSeek API。

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

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(" 你:") if user_input.lower() in ["exit", "quit", "q"]: print(" 👋 智能体已退出") break # 加入用户消息 messages.append({"role": "user", "content": user_input}) # 调用模型(ReAct 思考 + 行动) print(" 🤖 智能体思考中...") response = deepseek_chat(messages) # 输出结果 print(f"智能体:{response}") # 保存回答到历史(关键:多轮对话的核心) messages.append({"role": "assistant", "content": response}) 

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

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(" 你:") if user_input.lower() in ["exit", "quit", "q"]: print(" 👋 智能体已退出") break # 加入用户消息 messages.append({"role": "user", "content": user_input}) # 调用模型(ReAct 思考 + 行动) print(" 🤖 智能体思考中...") response = deepseek_chat(messages) # 输出结果 print(f"智能体:{response}") # 保存回答到历史(关键:多轮对话的核心) messages.append({"role": "assistant", "content": response}) if __name__ == "__main__": react_agent() 
  1. 真正 ReAct 框架:思考 → 行动 → 观察
  2. 多轮对话:自动保存上下文,记住之前的对话
  3. 纯 CLI:干净、轻量、无界面依赖

运行

pip install requests 

需要充点钱

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

运行

python react_agent.py 

输入:1+1等于几

agent运行

agent运行2

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

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

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

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

方法 web_search 代码如下:

# 搜索工具配置(使用 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}

链接:{url}“)

    if not results:
        return "未搜索到相关信息"

    return "

”.join(results)

except Exception as e:
    return f"搜索失败:{str(e)}"

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}
链接:{url}")
        
        if not results:
            return "未搜索到相关信息"
        
        return "
".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("
👨‍💻 你:")
        if user_input.lower() in ["exit", "quit", "q"]:
            print("
👋 智能体已退出")
            break
        
        messages.append({"role": "user", "content": user_input})
        print("
🤖 智能体思考中...")

        # 第一步:让模型思考是否需要搜索
        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。

运行:

python react_agent.py

运行Agent

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

运行Agent

大模型回答属于实时赛事消息,然后调用搜索功能,搜索结果,在传给大模型进行整理。

搜索结果是2024年的信息,应该搜索最近信息,不知道是不是duckduckgo的API出了问题

不过Agent整体运行是正常的。

一个简单的带有搜索功能的 ReAct 的 Agent 就开发完成了 。

[完]

小讯
上一篇 2026-04-14 15:54
下一篇 2026-04-14 15:52

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/260792.html