English 繁體中文 简体中文

How do you make an AI agent reusable (ReAct, version 4, one function, any task)?

Howard Pong Yuen Lam · AI Notes · November 9, 2026 · 3 min read

The previous note built an agent that researches a question with web search — but the question is written into the script, and the answer only appears on screen. This note makes two structural changes and no others: the loop moves into a function, perform_task(task), that accepts any question, and the function returns the answer as text. The agent becomes something your program can call, not something you read once.

The script

This is ReAct04.py as it stands:

# 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")

What changed from the previous script

Line for line, this is the same agent. The difference is packaging:

One real run

=== 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**.

Extracts shortened (…) for readability; the full run prints every round in full.

Two things are worth noticing. First, round 2 does something the earlier run did not: it separates Muse the agent from Muse Spark the underlying model, because the search results mixed the two. The final answer reports both dates and says which is which — the ambiguity in the question is resolved openly, not silently. Second, the answer text contains ** marks: the model wrote markdown bold. When you print it, you see the marks; when another program displays it as markdown, they become real bold text. That is a small preview of why returning the answer matters — the same text now has two possible lives.

Running it on your own computer

Download the demo program (Folder-AI-ReAct04.zip). The zip holds three files: ReAct04.py (the script above), pyproject.toml (the package list) and README.md.

  1. Open the folder in Visual Studio Code.
  2. Create a file named .env in the folder with two lines:
    DEEPSEEK_API_KEY=your-deepseek-key
    TAVILY_API_KEY=your-tavily-key
    Get the first from the DeepSeek console and the second from Tavily; both have free starting credit.
  3. In the Terminal, run:
    uv sync
    uv run ReAct04.py
    uv sync is needed only the first time; it reads pyproject.toml and installs openai, tavily-python and python-dotenv into the project.

Now the experiment is in the last line. Change it to perform_task("What were the three biggest news stories in my city this week?") — or anything else — and run again. One line, a different research project.

Why this small change matters

Further reading