惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

N
News and Events Feed by Topic
爱范儿
爱范儿
Blog — PlanetScale
Blog — PlanetScale
The GitHub Blog
The GitHub Blog
C
Check Point Blog
小众软件
小众软件
I
InfoQ
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Engineering at Meta
Engineering at Meta
酷 壳 – CoolShell
酷 壳 – CoolShell
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Hugging Face - Blog
Hugging Face - Blog
博客园 - 三生石上(FineUI控件)
MyScale Blog
MyScale Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
腾讯CDC
Y
Y Combinator Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
B
Blog
T
Tailwind CSS Blog
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
D
Docker
博客园 - 司徒正美
博客园_首页
Recent Announcements
Recent Announcements
D
DataBreaches.Net
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
Google Developers Blog
Microsoft Security Blog
Microsoft Security Blog
F
Fortinet All Blogs
Stack Overflow Blog
Stack Overflow Blog
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 聂微东
GbyAI
GbyAI
Jina AI
Jina AI
V
V2EX
Vercel News
Vercel News
IT之家
IT之家
WordPress大学
WordPress大学
M
MIT News - Artificial intelligence
NISL@THU
NISL@THU
V
Visual Studio Blog
C
Cybersecurity and Infrastructure Security Agency CISA

博客园 - 九卷

AI-Native 组织到底应该围绕什么来组织?人还是Agent? 工作的意义、工作的困难认知再思考 LLM大模型技术相关的40个重要概念解释 AI Agent上下文工程(context engineering)知识学习总结 prompt提示词和prompt-engineering提示词工程基础学习 LLM大模型中AI-Agent智能体应用开发相关知识介绍 职场沟通中的认知盲点与突破之道-以沟通视窗和邓克效应为核心的深度分析 AI大模型时代中小软件研发公司团队组织如何变革? 《创业维艰 如何完成比难更难的事》学习笔记 LLM大模型技术基础知识学习 生意的本质 读书笔记与总结 职场中员工的进取心千差万别,为什么?本文从动机、性格特质等维度进行分析 100种思维模型概念(多个角度分析问题) 为什么有的人说“越老思维越固化”?怎么才能具备成长型思维? 技术管理:产品经理PM和技术开发人员RD之间常见的矛盾有哪些 技术管理:搭建团队研发管理体系的一个框架概述 人生四大支柱 - 健康,金钱,工作,关系 大龄程序员35岁后职业发展出路:认知与思路转变 如何对一个问题进行全面思考?怎么深度思考? 周期思维:思考事物运行方式的一把好“钥匙”
100多行代码实现一个最简单的Agent(用ReAct)
九卷 · 2026-04-13 · via 博客园 - 九卷

一、介绍

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

二、ReAct 最简单介绍

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

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

三、实现代码

第一步:调用大模型API

这类调用 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"]

第二步:实现ReAct的Agent

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 程序:

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. 安装依赖

运行

pip install requests

2. 获取 DeepSeek API Key

需要充点钱

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

3. 运行

运行

python react_agent.py

4. CLI 使用示例

输入:1+1等于几

agent运行

agent运行2

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

把上面的程序扩展为带有联网搜索能力的 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}\n链接:{url}")
        
        if not results:
            return "未搜索到相关信息"
        
        return "\n".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}\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。

运行:

python react_agent.py

运行Agent

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

运行Agent

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

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

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

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

[完]