Runoob Tutorial ArchiveEnglish

Python implementation of reasoning and planning

Python implementation of reasoning and planning

This chapter introduces the core intelligent capabilities of AI Agents, namely reasoning and planning.

Unlike traditional instruction execution modes, Agents with reasoning capabilities can undergo complex thinking processes.

It can decompose complex tasks into executable steps and make decisions based on context.


ReAct framework

ReAct (Reasoning + Acting) is a framework that combines reasoning and action.

In the ReAct mode, the Agent alternates between reasoning and acting, forming a closed loop.

Reasoning guides actions, and the results of the actions are fed back into the reasoning process, forming a continuous loop.

ReAct simulates the human problem-solving process: thinking before taking an action, observing the results after the action, and then continuing to reason based on the new information.

Working Principle

The core idea of ReAct can be summarized as a loop of three stages:

First step, the reasoning stage. The Agent generates a thought about the next action based on the current context.

Second step, the action stage. The Agent executes the selected tool or action.

Third step, the observation stage. The Agent receives the action result, updates the context, and returns to the first step to continue reasoning.

Code Implementation

Below is a simplified implementation of a ReAct Agent:

Basic ReAct Agent implementation

class

ReActAgent:

   

"""
Agent implementation of the ReAct framework
Core mechanism: Thought -> Action -> Observation -> Thought (loop)
"""

   

   

def

init

(

self

,

llm

,

tools

,

max_iterations

=

5

)

:

       

LLM instance for inference and generation

       

self

.

llm

=

llm

       

List of available tools

       

self

.

tools

=

tools

       

Maximum number of iterations to prevent infinite loops

       

self

.

max_iterations

=

max_iterations

   

   

def

run

(

self

,

task

)

:

       

"""
Execute the ReAct loop
:param task: User task description
:return: Execution result
"""

       

Initialize the context, including task and history information

context

=

{

           

"task"

: task

,

           

"steps"

:

[

]

,

     

Record of executed steps

           

"observations"

:

[

]

 

Observation record

       

}

       

       

for

i

in

range

(

self

.

max_iterations

)

:

           

Phase one: Reasoning - Generate the next action based on the current context

reasoning

=

self

.

llm

.

reason

(

context

)

           

           

Determine whether to execute a tool or return the answer directly

           

if

reasoning.

needs_action

:

               

Select the tool to use

action

=

reasoning.

select_tool

(

self

.

tools

)

               

Execute the tool and get the observation result

observation

=

action.

execute

(

reasoning.

tool_input

)

               

Add the observation to the context

context

[

"observations"

]

.

append

(

observation

)

           

else

:

               

No action is needed, return the answer derived from the reasoning directly

               

return

reasoning.

answer

       

       

Did not complete even after reaching the maximum number of iterations

       

return

"Maximum iteration limit reached"

Typical application scenarios

The ReAct pattern is particularly suitable for the following scenarios:

Tasks that require exploration and information gathering in an environment before completion.

Intelligent search scenarios: The Agent needs to search for information first, and then reason and summarize based on the search results.

Conversational Q&A: The Agent needs to clarify requirements and obtain information through multiple rounds of dialogue.

Complex problem solving: The problem cannot be solved in one step and requires multiple intermediate steps.

Note: The advantage of the ReAct mode is its flexibility, allowing it to dynamically adjust subsequent actions based on the results of each step. However, this also means that the execution path may be unstable, making it suitable for exploratory tasks.


Chain of Thought (CoT)

Chain of Thought is a technique that prompts the model to show its step-by-step reasoning process.

CoT does not ask the model to give a direct answer, but rather guides it to first show the reasoning steps before reaching the final conclusion.

Why is Chain of Thought needed?

Directly asking the model to output an answer has several problems:

Intermediate steps of complex reasoning are easily ignored or skipped.

It is difficult to pinpoint where the error occurred.

Users cannot understand the model's thought process.

Chain-of-Thought solves these problems by requiring the model to show its reasoning process.

Zero-shot CoT

Zero-shot CoT is a method that can elicit step-by-step reasoning ability without examples.

It only requires adding a trigger statement like "Let's think step by step" at the end of the prompt.

Zero-shot CoT example

Zero-shot CoT prompt template

prompt

=

"""
Problem: Xiao Ming has 5 apples, Xiao Hong gave him 3, and Xiao Ming ate 2. How many are left?
Let's think step by step:
"""

Call the language model

response

=

llm.

generate

(

prompt

)

Model output example:

Step 1: Calculate the total number of apples Xiao Ming has after receiving them

Xiao Ming originally had 5 apples, and Xiao Hong gave him 3

5 + 3 = 8 items

Step 2: Calculate the remaining quantity after eating

Xiao Ming ate 2 items

8 - 2 = 6 items

Conclusion: 6 apples remain

Few-shot CoT

Few-shot CoT helps the model learn specific reasoning patterns by providing examples that include detailed reasoning processes.

When Zero-shot CoT performs poorly, you can try Few-shot CoT.

Few-shot CoT example

Few-shot CoT prompt template

prompt

=

"""
Example 1:
Question: Xiao Zhang has 10 yuan, bought 3 books, each costing 2 yuan, how much is left?
Let's think step by step:

Example 2:
Question: A cat catches 2 mice per hour, how many did it catch in 8 hours?
Let's think step by step:

Question: {user_question}
Let's think step by step:
"""

response

=

llm.

generate

(

prompt

)

Advantages of Chain-of-Thought

Chain-of-Thought technology brings three core values:

Traceability: Decomposing complex reasoning into traceable intermediate steps, facilitating understanding of the reasoning process.

Interpretability: Enhancing model interpretability, allowing users to know where the answer comes from.

Accuracy Improvement: Significantly enhances the accuracy of complex reasoning tasks, with noticeable effects in mathematical and logical tasks.


Tree of Thoughts (ToT)

Tree of Thoughts is an extension of Chain-of-Thought, no longer limited to linear reasoning.

ToT explores multiple possible paths at each reasoning node, forming a tree structure.

This enables the Agent to perform multi-path exploration, backtracking, and global evaluation.

Difference from Chain-of-Thought

CoT adopts linear reasoning, where each step depends on the conclusion of the previous step, suitable for problems with a clear path.

ToT adopts spatial reasoning, considering multiple possible branches simultaneously, suitable for problems requiring exploration and planning.

Code implementation

Basic implementation of ToT Agent

class

ToTAgent:

   

"""
Tree of Thoughts Agent implementation
Core mechanism: generate multiple candidate branches at each node, evaluate, and select the optimal continuation
"""

   

   

def

init

(

self

,

llm

,

max_depth

=

4

,

beam_size

=

3

)

:

       

LLM instance

       

self

.

llm

=

llm

       

Maximum search depth

       

self

.

max_depth

=

max_depth

       

Number of candidate nodes retained per layer (beam width)

       

self

.

beam_size

=

beam_size

   

   

def

solve

(

self

,

problem

)

:

       

"""
Use the ToT framework to solve the problem
:param problem: Problem description
:return: Optimal solution
"""

       

Create the root node, including the problem as the initial state

root

=

ThoughtNode

(

problem

,

depth

=

0

)

       

Initialize the frontier node list (nodes to be expanded)

frontier

=

[

root

]

       

       

Layer-by-layer expansion

       

for

depth

in

range

(

self

.

max_depth

)

:

           

Store all candidate nodes

all_candidates

=

[

]

           

           

Iterate over all frontier nodes

           

for

node

in

frontier:

               

Generate multiple candidate next steps for the current node

candidates

=

self

.

llm

.

generate_thoughts

(

                    node.

content

,

   

Current node content

n

=

self

.

beam_size

 

Number of generations

               

)

               

Create a new node and add it to the candidate list

               

for

cand

in

candidates:

all_candidates.

append

(

ThoughtNode

(

cand

,

depth +

1

,

parent

=

node

)

                   

)

           

           

Evaluate all candidate nodes

evaluated

=

self

.

evaluator

.

rank

(

all_candidates

)

           

           

Select the optimal beam_size nodes as the next frontier

frontier

=

evaluated

[

:

self

.

beam_size

]

           

           

Check if a solution is found

           

if

self

.

is_solution

(

frontier

)

:

               

break

       

       

Backtrack to find the optimal solution

       

return

self

.

backtrack_best

(

frontier

)

Application Scenarios

ToT is especially suitable for scenarios that require making choices or planning:

Creative Writing: Generating multiple story development directions and selecting the optimal one after evaluation.

Strategic Planning: Evaluating the potential outcomes of multiple action plans.

Complex Decision Making: Decision problems that require considering multiple possibilities.


Task Planning and MCTS

Monte Carlo Tree Search (MCTS) is a heuristic search algorithm used for complex decision-making problems.

MCTS has wide applications in Agent planning, especially suitable for game AI and complex task planning.

Core Idea

MCTS evaluates the potential value of each decision node by simulating random games.

It does not need to evaluate all possible paths, but guides the search direction through sampling and statistics.

The Four Steps of MCTS

The first step, Selection: Starting from the root node, recursively select the optimal child node until a leaf node is reached.

Use the UCB (Upper Confidence Bound) formula when selecting to balance exploration and exploitation.

Step two, Expansion: Add one or more child nodes to a leaf node.

Step three, Simulation: Start from the new node and randomly simulate the game until it ends.

Step four, Backpropagation: Update the statistics of all nodes along the simulated path.

Code implementation

MCTS planner implementation

import

math

class

MCTSNode:

   

"""
MCTS tree node
Stores node state, statistics, and child node relationships
"""

   

   

def

init

(

self

,

state

,

parent

=

None

,

action

=

None

)

:

       

Current state

       

self

.

state

=

state

       

Parent node reference

       

self

.

parent

=

parent

       

Action from the parent node to this node

       

self

.

action

=

action

       

Child node list

       

self

.

children

=

[

]

       

Number of times this node has been accessed

       

self

.

visit_count

=

0

       

Cumulative reward value of this node

       

self

.

reward

=

0.0

   

   

def

is_fully_expanded

(

self

)

:

       

"""Check if all possible child nodes have been expanded"""

       

return

len

(

self

.

children

)

0

   

   

def

is_terminal

(

self

)

:

       

"""Check if it is a terminal node (game over or goal achieved)"""

       

return

self

.

state

.

is_terminal

(

)

   

   

def

uct_child

(

self

)

:

       

"""
Select the optimal child node using the UCT formula
UCT = reward/visits + C * sqrt(ln(parent_visits)/visits)
C is the exploration constant, usually set to sqrt(2)
"""

       

Exploration constant, balances exploration and exploitation

C

=

math

.

sqrt

(

2

)

       

       

return

max

(

           

self

.

children

,

            key

=

lambda

c: c.

reward

/ c.

visit_count

C *

math

.

sqrt

(

math

.

log

(

self

.

visit_count

)

/ c.

visit_count

)

       

)

class

MCTSPlanner:

   

"""
MCTS planner
Use Monte Carlo Tree Search to generate action plans for the Agent
"""

   

   

def

init

(

self

,

simulation_limit

=

1000

,

exploration_constant

=

1.41

)

:

       

Maximum simulation count

       

self

.

simulation_limit

=

simulation_limit

       

Exploration constant

       

self

.

exploration_constant

=

exploration_constant

   

   

def

plan

(

self

,

initial_state

)

:

       

"""
Plan starting from the initial state
:param initial_state: initial state
:return: Optimal action
"""

       

Create root node

root

=

MCTSNode

(

initial_state

)

       

       

Execute multiple simulations

       

for

_

in

range

(

self

.

simulation_limit

)

:

           

1. Selection: Select the optimal child node from the root node downwards until a leaf node is reached

node

=

self

._selection

(

root

)

           

           

2. Expansion: If it is not a terminal node, expand a new node

           

if

not

node.

is_terminal

(

)

:

node

=

self

._expansion

(

node

)

           

           

3. Simulation: Randomly simulate from a new node until termination

reward

=

self

._simulation

(

node

)

           

           

4. Backpropagation: Update statistics of all nodes on the path

           

self

._backpropagation

(

node

,

reward

)

       

       

Return the action corresponding to the optimal child node of the root node

       

return

root.

best_child

(

)

.

action

   

   

def

_selection

(

self

,

node

)

:

       

"""Selection phase: select the optimal child node"""

       

while

node.

is_fully_expanded

(

)

and

not

node.

is_terminal

(

)

:

node

=

node.

uct_child

(

)

       

return

node

   

   

def

_expansion

(

self

,

node

)

:

       

"""Expansion phase: Add new child nodes"""

       

Generate all possible actions

possible_actions

=

node.

state

.

get_possible_actions

(

)

       

Create a child node for each action

       

for

action

in

possible_actions:

            new_state

=

node.

state

.

apply_action

(

action

)

child

=

MCTSNode

(

new_state

,

parent

=

node

,

action

=

action

)

node.

children

.

append

(

child

)

       

Return a random child node (a deterministic strategy can also be used)

       

return

node.

children

[

0

]

   

   

def

_simulation

(

self

,

node

)

:

       

"""Simulation phase: random simulation until game end"""

state

=

node.

state

       

while

not

state.

is_terminal

(

)

:

           

Randomly select action

actions

=

state.

get_possible_actions

(

)

action

=

random

.

choice

(

actions

)

state

=

state.

apply_action

(

action

)

       

Return final reward

       

return

state.

get_reward

(

)

   

   

def

_backpropagation

(

self

,

node

,

reward

)

:

       

"""Backpropagation: Update statistics"""

       

while

node

is

not

None

:

            node.

visit_count

=

1

node.

reward

=

reward

node

=

node.

parent

Note: MCTS has a high computational cost and is suitable for scenarios requiring deep planning with clear termination conditions. For tasks with high real-time requirements, it may be necessary to limit the number of simulations or use other methods.


Reflexion (Self-Reflection)

Reflexion is a technique that gives Agents the ability to self-reflect.

By adding a reflection mechanism to the Agent, it can analyze the cause of failure, adjust its strategy, and retry after a failure.

Core Idea

The Agent not only executes actions but also observes the results and reflects: Why did I fail? How should I improve next time?

This ability is crucial for continuous learning and self-improvement.

Code Implementation

Reflexion Agent Implementation

class

ReflexionAgent:

   

"""
An Agent with self-reflection capabilities
Core mechanism: Execute -> Review -> Reflect -> Retry
"""

   

   

def

init

(

self

,

actor

,

reviewer

,

max_retries

=

3

)

:

       

Executor: responsible for executing specific tasks

       

self

.

actor

=

actor

       

Reviewer: responsible for evaluating execution results

       

self

.

reviewer

=

reviewer

       

Maximum retry count

       

self

.

max_retries

=

max_retries

   

   

def

run

(

self

,

task

)

:

       

"""
Executes a task with self-reflection
:param task: Task description
:return: Execution result
"""

       

Maintenance execution history

history

=

[

]

       

       

for

attempt

in

range

(

self

.

max_retries

)

:

           

Phase one: Attempt to execute the task

result

=

self

.

actor

.

execute

(

task

,

history

)

           

           

Record this attempt

history.

append

(

{

               

"attempt"

: attempt

,

               

"result"

: result

           

}

)

           

           

Phase Two: Review Results

feedback

=

self

.

reviewer

.

evaluate

(

task

,

result

)

           

           

Phase Three: Check for success

           

if

feedback.

is_success

:

               

return

result

           

           

Phase Four: Reflect on Failure Reasons

           

Generate a new strategy prompt to guide the next attempt

reflection

=

self

.

reviewer

.

reflect

(

task

,

         

original task

result

,

       

Failure result

feedback

Review feedback

           

)

           

           

Add the reflection result to the history for reference in the next attempt

history.

append

(

{

               

"type"

:

"reflection"

,

               

"content"

: reflection

           

}

)

       

       

All retries failed, return history

       

return

history

class

Reviewer:

   

Reviewer: Evaluates execution results and generates reflections

   

   

def

evaluate

(

self

,

task

,

result

)

:

       

"""
Evaluate execution result
:return: An object containing success status and detailed feedback
"""

       

Check if the result meets the task requirements

is_success

=

self

.

check_success

(

task

,

result

)

       

       

if

is_success:

           

return

EvaluationResult

(

is_success

=

True

)

       

else

:

           

Analysis of generation failure reasons

failure_reasons

=

self

.

analyze_failures

(

task

,

result

)

           

return

EvaluationResult

(

is_success

=

False

,

reasons

=

failure_reasons

           

)

   

   

def

reflect

(

self

,

task

,

result

,

feedback

)

:

       

"""
Generate reflection content
Help Actor understand the reason for failure and improve strategy
"""

prompt

=

f

"""
Task: {task}
Execution result: {result}
Failure reason: {feedback.reasons}

Please analyze the reason for failure and provide suggestions for improvement.
Key points to explain:

  1. Where did the problem occur?
  2. How should it be avoided next time?
  3. What strategy needs to be changed?
    """

       

return

self

.

llm

.

generate

(

prompt

)

Application Scenarios

Reflexion is particularly suitable for the following scenarios:

Tasks that require continuous improvement, such as dialogue systems and code generation.

Scenarios where the cost of error is high but the cost of retrying is low.

Situations that require learning from failures.


Task Decomposition Strategy

Complex tasks usually need to be broken down into manageable subtasks.

Effective task decomposition is the foundation of planning ability.

Recursive Task Decomposition

Recursively decompose the task into smaller subtasks until the subtasks can be executed directly.

Recursive Task Decomposition

def

decompose

(

task

,

is_executable_fn

,

decompose_fn

)

:

   

"""
Recursively decompose the task
:param task: The task to be decomposed
:param is_executable_fn: A function to determine if the task can be executed directly
:param decompose_fn: The function to decompose the task
:return: List of executable tasks
"""

   

If the task can be executed directly, return it directly

   

if

is_executable_fn

(

task

)

:

       

return

[

task

]

   

   

Decompose the task into subtasks

= subtasks

=

decompose_fn

(

task

)

   

   

Recursively decompose each subtask

result

=

[

]

   

for

subtask

in

subtasks:

       

Recursively call the decomposition function for subtasks

result.

extend

(

decompose

(

subtask

,

is_executable_fn

,

decompose_fn

)

       

)

   

   

return

result

Example: Determine if the task is executable

def

is_code_complete

(

task

)

:

   

"""Check if the task can execute code directly"""

   

return

task.

get

(

"type"

)

==

"code"

and

len

(

task.

get

(

"dependencies"

,

[

]

)

)

==

0

Example: Decomposing complex tasks

def

decompose_programming_task

(

task

)

:

   

"""Decompose programming tasks"""

   

if

"write_function"

in

task

[

"type"

]

:

       

return

[

           

{

"type"

:

"understand_requirements"

,

"task"

: task

[

"spec"

]

}

,

           

{

"type"

:

"write_code"

,

"spec"

: task

[

"spec"

]

}

,

           

{

"type"

:

"write_tests"

,

"function"

: task

[

"function_name"

]

}

,

           

{

"type"

:

"verify_tests"

,

"function"

: task

[

"function_name"

]

}

       

]

   

return

[

task

]

Parallel task decomposition

Identify independent subtasks that can be executed in parallel to improve execution efficiency.

This is a key strategy for accelerating task execution.

Hierarchical task decomposition

Divide tasks into different levels of abstraction, where high-level tasks call low-level tasks, forming a task hierarchy tree.

Suitable for complex systems that require multiple levels of abstraction.


Plan-and-Execute Mode

Plan-and-Execute is an architectural pattern that separates planning and execution.

The Agent first plans the entire task flow completely, and then executes according to the plan.

Difference from ReAct

ReAct infers and executes concurrently, making it more flexible but potentially unstable in its path.

Plan-and-Execute plans first and executes later, making it more stable but lacking dynamic adjustment capabilities.

Code Implementation

Plan-and-Execute Agent Implementation

class

PlanAndExecuteAgent:

   

"""
Agent for the Plan-and-Execute architecture
Core mechanism: plan completely first, then execute according to the plan
"""

   

   

def

init

(

self

,

planner

,

executor

)

:

       

Planner: responsible for formulating the execution plan

       

self

.

planner

=

planner

       

Executor: responsible for executing specific steps

       

self

.

executor

=

executor

   

   

def

run

(

self

,

task

)

:

       

"""
Execute task
Divided into planning phase and execution phase
"""

       

==================== Planning Phase ====================

       

Generate a complete execution plan at once

plan

=

self

.

planner

.

create_plan

(

task

)

       

       

==================== Execution Phase ====================

results

=

[

]

       

       

Execute in planned order

       

for

step

in

plan.

steps

:

           

Execute the current step

result

=

self

.

executor

.

execute

(

step

)

results.

append

(

result

)

           

           

Check if replanning is necessary

           

For example, if the execution result does not match the expectation or an unexpected situation occurs

           

if

self

.

needs_replan

(

results

)

:

               

Replan based on the current result

plan

=

self

.

planner

.

replan

(

task

,

results

)

       

       

Integrate all results

       

return

self

.

summarize

(

results

)

   

   

def

needs_replan

(

self

,

results

)

:

       

"""
Determine if replanning is necessary
Check if the execution result meets expectations
"""

       

Get the last result

last_result

=

results

[

1

]

       

       

If the result is clearly not as expected, replanning is required

       

if

last_result.

is_unexpected

(

)

:

           

return

True

       

       

If the result prevents subsequent steps from being executed, replanning is required

       

if

last_result.

blocks_future

(

)

:

           

return

True

       

       

return

False

class

Planner:

   

Planner: Generates task execution plan

   

   

def

create_plan

(

self

,

task

)

:

       

"""Create initial execution plan"""

prompt

=

f

"""
Task: {task}

Please formulate a detailed execution plan, including:

  1. The sequence of steps to be executed
  2. Specific operations for each step
  3. Dependencies between steps

Output format:
Step 1: [Operation description]
Step 2: [Operation description]
...
"""

plan_text

=

self

.

llm

.

generate

(

prompt

)

       

return

Plan.

parse

(

plan_text

)

   

   

def

replan

(

self

,

task

,

results

)

:

       

"""Replan based on execution results"""

       

Analyze the completed results

completed

=

[

r

for

r

in

results

if

r.

is_success

]

failed

=

[

r

for

r

in

results

if

not

r.

is_success

]

       

       

Generate the adjusted plan

prompt

=

f

"""
Original task: {task}
Completed steps: {completed}
Failed steps: {failed}

Please formulate the adjusted execution plan:
"""

plan_text

=

self

.

llm

.

generate

(

prompt

)

       

return

Plan.

parse

(

plan_text

)

class

Executor:

   

"""Executor: Executes specific plan steps"""

   

   

def

execute

(

self

,

step

)

:

       

"""Execute a single step"""

       

Select execution method based on step type

       

if

step.

type

==

"tool_call"

:

           

return

self

.

execute_tool_call

(

step

)

       

elif

step.

type

==

"code"

:

           

return

self

.

execute_code

(

step

)

       

elif

step.

type

==

"query"

:

           

return

self

.

execute_query

(

step

)

       

       

return

Result

(

success

=

False

,

error

=

"Unknown step type"

)

Note: The Plan-and-Execute mode is suitable for scenarios where the task structure is relatively stable and can be planned in advance. The ReAct mode may be more suitable for environments that require flexible adaptation.


Chapter Summary

This chapter introduces the core reasoning and planning capabilities of AI Agents.

The ReAct framework allows Agents to adjust strategies while executing through a loop of reasoning and action.

Chain-of-Thought (CoT) enhances the execution accuracy of complex tasks by demonstrating a step-by-step reasoning process.

Tree-of-Thought (ToT) extends Chain-of-Thought to support multi-path exploration and backtracking.

MCTS is a heuristic search algorithm suitable for complex decision-making and planning problems.

Reflexion endows Agents with self-reflection capabilities, enabling them to learn and improve from failures.

Task decomposition strategies are the foundation of planning capabilities, including recursive, parallel, and hierarchical decomposition.

Plan-and-Execute adopts a plan-then-execute mode, suitable for structurally stable tasks.

These technologies can be used individually or combined to build more powerful Agent systems.