Runoob Tutorial ArchiveEnglish

Reasoning & Planning

Reasoning & Planning

In the process of building autonomous AI Agents, if the Large Language Model (LLM) is the Agent's brain and Tool Use is its limbs, then Reasoning & Planning is the core engine that upgrades it from a simple Q&A machine to an autonomous problem solver.

Complex real-world tasks often cannot be completed in a single pass generation. AI needs the ability to decompose goals, logically infer, explore paths, self-correct, and schedule tools.

The following are the most mainstream reasoning and planning frameworks in the industry.


Chain of Thought (CoT)

Step-by-step reasoning capability

Traditional LLMs often provide intuitive, one-shot answers.

The core idea of Chain-of-Thought (CoT) is:Forcing the model to explicitly output intermediate reasoning steps (Let's think step by step) before outputting the final answer.This approach can significantly activate the model's potential in complex mathematical, logical reasoning, and common sense Q&A.

CoT not only gives the model more computation time (the number of tokens represents the amount of computation) but also allows subsequent generations to be based on the correct logic from before.

Example: Few-shot CoT prompt design

Guiding the model to perform CoT reasoning by providing examples that include the reasoning process.

prompt

=

"""
Question: Roger has 5 tennis balls. He bought 2 cans of tennis balls. Each can has 3 tennis balls. How many tennis balls does he have in total now?
Answer: Roger started with 5 tennis balls. 2 cans of tennis balls, with 3 in each, total 2 * 3 = 6 tennis balls. 5 + 6 = 11. The answer is 11.

Question: The cafeteria has 23 apples. If they use 20 for lunch and then buy 6 more, how many apples do they have now?
Answer: The cafeteria originally had 23 apples. After using 20, there are 23 - 20 = 3 left. They bought 6 more, so now there are 3 + 6 = 9. The answer is 9.

Question: {user_question}
Answer:"""


ReAct framework (Reasoning + Acting)

Reasoning + Action Loop

If CoT is merely closed-door thinking within the model, thenReAct (Reason + Act)allows the model to open its eyes to the world. It intertwines internal logical reasoning (Thought) with external tool interaction (Action), forming a dynamic closed-loop feedback system.

Under the ReAct paradigm, the Agent followsthe loop of Thought -> Action -> Observationuntil a final conclusion is reached.

ReAct loop architecture diagram Shows the cyclic relationship between Thought, Action, and Observation. Thought Analyze current state and goals Action Call external tools/API Observation User Query

Limitations:ReAct performs excellently in short, clearly-stepped tasks. However, because the entire thought and action history is accumulated in a single context window, it is prone to getting stuck in infinite loops or forgetting the initial goal due to context overload when the task chain is too long.


Plan-and-Execute (Plan-first, Execute-later mode)

To address ReAct's weakness in long-term tasks, Plan-and-Execute decouples thinking and action, adopting a strategy similar to how humans manage large projects:First create a schedule, then work on each item sequentially..

The system is usually divided into two independent roles:

  1. Planner: Responsible for receiving the overall goal and generating a detailed Step-by-Step list of subtasks.
  2. Executor: Responsible for executing these subtasks in sequence. The executor is usually a small ReAct Agent, focusing on completing one small goal at a time.
Plan-and-Execute architecture diagram Complex goal Planner 1. Crawl web pages 2. Extract data 3. Generate report Executor Process subtasks one by one (independent context each time) Final delivery

Tree of Thoughts (ToT) and Tree-structured Multi-path Exploration

Tree-structured Multi-path Exploration

Whether it is CoT or Plan-and-Execute, fundamentally it islinearpath exploration. However, when writing code, solving math problems, or creative writing, humans often conceive multiple solutions, evaluate them, choose the best one, and even backtrack when errors are found.

ToT (Tree of Thoughts)Model the reasoning process as a tree: nodes are the current thought states. The model generates multiple candidate Thoughts at each branching point, and then scores these nodes using an internal Evaluator (e.g., feasible, potentially risky, infeasible). CombiningBFS (Breadth-First Search)orDFS (Depth-First Search)algorithms to decide whether to continue deeper or backtrack and retry.


Task Planning & MCTS (Monte Carlo Tree Search)

Decomposition and search for complex tasks

For strategic games or extremely difficult reasoning tasks (such as cutting-edge mathematical verification or complex code repository refactoring), simple ToT is no longer efficient enough. The industry is beginning to combine LLMs with traditional reinforcement learning search algorithmsMCTS (Monte Carlo Tree Search)Combining (similar to the core logic of AlphaGo).


Reflexion: Self-reflection and error correction

When humans fail a task on the first attempt, they summarize lessons learned and avoid errors in the next attempt.

ReflexionThe framework grants the Agent similar capabilities.

In the Reflexion closed loop, when the Agent's output is judged as a failure (e.g., test case failed, API error), aReviewer mechanismis triggered.

The LLM is required to write a colloquial reflection (Reflection) based on the historical actions and the failure feedback, for example:"I used the wrong API parameter format just now; next time I should consult the documentation before passing JSON."This reflection will be stored in the Episodic Memory as a context prompt for the next attempt, significantly improving the Agent's self-healing ability.

Example: Reflexion's reflection prompt design

reflection_prompt

=

"""
You are an AI assistant trying to write a Python web crawler.
This is the code you just executed: {previous_code}
This is the error message returned by the runtime environment: {error_traceback}

Please deeply reflect:

  1. What is the root cause of the error?
  2. What is your specific modification strategy for the next attempt?

Please record your reflections to guide subsequent actions.
"""


Task Decomposition Strategy and Engineering Practices

In the actual development of production-grade AI agents, relying solely on LLM "zero-shot" for complex planning is unstable. Common hybrid intervention strategies include:

Intervention Strategy Core Practices Applicable Scenarios
Subtask Templatization (SOP) Instead of letting the LLM plan freely, predefine standard operating procedures (SOP) so that the LLM flows within a fixed State Machine. Customer service systems, standardized data cleaning pipelines.
HITL (Human-in-the-Loop) After the Planner generates a task list, execution is interrupted, requiring human users to confirm, modify, or approve before being handed over to the Executor. High-risk operations: such as deleting database records, sending mass emails, or large fund transfers.
RLHF guided planning Utilizing reinforcement learning and human preference feedback to fine-tune the planning capabilities of large models, making them more inclined to generate safe and efficient sequences of steps. Training phase of the underlying large language model foundation (such as OpenAI's o1 model training).

Framework comparison summary

Mode Core mechanism Advantages Drawbacks
CoT Step-by-Step Linear Reasoning Simple implementation, significantly improves basic reasoning accuracy Cannot call external tools, easily gets stuck on one path
ReAct Alternating thought and action loop Dynamically adapts to the environment, can adjust in real-time through observation Context can explode due to accumulation across steps, losing the original intent
Plan-and-Execute Decompose into subtasks first, then execute in isolation Extremely suitable for long-term complex tasks with clear context Not flexible enough when facing sudden changes (when the plan itself is flawed)
ToT / MCTS Tree search, evaluation and backtracking Can solve the most difficult complex logic problems The computational cost is extremely high, and token consumption is exponential.
Reflexion Generates reflective memory based on failure feedback. Possesses the ability to self-correct and continuously evolve. Relies on clear feedback signals (such as code compiler errors).