เฟรมเวิร์ก ReAct: คิด ลงมือทำ สังเกต
ทำความเข้าใจวงจร ReAct ซึ่งโมเดลสร้าง Thought เลือก Action รับ Observation และทำซ้ำจนได้ Final Answer
เฟรมเวิร์ก ReAct: คิด ลงมือทำ สังเกต เป็นบทเรียน AI Engineering Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Engineering Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Engineering Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Is the ReAct Framework?
ReAct (Reasoning + Acting) is a prompting framework that interleaves the model's internal reasoning with external actions. Instead of producing a final answer immediately, the model generates a Thought, chooses an Action, receives an Observation from executing that action, and repeats the cycle until it can give a Final Answer.
The Think-Act-Observe Loop
Each iteration of the ReAct loop has three phases:
- Thought: The model reasons about what it knows and what it needs to find out next.
- Action: The model calls a tool — such as a web search, a calculator, or a database lookup.
- Observation: The result of the tool call is returned and appended to the model's context.
The loop continues until the model emits Final Answer: with its conclusion.
ReAct Trace Example
Here is a concrete trace of a ReAct agent answering 'What is the population of Tokyo?' using a search tool. Notice how each step builds on the previous observation.
# ReAct trace (pseudocode showing the reasoning loop)
# Iteration 1
Thought_1 = 'I need to find the current population of Tokyo. I will search for it.'
Action_1 = 'search("Tokyo population 2024")'
Observation_1 = 'According to the 2023 census, Tokyo has approximately 13.96 million people in the city proper.'
# Iteration 2
Thought_2 = 'I have the population. I can now give a final answer.'
Final_Answer = 'The population of Tokyo is approximately 13.96 million people.'Why ReAct Outperforms Direct Prompting
Direct prompting asks the model to answer from memory, leading to hallucinations on factual questions. Chain-of-thought prompting improves reasoning but still cannot access external information. ReAct combines both: explicit reasoning traces like chain-of-thought plus the ability to gather fresh information through tool calls.
ReAct Prompt Structure
The ReAct system prompt teaches the model the exact format to use. It lists available tools with their descriptions and shows examples of the Thought/Action/Observation/Final Answer pattern. The model learns to follow this format precisely from the prompt.
REACT_SYSTEM_PROMPT = '''You are an AI assistant with access to these tools:
- search(query: str): Search the web for up-to-date information.
- calculator(expression: str): Evaluate a mathematical expression.
- lookup(topic: str): Look up a topic in the knowledge base.
Always follow this exact format:
Thought: [your reasoning about what to do next]
Action: tool_name(arguments)
Observation: [result of the action, provided by the system]
... (repeat as needed)
Final Answer: [your final response to the user]
Begin!'''Parsing Thought, Action, and Observation
Your application code acts as the runtime for the ReAct loop. After each model response, parse the output to extract the action name and arguments, execute the corresponding Python function, format the result as an observation, append it to the message history, and call the model again.
import re
def parse_react_output(text: str):
'''Extract action name and argument from a ReAct model output.'''
action_match = re.search(r'Action:\s*(\w+)\((.*)\)', text)
if action_match:
tool_name = action_match.group(1)
tool_input = action_match.group(2).strip('\"\' ')
return tool_name, tool_input
if 'Final Answer:' in text:
answer = text.split('Final Answer:')[-1].strip()
return 'final', answer
return None, NoneThe Agent Execution Loop
The execution loop calls the LLM, parses its output, dispatches the tool, appends the observation, and loops. A max_iterations guard prevents infinite loops when the model cannot resolve a task.
from openai import OpenAI
client = OpenAI()
def run_react_agent(user_query: str, tools: dict, max_iterations: int = 10) -> str:
messages = [
{'role': 'system', 'content': REACT_SYSTEM_PROMPT},
{'role': 'user', 'content': user_query}
]
for i in range(max_iterations):
resp = client.chat.completions.create(model='gpt-4o', messages=messages)
output = resp.choices[0].message.content
messages.append({'role': 'assistant', 'content': output})
tool_name, tool_input = parse_react_output(output)
if tool_name == 'final':
return tool_input
if tool_name and tool_name in tools:
observation = tools[tool_name](tool_input)
messages.append({'role': 'user', 'content': f'Observation: {observation}'})
else:
messages.append({'role': 'user', 'content': 'Observation: Tool not found.'})
return 'Max iterations reached without a final answer.'Registering Simple Tools
Tools are just Python functions. You register them in a dictionary mapping tool name to function. The functions receive a string argument and return a string result — this keeps the interface simple and consistent with what the model expects to see as observations.
import math
def calculator_tool(expression: str) -> str:
try:
# Restrict to safe math expressions
allowed_names = {k: v for k, v in math.__dict__.items() if not k.startswith('_')}
result = eval(expression, {'__builtins__': {}}, allowed_names)
return str(result)
except Exception as e:
return f'Error: {e}'
def search_tool(query: str) -> str:
# Stub — replace with real web search API
return f'Top result for "{query}": [placeholder result]'
# Register tools
tools = {
'calculator': calculator_tool,
'search': search_tool
}Multi-Hop Reasoning with ReAct
ReAct shines on multi-hop questions that require chaining multiple pieces of information. For example: 'Who is the CEO of the company that makes GPT-4, and what year was that company founded?' The agent first searches for the CEO, then uses that result to look up the company's founding year — two separate tool calls chained by reasoning.
ReAct vs. Pure Chain-of-Thought
Chain-of-Thought (CoT) improves reasoning by having the model think step by step, but it cannot access external information. ReAct adds actions to CoT, letting the model fetch real data, run computations, and verify facts. The trade-off: ReAct is slower (multiple API calls) but far more accurate on tasks requiring current or specialized knowledge.
Debugging ReAct with Traces
When a ReAct agent produces the wrong answer, inspect the full Thought/Action/Observation trace. Common failure patterns include: the model inventing an observation instead of calling the tool, parsing errors that skip tool execution, and incorrect reasoning in the Thought step that leads to a wrong action choice.
- Log every message appended to the context
- Check that tool output was actually appended before the next model call
- Verify the action regex matches the model's output format
Quick Check
Test your understanding of the ReAct framework.
Lesson Recap
In this lesson you learned: ReAct interleaves Thought, Action, and Observation in a loop, your application code acts as the runtime that executes tools and appends observations, and max_iterations guards prevent infinite agent loops. Next up we learn to define custom tools so your agent can do exactly what your application needs.
คำถามที่พบบ่อย
บทเรียน “เฟรมเวิร์ก ReAct: คิด ลงมือทำ สังเกต” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “เฟรมเวิร์ก ReAct: คิด ลงมือทำ สังเกต” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Engineering Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Engineering Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “เฟรมเวิร์ก ReAct: คิด ลงมือทำ สังเกต”
ทำความเข้าใจวงจร ReAct ซึ่งโมเดลสร้าง Thought เลือก Action รับ Observation และทำซ้ำจนได้ Final Answer คุณปฏิบัติ AI Engineering Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Engineering Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Engineering Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “เฟรมเวิร์ก ReAct: คิด ลงมือทำ สังเกต” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Engineering Academy นี้ได้ไหม
ได้ บทเรียน AI Engineering Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- เฟรมเวิร์ก ReAct: คิด ลงมือทำ สังเกต
- การกำหนดเครื่องมือสำหรับ Agent
- การสร้าง Agent แบบ ReAct ด้วย LangChain
- การจัดการข้อผิดพลาดและลูปของเอเจนต์