How does an AI agent think, act and observe (ReAct, version 1)?
Ask a language model for today's temperature and it can only guess — its knowledge ends at training time. ReAct (short for Reasoning and Acting) is the pattern that fixes this. The agent works in a loop of three steps: it thinks about the task in writing, acts by naming a tool to call, and observes the real-world result before giving the final answer. This note builds the smallest possible ReAct agent: one task, one tool, three printed steps, using DeepSeek as the model.
Where the idea comes from
The pattern is from a 2022 research paper, ReAct: Synergizing Reasoning and Acting in Language Models, by researchers at Google Brain and Princeton University. In plain words, the paper says this: before ReAct, a language model could either reason (think through a problem in writing) or act (do things in the world), but not both at once. The authors let the model do the two in turns — write down its thinking, then take an action, then read the result and think again. The thinking keeps the actions on track, and the actions bring back real facts, so the model stops making things up.
The script
This is ReAct01.py as it stands:
# Step 1: THINK -> ask the model to reason step by step (reasoning trace)
# Step 2: ACT -> append that trace to the prompt and ask "What action should be taken?"
# Step 3: OBSERVE-> run the action (a real tool), feed the result back, get the final answer
import os
import requests
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")
def ask(prompt):
"""Send one prompt to the model and return its text reply."""
response = client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content
# The only tool (action) our agent can use
def get_hk_temperature():
"""Return the current temperature in Hong Kong from open-meteo.com."""
params = {"latitude": 22.32, "longitude": 114.17,
"current": "temperature_2m", "timezone": "auto"}
data = requests.get("https://api.open-meteo.com/v1/forecast",
params=params, timeout=10).json()
return f"{data['current']['temperature_2m']}°C"
task = "What is the temperature in Hong Kong today?"
# ---- Step 1: THINK (Reasoning) ----
prompt = f"""Task: {task}
Think step-by-step about how to solve this task. Do not answer yet."""
thought = ask(prompt)
print("=== Step 1: Thought (reasoning trace) ===")
print(thought)
# ---- Step 2: ACT — append the reasoning trace to the prompt, then ask for an action ----
prompt = prompt + f"""
Thought: {thought}
You have ONE tool: get_hk_temperature. What action should be taken based on that? Reply with ONLY: get_hk_temperature or none"""
action = ask(prompt).strip()
print("=== Step 2: Action chosen by the model ===")
print(action)
# ---- Step 3: OBSERVE — our Python code (not the model) runs the tool ----
if "get_hk_temperature" in action:
observation = get_hk_temperature()
else:
observation = "No action taken."
print("=== Step 3: Observation from the real world ===")
print(observation)
# ---- Final answer: the model reasons again, now grounded in the observation ----
prompt = prompt + f"""
Action: {action}
Observation: {observation}
Now give the final answer to the task in one sentence."""
print("=== Final Answer ===")
print(ask(prompt))
What each part does
-
The DeepSeek client. The
openaipackage also speaks to DeepSeek, because DeepSeek follows the same interface. The key comes from a.envfile, loaded byload_dotenv(), so the secret never appears in the code. -
ask(). One helper sends one prompt and returns one string. Every conversation with the model in this script goes through it. -
The one tool.
get_hk_temperature()asks Open-Meteo for the current temperature at Hong Kong's coordinates and returns it as a short string, for example26.8°C. No key is needed. - Step 1 — THINK. The prompt holds the task plus one instruction: think step-by-step, do not answer yet. The reply is a reasoning trace — the model's working, written down.
-
Step 2 — ACT. The trace is appended to the prompt, and
the model is told it has exactly one tool. It must reply with only the tool
name or
none. The model chooses the action; it does not run it. -
Step 3 — OBSERVE. Python — not the model —
checks the chosen action and runs the tool. The result, for example
26.8°C, is the observation. - The final answer. The prompt now contains the task, the trace, the action and the observation. The model writes one sentence grounded in a real number instead of a guess.
Running it on your own computer
Download the demo program
(Folder-AI-ReAct01.zip). The zip holds three files:
ReAct01.py (the script above), pyproject.toml (the
package list) and README.md.
- Open the folder in Visual Studio Code.
-
Create a file named
.envin the folder with one line:
Get a key from the DeepSeek console; new accounts come with trial credit.DEEPSEEK_API_KEY=your-key-here - In the Terminal, run:
uv sync uv run ReAct01.pyuv syncis needed only the first time; it readspyproject.tomland installsopenai,requestsandpython-dotenvinto the project.
You should see four blocks printed in order: the reasoning trace, the chosen
action (get_hk_temperature), the observed temperature, and the
final one-sentence answer that uses the real number. Here is one real run:
=== Step 1: Thought (reasoning trace) ===
Let’s break this down step-by-step:
1. **Identify the goal** – The user wants the current temperature in Hong Kong today.
2. **Determine location specifics** – Hong Kong is a major city; its weather can vary slightly by district but generally a single official temperature reading is used for “Hong Kong” in weather reports.
3. **Check date/time awareness** – “Today” means the current date. My knowledge isn’t real-time, so I can’t know the live temperature without up-to-date data.
4. **Possible sources** – Could use:
- Real-time weather websites (e.g., Hong Kong Observatory).
- Weather apps or APIs.
- Search engine results for “Hong Kong temperature”.
5. **Consider limitations** – Without live access or browsing ability, I can’t retrieve the exact current temperature.
6. **Formulate approach for answer** – If I had browsing or API tools, I’d check the Hong Kong Observatory or a trusted weather source right now and report the temperature in °C (and possibly °F).
7. **Alternate if no access** – I’d explain I can’t provide real-time data and suggest how the user can check (e.g., HKO website, weather apps).
This reasoning sets up how to get the answer, but the actual temperature value would need current data.
=== Step 2: Action chosen by the model ===
get_hk_temperature
=== Step 3: Observation from the real world ===
27.1°C
=== Final Answer ===
The temperature in Hong Kong today is 27.1°C.
Two things are worth noticing in the trace. First, the model says it plainly: “My knowledge isn’t real-time” — given only the task, it already knows it cannot answer from memory. Second, its plan (“check a trusted weather source”) is exactly what the tool then does. The loop turns the model’s own admission into a real answer.
Why this pattern matters
- The model decides, the code executes. The model never touches the internet; your Python stays in charge of what actually runs. That is what makes the pattern safe to extend.
- Each step is visible. The trace, the chosen action and the observation are printed, so when the agent misbehaves you can see where it went wrong — a wrong thought, a wrong choice, or a tool problem.
- More tools, same loop. To give the agent a second ability (the time, a search, a file), add the function and mention it in the Step 2 prompt. The three-step rhythm does not change.
Further reading
- ReAct: Synergizing Reasoning and Acting in Language Models — the paper that named the pattern.
- DeepSeek API documentation — models, keys and pricing.
- Open-Meteo API documentation — every field the weather call can return.