English 繁體中文 简体中文

如何让 AI 代理可以复用(ReAct,版本 4,一个函数,任何任务)?

林邦源博士 · AI 笔记 · 2026 年 11 月 9 日 · 约 3 分钟阅读

上一篇笔记 建立了一个会用网上搜索研究问题的代理 —— 但问题是写在脚本里的,答案也只会 出现在屏幕上。这篇笔记只做两项结构上的改动,其他一概不变:循环搬进一个 函数,perform_task(task),它接受任何问题;而函数会把 答案以文字形式返回。代理于是变成你的程序可以调用的东西, 而不是你只能读一次的东西。

脚本

这是 ReAct04.py 目前的内容:

# Same ReAct idea as react01.py, but this task needs MORE THAN ONE action,
# so we repeat Think -> Act -> Observe in a loop until the model says "finish".
# Step 1: THINK  -> ask the model to reason about what to do next
# Step 2: ACT    -> ask for ONE action: search[...] or finish[...]
# Step 3: OBSERVE-> run the Tavily web search (a real tool), add the result to the prompt, loop again
import os
import re
from datetime import datetime
from tavily import TavilyClient
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()

client = OpenAI(
    api_key=os.environ.get('DEEPSEEK_API_KEY'),
    base_url="https://api.deepseek.com")
tavily = TavilyClient(api_key=os.environ.get('TAVILY_API_KEY'))

def ask(prompt, stop=None):
    """Send one prompt to the model and return its text reply."""
    response = client.chat.completions.create(
        model="deepseek-flash",
        messages=[{"role": "user", "content": prompt}],
        stop=stop,   # stop writing when this text appears
    )
    return response.choices[0].message.content

# The only tool (action) our agent can use
def search_tavily(query):
    """Return the top web results from Tavily (title, url, short content)."""
    results = tavily.search(query=query, max_results=3)["results"]
    if not results:
        return f"No web results found for '{query}'."
    return "\n".join(f"[{r['title']}] ({r['url']}) {r['content'][:400]}"
                     for r in results)

def perform_task(task):
    """Run the Think -> Act -> Observe loop for one task and return the answer."""
    prompt = f"""Task: {task}
You can use ONE tool: search[query] searches the web (Tavily) and returns the top results.
Today is {datetime.now().strftime('%Y-%m-%d')}.
Work in steps. Each step has a Thought, an Action, and an Observation."""

    for step in range(1, 6):          # at most 5 rounds, so it cannot loop forever
        # ---- Step 1: THINK (Reasoning) ----
        thought = ask(prompt + f"\n\nThought {step}: (reason briefly about what to do next; do not act yet)",
                      stop=["Action"])   # stop the model inventing its own Action/Observation
        print(f"=== Round {step} - Thought ===")
        print(thought)

        # ---- Step 2: ACT — append the reasoning trace, then ask for an action ----
        prompt = prompt + f"\n\nThought {step}: {thought}"
        action = ask(prompt + "\n\nWhat action should be taken based on that? "
                     "Reply with ONLY: search[query] or finish[answer]").strip()
        print(f"=== Round {step} - Action chosen by the model ===")
        print(action)

        if action.startswith("finish"):
            found = re.search(r"finish\[(.*)\]", action, re.S)
            answer = found.group(1) if found else action
            print("=== Final Answer ===")
            print(answer)
            return answer

        # ---- Step 3: OBSERVE — our Python code (not the model) runs the tool ----
        query = re.search(r"search\[(.*)\]", action, re.S)
        observation = search_tavily(query.group(1)) if query else "Invalid action."
        print(f"=== Round {step} - Observation from Tavily web search ===")
        print(observation)
        prompt = prompt + f"\nAction {step}: {action}\nObservation {step}: {observation}"
    else:
        print("=== Stopped: no answer after 5 rounds ===")

perform_task("When did Mark launch Muse")

与上一个脚本相比有什么改变

逐行来看,这是同一个代理。差别在于包装方式:

一次真实运行

=== Round 1 - Thought ===
Thought 1: I need to find out when Mark (likely Mark Zuckerberg) launched Muse. I should search the web for this information, but I need to be careful because "Muse" could refer to different things...
=== Round 1 - Action chosen by the model ===
search[Mark launch Muse date]
=== Round 1 - Observation from Tavily web search ===
[Mark Zuckerberg announces Muse Spark, a new Meta AI model ... | Mashable] ...after Meta launched Muse, an autonomous personal artificial intelligence agent.
[Muse Spark - Wikipedia] ...Muse Spark ... introduced in April 2026 and launched as Muse Spark 1.1 on July 9, 2026...
[Everything new coming to Meta's AI agent Muse | TechCrunch] Muse, which launched in early September...
=== Round 2 - Thought ===
Thought 2: The search results give conflicting dates depending on what "Muse" refers to. I need to distinguish between the Muse AI agent and the underlying Muse Spark model...
=== Round 2 - Action chosen by the model ===
search[Mark Zuckerberg Meta launched Muse AI agent exact date September 2026]
...two more rounds of searching...
=== Round 4 - Action chosen by the model ===
finish[Mark Zuckerberg/Meta launched **Muse**, the personal AI agent, on **September 8, 2026**. If the question refers to **Muse Spark**, that model was introduced in **April 2026** and launched as **Muse Spark 1.1 on July 9, 2026**.]
=== Final Answer ===
Mark Zuckerberg/Meta launched **Muse**, the personal AI agent, on **September 8, 2026**. If the question refers to **Muse Spark**, that model was introduced in **April 2026** and launched as **Muse Spark 1.1 on July 9, 2026**.

摘录为求易读而经过缩短(…);完整运行会把每一轮完整打印出来。

有两点值得注意。第一,第 2 轮做了一件之前那次运行没有做的事:它把代理 Muse 与背后的模型 Muse Spark 分开,因为搜索结果把两者混在 一起。最后的答案同时报告两个日期,并说明哪个是哪个 —— 问题中的含糊之处 是公开解决的,而不是静静带过。第二,答案文字里有 ** 符号: 模型写的是 markdown 粗体。你把它打印出来时,看到的是符号;当另一个程序以 markdown 显示它时,它们就会变成真正的粗体文字。这是返回答案为何重要的一 个小预览 —— 同一段文字现在有两种可能的生命。

在自己的电脑上运行

下载演示程序 (Folder-AI-ReAct04.zip)。zip 内包含三个文件: ReAct04.py(就是上面的脚本)、pyproject.toml (包清单)和 README.md。

  1. 在 Visual Studio Code 打开这个文件夹。
  2. 在文件夹内创建一个名为 .env 的文件,内容有两行:
    DEEPSEEK_API_KEY=your-deepseek-key
    TAVILY_API_KEY=your-tavily-key
    第一个密钥从 DeepSeek 控制台获取,第二个从 Tavily获取; 两者都有免费的起始额度。
  3. 在终端运行:
    uv sync
    uv run ReAct04.py
    uv sync 只需要第一次运行;它会读取 pyproject.toml,并把 openai、 tavily-python 和 python-dotenv 装进这个项目。

现在实验就在最后一行。把它改成 perform_task("What were the three biggest news stories in my city this week?") —— 或者任何其他问题 —— 再运行一次。改一行,就是另一个研究项目。

为什么这个小改动重要

延伸阅读