Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
Add a new plan module in AgentScope to enable agents to create and execute plans formally (#722)
DavdGao458e8eedc94b
diff --git a/README.md b/README.mdindex f852b50a6..50d8f06b1 100644--- a/README.md+++ b/README.md@@ -98,9 +98,12 @@ Quick overview of important features in **AgentScope 1.0**:| evaluation | Provide distributed and parallel evaluation | [Evaluation](https://doc.agentscope.io/tutorial/task_eval.html) || formatter | Support multi-agent prompt formatting with tools API | [Prompt Formatter](https://doc.agentscope.io/tutorial/task_prompt.html) || | Support truncation-based formatter strategy | |+| plan | Support ReAct-based long-term planning | [Plan](https://doc.agentscope.io/tutorial/task_plan.html) |+| | Support manual plan specification | || ... | | |## 📢 News+- **[2025-09]** A new powerful 📋**Plan** module is online now! Check out the [tutorial](https://doc.agentscope.io/tutorial/task_plan.html) for more details.- **[2025-09]** **AgentScope Runtime** is open-sourced now! Enabling effective agent deployment with sandboxed tool execution for production-ready AI applications. Check out the [GitHub repo](https://github.com/agentscope-ai/agentscope-runtime).- **[2025-09]** **AgentScope Studio** is open-sourced now! Check out the [GitHub repo](https://github.com/agentscope-ai/agentscope-studio).- **[2025-08]** The new tutorial of v1 is online now! Check out the [tutorial](https://doc.agentscope.io) for more details.@@ -354,6 +357,7 @@ as_studio- Functional- [ReAct Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/react_agent)- [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/mcp)+ - [Plan](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/plan)- [Structured Output](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)- [Long-Term Memory](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory)- [Session with SQLite](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/session_with_sqlite)diff --git a/README_zh.md b/README_zh.mdindex 5ea5e1065..1586effc1 100644--- a/README_zh.md+++ b/README_zh.md@@ -99,9 +99,12 @@ AgentScope v1.0 新功能概览:| evaluation | 提供分布式和并行评估 | [Evaluation](https://doc.agentscope.io/zh_CN/tutorial/task_eval.html) || formatter | 支持多Agent提示格式化与工具API | [Prompt Formatter](https://doc.agentscope.io/zh_CN/tutorial/task_prompt.html) || | 支持基于截断的格式化策略 | |+| plan | 支持任务分解和计划制定 | [Plan](https://doc.agentscope.io/zh_CN/tutorial/task_plan.html) |+| | 支持开发者手动设定计划 | || ... | | |## 📢 新闻+- **[2025-09]** 一个全新功能强大的 📋**Plan** 模块已经上线 AgentScope!查看[文档](https://doc.agentscope.io/zh_CN/tutorial/task_plan.html)了解更多详情。- **[2025-09]** **AgentScope Runtime** 现已开源!支持沙盒化工具执行的高效智能体部署,助力打造生产级AI应用。查看 [GitHub 仓库](https://github.com/agentscope-ai/agentscope-runtime)。- **[2025-09]** **AgentScope Studio** 现已开源!查看 [GitHub 仓库](https://github.com/agentscope-ai/agentscope-studio)。- **[2025-08]** v1 版本 Tutorial 已上线!查看[tutorial](https://doc.agentscope.io/zh_CN/)了解更多详情。@@ -356,6 +359,7 @@ as_studio- 功能演示- [ReAct Agent](https://github.com/agentscope-ai/agentscope/tree/main/examples/react_agent)- [MCP](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/mcp)+ - [计划](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/plan)- [结构化输出](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/structured_output)- [长期记忆](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/long_term_memory)- [基于DB的会话管理](https://github.com/agentscope-ai/agentscope/tree/main/examples/functionality/session_with_sqlite)diff --git a/docs/tutorial/_static/images/plan.png b/docs/tutorial/_static/images/plan.pngnew file mode 100644index 000000000..482c8547cBinary files /dev/null and b/docs/tutorial/_static/images/plan.png differdiff --git a/docs/tutorial/en/index.rst b/docs/tutorial/en/index.rstindex 4d0669828..73b0fdf79 100644--- a/docs/tutorial/en/index.rst+++ b/docs/tutorial/en/index.rst@@ -42,6 +42,7 @@ Welcome to AgentScope's documentation!tutorial/task_long_term_memorytutorial/task_agenttutorial/task_pipeline+ tutorial/task_plantutorial/task_statetutorial/task_hooktutorial/task_mcpdiff --git a/docs/tutorial/en/src/quickstart_agent.py b/docs/tutorial/en/src/quickstart_agent.pyindex f2d6a1989..e58bf72e6 100644--- a/docs/tutorial/en/src/quickstart_agent.py+++ b/docs/tutorial/en/src/quickstart_agent.py@@ -89,6 +89,12 @@ from agentscope.tool import Toolkit, execute_python_code# * - ``max_iters``# -# - The maximum number of iterations for the agent to generate a response+# * - ``plan_notebook``+# - :ref:`plan`+# - The plan notebook to manage the plans+# * - ``print_hint_msg``+# -+# - Whether to print the hint message generated by the plan notebook at each step## Taking DashScope API as example, we create an agent object as follows:diff --git a/docs/tutorial/en/src/task_plan.py b/docs/tutorial/en/src/task_plan.pynew file mode 100644index 000000000..8c1abcc40--- /dev/null+++ b/docs/tutorial/en/src/task_plan.py@@ -0,0 +1,293 @@+# -*- coding: utf-8 -*-+"""+.. _plan:++Plan+=========================++The Plan Module enables agents to formally break down complex tasks into manageable sub-tasks and execute them systematically. Key features include:++- Support **manual plan specification**+- Comprehensive plan management capabilities:+ - **Creating, modifying, abandoning, and restoring** plans+ - **Switching** between multiple plans+ - **Gracefully handling interruptions** by temporarily suspending plans to address user queries or urgent tasks+- **Real-time visualization and monitoring** of plan execution++.. note:: The current plan module has the following limitations, and we are working on improving them:++ - The subtasks in a plan must be executed sequentially++Specifically, the plan module works by++- providing tool functions for plan management+- inserting hint messages to guide the ReAct agent to complete the plan++The following figure illustrates how the plan module works with the ReAct agent:++.. figure:: ../../_static/images/plan.png+ :width: 90%+ :alt: Plan module+ :class: bordered-image+ :align: center++ How the plan module works with the ReAct agent++"""+import asyncio+import os++from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.model import DashScopeChatModel+from agentscope.plan import PlanNotebook, Plan, SubTask++# %%+# PlanNotebook+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# The `PlanNotebook` class is the core of the plan module, responsible for providing+#+# - plan-related tool functions+# - hint messages to guide the agent to finish the plan+#+# The `PlanNotebook` class can be instantiated with the following parameters:+#+# .. list-table:: Parameters of the `PlanNotebook` constructor+# :header-rows: 1+#+# * - Name+# - Type+# - Description+# * - ``max_subtasks``+# - ``int | None``+# - The maximum number of subtasks allowed in a plan, infinite if None+# * - ``plan_to_hint``+# - ``Callable[[Plan | None], str | None] | None``+# - The function to generate hint message based on the current plan. If not provided, a default `DefaultPlanToHint` object will be used.+# * - ``storage``+# - ``PlanStorageBase | None``+# - The plan storage. If not provided, a default in-memory storage will be used.+#+# The ``plan_to_hint`` callable object is the most important part of the+# `PlanNotebook` class, also serves as the interface for prompt engineering.+# We have built a default `DefaultPlanToHint` class that can be used directly.+# Developers are encouraged to providing their own ``plan_to_hint`` function+# for better performance.+#+# The ``storage`` is to store historical plans, allowing agent to+# retrieve and restore historical plans. Developers are encouraged to+# implement their own plan storage by inheriting the ``PlanStorageBase`` class.+# If not provided, a default in-memory storage will be used.+#+# .. tip:: The ``PlanStorageBase`` class inherits from the ``StateModule``+# class, so that the plan storage will also be saved and loaded by the+# session management.+#+# The core attributes and methods of the `PlanNotebook` class are summarized+# as follows:+#+# .. list-table:: Core attributes and methods of the `PlanNotebook` class+# :header-rows: 1+#+# * - Type+# - Name+# - Description+# * - attribute+# - ``current_plan``+# - The current plan that the agent is executing+# * -+# - ``storage``+# - The storage for historical plans, used for retrieving and restoring historical plans+# * -+# - ``plan_to_hint``+# - A callable object that takes the current plan as input and generates a hint message to guide the agent to finish the plan+# * - method+# - ``list_tools``+# - List all the tool functions provided by the `PlanNotebook` class+# * -+# - ``get_current_hint``+# - Get the hint message for the current plan, which will call the ``plan_to_hint`` function+# * -+# - | ``create_plan``,+# | ``view_subtasks``,+# | ``revise_current_plan``,+# | ``update_subtask_state``,+# | ``finish_subtask``,+# | ``finish_plan``,+# | ``view_historical_plans``,+# | ``recover_historical_plan``+# - The tool functions that allows the agent to manage the plan and subtasks+# * -+# - ``register_plan_change_hook``+# - Register a hook function that will be called when the plan is changed, used to plan visualization and monitoring+# * -+# - ``remove_plan_change_hook``+# - Remove a registered plan change hook function+#+# The ``list_tools`` method is a quick way to obtain all tool functions, so that you can register them to the agent's toolkit.++plan_notebook = PlanNotebook()+++async def list_tools() -> None:+ """List the tool functions provided by PlanNotebook."""+ print("The tools provided by PlanNotebook:")+ for tool in await plan_notebook.list_tools():+ print(tool.__name__)+++asyncio.run(list_tools())+++# %%+# Working with ReActAgent+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# The `ReActAgent` in AgentScope has integrated the plan module by a ``plan_notebook`` parameter in its constructor.+# Once provided, the agent will+#+# - be equipped with the plan management tool functions, and+# - be inserted with the hint messages at the beginning of each reasoning step+#+# There are two ways to use the plan module with the `ReActAgent`:+#+# - Manual plan specification: Users can manually create a plan by calling the ``create_plan`` tool function, and initialize the `ReActAgent` with the plan notebook.+# - Agent-managed plan execution: The agent will create and manage the plan by itself, by calling the plan management tool functions.+#+# Manual Plan Specification+# ---------------------------------+# Manually creating a plan is straightforward by calling the ``create_plan`` tool function.+# The following is an example of manually creating a plan to conduct a comprehensive research on the LLM-empowered agent.+#+async def manual_plan_specification() -> None:+ """Manual plan specification example."""+ await plan_notebook.create_plan(+ name="Research on Agent",+ description="Conduct a comprehensive research on the LLM-empowered agent.",+ expected_outcome="A Markdown format report answer three questions: 1. What's agent? 2. What's the current state of the art of agent? 3. What's the future trend of agent?",+ subtasks=[+ SubTask(+ name="Search agent-related survey papers",+ description=(+ "Search for survey parers on multiple sources, including "+ "Google Scholar, arXiv, and Semantic Scholar. Must be "+ "published after 2021 and have more than 50 citations."+ ),+ expected_outcome="A paper list in Markdown format",+ ),+ SubTask(+ name="Read and summarize the papers",+ description=(+ "Read the papers found in the previous step, and "+ "summarize the key points, including the definition, "+ "taxonomy, challenges, and key directions."+ ),+ expected_outcome="A summary of the key points in Markdown format",+ ),+ SubTask(+ name="Research on recent advances of large company",+ description=(+ "Research on the recent advances of large companies, "+ "including Google, Microsoft, OpenAI, Anthropic, Alibaba "+ "and Meta. Find the official blogs or news articles."+ ),+ expected_outcome="A recent advances of large company ",+ ),+ SubTask(+ name="Write a report",+ description=(+ "Write a report based on the previous steps, and answer "+ "the three questions in the expected outcome."+ ),+ expected_outcome=(+ "A Markdown format report answer three questions: 1. "+ "What's agent? 2. What's the current state of the art of "+ "agent? 3. What's the future trend of agent?"+ ),+ ),+ ],+ )++ print("The current hint message:\n")+ msg = await plan_notebook.get_current_hint()+ print(f"{msg.name}: {msg.content}")+++asyncio.run(manual_plan_specification())++# %%+# After creating the plan, you can initialize the `ReActAgent` with the+# plan notebook as follows:++agent = ReActAgent(+ name="Friday",+ sys_prompt="You are a helpful assistant.",+ model=DashScopeChatModel(+ model_name="qwen-max",+ api_key=os.environ["DASHSCOPE_API_KEY"],+ ),+ formatter=DashScopeChatFormatter(),+ plan_notebook=plan_notebook,+)++# %%+# Agent-Managed Plan Execution+# ---------------------------------+# Agent can also create and manage the plan by itself, by calling the plan management tool functions.+# We just need to initialize the `ReActAgent` with the plan notebook as follows:+#++agent = ReActAgent(+ name="Friday",+ sys_prompt="You are a helpful assistant.",+ model=DashScopeChatModel(+ model_name="qwen-max",+ api_key=os.environ["DASHSCOPE_API_KEY"],+ ),+ formatter=DashScopeChatFormatter(),+ plan_notebook=PlanNotebook(),+)++# %%+# After that, we can build a loop to interact with the agent as follows.+# Once the task is complex, the agent will create a plan by itself and+# execute the plan step by step.+#+# .. code-block:: python+# :caption: Build conversation with the plan agent+#+# async def interact_with_agent() -> None:+# """Interact with the plan agent."""+# user = UserAgent(name="user")+#+# msg = None+# while True:+# msg = await user(msg)+# if msg.get_text_content() == "exit":+# break+# msg = await agent(msg)+#+# asyncio.run(interact_with_agent())+#+#+# Plan Visualization and Monitoring+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# AgentScope supports real-time visualization and monitoring of the plan+# execution by the plan change hook function.+#+# They will be triggered when the plan is changed by calling the tool+# functions. A template of the plan change hook function is as follows:+#+++def plan_change_hook_template(self: PlanNotebook, plan: Plan) -> None:+ """A template of the plan change hook function.++ Args:+ self (`PlanNotebook`):+ The PlanNotebook instance.+ plan (`Plan`):+ The current plan instance (after the change).+ """+ # Forward the plan to the frontend for visualization or other processingdiff --git a/docs/tutorial/zh_CN/index.rst b/docs/tutorial/zh_CN/index.rstindex 4d0669828..73b0fdf79 100644--- a/docs/tutorial/zh_CN/index.rst+++ b/docs/tutorial/zh_CN/index.rst@@ -42,6 +42,7 @@ Welcome to AgentScope's documentation!tutorial/task_long_term_memorytutorial/task_agenttutorial/task_pipeline+ tutorial/task_plantutorial/task_statetutorial/task_hooktutorial/task_mcpdiff --git a/docs/tutorial/zh_CN/src/quickstart_agent.py b/docs/tutorial/zh_CN/src/quickstart_agent.pyindex dba605b3f..db9b4f319 100644--- a/docs/tutorial/zh_CN/src/quickstart_agent.py+++ b/docs/tutorial/zh_CN/src/quickstart_agent.py@@ -88,6 +88,12 @@ from agentscope.tool import Toolkit, execute_python_code# * - ``max_iters``# -# - 智能体生成响应的最大迭代次数+# * - ``plan_notebook``+# - :ref:`plan`+# - 计划模块,允许智能体制定和管理计划与子任务+# * - ``print_hint_msg``+# -+# - 是否在终端打印 ``plan_notebook`` 生成的提示消息## 以 DashScope API 为例,我们创建一个智能体对象如下:diff --git a/docs/tutorial/zh_CN/src/task_plan.py b/docs/tutorial/zh_CN/src/task_plan.pynew file mode 100644index 000000000..58f56441a--- /dev/null+++ b/docs/tutorial/zh_CN/src/task_plan.py@@ -0,0 +1,273 @@+# -*- coding: utf-8 -*-+"""+.. _plan:++计划+=========================++AgentScope 中的计划(Plan)模块使智能体能够正式地将复杂任务分解为可管理的子任务并系统地执行它们。主要功能包括:++- 支持 **手动计划规范**+- 全面的计划管理功能:+ - **创建、修改、放弃和恢复** 计划+ - 在多个计划之间 **切换**+ - 通过临时暂停计划来处理用户查询或紧急任务,**优雅地处理中断**+- 计划执行的 **实时可视化和监控**++.. note:: 当前计划模块仅支持子任务按照顺序执行。+++具体来说,计划模块的工作原理是++- 提供计划管理的工具函数+- 插入提示消息来指导ReAct智能体完成计划++下图说明了计划模块如何与ReAct智能体协作:++.. figure:: ../../_static/images/plan.png+ :width: 90%+ :alt: 计划模块+ :class: bordered-image+ :align: center++ 计划模块如何与ReAct智能体协作++"""+import asyncio+import os++from agentscope.agent import ReActAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.model import DashScopeChatModel+from agentscope.plan import PlanNotebook, Plan, SubTask++# %%+# PlanNotebook+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+#+# ``PlanNotebook`` 类是计划模块的核心,负责提供+#+# - 管理计划,子任务的工具函数+# - 提供用于“引导智能体正确完成任务”的提示消息(Hint message)+#+# ``PlanNotebook`` 类使用以下参数实例化:+#+# .. list-table:: ``PlanNotebook`` 构造函数的参数+# :header-rows: 1+#+# * - 名称+# - 类型+# - 描述+# * - ``max_subtasks``+# - ``int | None``+# - 计划中允许的子任务最大数量,如果为 ``None`` 则无限制+# * - ``plan_to_hint``+# - ``Callable[[Plan | None], str | None] | None``+# - 基于当前计划的完成情况,生成对应提示消息的函数。如果未提供,将使用默认的 ``DefaultPlanToHint`` 对象。+# * - ``storage``+# - ``PlanStorageBase | None``+# - 计划的存储模块,用于恢复,保存历史计划。如果未提供,将使用默认的内存(In-memory)存储。+#+# ``plan_to_hint`` 参数是 ``PlanNotebook`` 类的核心参数,也是开发者进行提示工程的接口。+# 作为可调用对象,接受当前计划作为输入,并返回一个字符串类型的提示消息。+# AgentScope 构建了一个默认的 ``DefaultPlanToHint`` 类,可以直接使用,同时我们鼓励开发者提供自己的 ``plan_to_hint`` 函数以获得更好的性能。+#+# ``storage`` 用于存储历史计划,允许智能体检索和恢复历史计划。+# 我们同样鼓励开发者通过继承 ``PlanStorageBase`` 类来实现自己的计划存储。如果未提供,将使用默认的内存存储。+#+# .. tip:: ``PlanStorageBase`` 类继承自 ``StateModule`` 类,因此 storage也会通过会话管理进行保存和加载。+#+# ``PlanNotebook`` 类的核心属性和方法总结如下:+#+# .. list-table:: ``PlanNotebook`` 类的核心属性和方法+# :header-rows: 1+#+# * - 类型+# - 名称+# - 描述+# * - 属性+# - ``current_plan``+# - 智能体正在执行的当前计划+# * -+# - ``storage``+# - 历史计划的存储,用于检索和恢复历史计划+# * -+# - ``plan_to_hint``+# - 一个可调用对象,以当前计划为输入并生成提示消息来指导智能体完成计划+# * - 函数+# - ``list_tools``+# - 列出 ``PlanNotebook`` 类提供的所有工具函数+# * -+# - ``get_current_hint``+# - 获取当前计划的提示消息,将调用 ``plan_to_hint`` 函数+# * -+# - | ``create_plan``,+# | ``view_subtasks``,+# | ``revise_current_plan``,+# | ``update_subtask_state``,+# | ``finish_subtask``,+# | ``finish_plan``,+# | ``view_historical_plans``,+# | ``recover_historical_plan``+# - 允许智能体管理计划和子任务的工具函数+# * -+# - ``register_plan_change_hook``+# - 注册一个钩子函数,当计划发生变化时将被调用,用于计划可视化和监控+# * -+# - ``remove_plan_change_hook``+# - 移除已注册的钩子函数+#+# ``list_tools`` 方法是获取所有工具函数的快速方法,这样您就可以将它们注册到智能体的工具包中。++plan_notebook = PlanNotebook()+++async def list_tools() -> None:+ """列出PlanNotebook提供的工具函数。"""+ print("PlanNotebook提供的工具:")+ for tool in await plan_notebook.list_tools():+ print(tool.__name__)+++asyncio.run(list_tools())+++# %%+# 与ReActAgent协作+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# AgentScope中的 ``ReActAgent`` 已通过构造函数中的 ``plan_notebook`` 参数集成了计划模块。+# 一旦提供,智能体将+#+# - 配备计划管理工具函数,并且+# - 在每个推理步骤开始时插入提示消息+#+# 有两种方式在 ``ReActAgent`` 中使用计划模块:+#+# - 开发者指定计划:开发者可以通过调用 ``create_plan`` 工具函数手动创建计划,并使用该计划来初始化 ``ReActAgent`` 。+# - 智能体管理的计划执行:智能体将通过调用计划管理工具函数自己创建和管理计划。+#+# 手动计划规范+# ---------------------------------+# 通过调用 ``create_plan`` 工具函数手动创建计划非常简单。+# 以下是手动创建计划以对LLM赋能的智能体进行全面研究的示例。+#+async def manual_plan_specification() -> None:+ """手动计划规范示例。"""+ await plan_notebook.create_plan(+ name="智能体研究",+ description="对基于LLM的智能体进行全面研究",+ expected_outcome="一份Markdown格式的报告,回答三个问题:1. 什么是智能体?2. 智能体的当前技术水平是什么?3. 智能体的未来趋势是什么?",+ subtasks=[+ SubTask(+ name="搜索智能体相关调研论文",+ description=(+ "在多个来源搜索调研论文,包括"+ "Google Scholar、arXiv和Semantic Scholar。必须"+ "在2021年后发表且引用数超过50。"+ ),+ expected_outcome="Markdown格式的论文列表",+ ),+ SubTask(+ name="阅读和总结论文",+ description="阅读前一步找到的论文,并总结关键点,包括定义、分类、挑战和关键方向。",+ expected_outcome="Markdown格式的关键点总结",+ ),+ SubTask(+ name="研究大公司的最新进展",+ description=(+ "研究大公司的最新进展,包括但不限于Google、Microsoft、OpenAI、"+ "Anthropic、阿里巴巴和Meta。查找官方博客或新闻文章。"+ ),+ expected_outcome="大公司的最新进展",+ ),+ SubTask(+ name="撰写报告",+ description="基于前面的步骤撰写报告,并回答预期结果中的三个问题。",+ expected_outcome=(+ "一份Markdown格式的报告,回答三个问题:1. "+ "什么是智能体?2. 智能体的当前技术水平"+ "是什么?3. 智能体的未来趋势是什么?"+ ),+ ),+ ],+ )++ print("当前提示消息:\n")+ msg = await plan_notebook.get_current_hint()+ print(f"{msg.name}: {msg.content}")+++asyncio.run(manual_plan_specification())++# %%+# 创建计划后,可以按如下方式使用计划笔记本初始化 ``ReActAgent`` :++agent = ReActAgent(+ name="Friday",+ sys_prompt="你是一个有用的助手。",+ model=DashScopeChatModel(+ model_name="qwen-max",+ api_key=os.environ["DASHSCOPE_API_KEY"],+ ),+ formatter=DashScopeChatFormatter(),+ plan_notebook=plan_notebook,+)++# %%+# 智能体自主管理+# ---------------------------------+# 智能体也可以通过调用计划管理工具函数自己创建和管理计划。+# 我们只需要按如下方式使用计划笔记本初始化 ``ReActAgent`` :+#++agent = ReActAgent(+ name="Friday",+ sys_prompt="你是一个有用的助手。",+ model=DashScopeChatModel(+ model_name="qwen-max",+ api_key=os.environ["DASHSCOPE_API_KEY"],+ ),+ formatter=DashScopeChatFormatter(),+ plan_notebook=PlanNotebook(),+)+++# %%+# 之后,我们可以构建一个循环来与智能体交互,如下所示。+# 一旦用户的任务复杂比较复杂,智能体将自己创建计划并逐步执行计划。+#+# .. code-block:: python+# :caption: 与计划智能体建立对话+#+# async def interact_with_agent() -> None:+# """与计划智能体交互。"""+# user = UserAgent(name="user")+#+# msg = None+# while True:+# msg = await user(msg)+# if msg.get_text_content() == "exit":+# break+# msg = await agent(msg)+#+# asyncio.run(interact_with_agent())+#+# 可视化和监控+# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+# AgentScope 通过钩子函数支持计划执行的实时可视化和监控。+#+# 当前计划被工具函数改变时,钩子函数将被触发,开发者可以在这些钩子函数中将当前的计划转发到对应的前端进行可视化或其他处理。+# 计划变化钩子函数的模板如下:+#+++def plan_change_hook_template(self: PlanNotebook, plan: Plan) -> None:+ """计划变化钩子函数的模板。++ Args:+ self (`PlanNotebook`):+ PlanNotebook实例。+ plan (`Plan`):+ 当前计划实例(变化后)。+ """+ # 将计划转发到前端进行可视化或其他处理diff --git a/examples/functionality/plan/README.md b/examples/functionality/plan/README.mdnew file mode 100644index 000000000..d1d8a8b83--- /dev/null+++ b/examples/functionality/plan/README.md@@ -0,0 +1,30 @@+# Plan with ReAct Agent++This example demonstrates how to use the plan module in AgentScope to make an agent create and manage a plan formally.++Specifically, we provide two examples: manual specification plan and Agent-managed plan.++## Manual Specification Plan++In this example, we first manually specify a plan for the agent to follow, then we let the agent execute the plan step by step.++To execute this example, run:++```bash+python main_manual_plan.py+```++## Agent-managed Plan++In this example, we let the agent create and manage its own plan.+Specifically, we use a query "Review the recent changes in AgentScope GitHub repository over the past month."++To run the example, execute:++```bash+python main_agent_managed_plan.py+```++> Note: The example is built with DashScope chat model. If you want to change the model in this example, don't forget+> to change the **formatter** at the same time! The corresponding relationship between built-in models and formatters+> are list in [our tutorial](https://doc.agentscope.io/tutorial/task_prompt.html#id1)\ No newline at end of filediff --git a/examples/functionality/plan/main_agent_managed_plan.py b/examples/functionality/plan/main_agent_managed_plan.pynew file mode 100644index 000000000..1ef61a4c7--- /dev/null+++ b/examples/functionality/plan/main_agent_managed_plan.py@@ -0,0 +1,69 @@+# -*- coding: utf-8 -*-+"""The main entry point of the plan example."""+import asyncio+import os++from agentscope.agent import ReActAgent, UserAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.plan import PlanNotebook+from agentscope.tool import (+ Toolkit,+ execute_shell_command,+ execute_python_code,+ write_text_file,+ insert_text_file,+ view_text_file,+)+++async def main() -> None:+ """The main entry point for the plan example."""+ import agentscope++ agentscope.init(studio_url="http://localhost:3000")++ toolkit = Toolkit()+ toolkit.register_tool_function(execute_shell_command)+ toolkit.register_tool_function(execute_python_code)+ toolkit.register_tool_function(write_text_file)+ toolkit.register_tool_function(insert_text_file)+ toolkit.register_tool_function(view_text_file)++ agent = ReActAgent(+ name="Friday",+ sys_prompt="""You're a helpful assistant named Friday.++# Target+Your target is to finish the given task with careful planning.++# Note+- You can equip yourself with plan related tools to help you plan and execute the given task.+- The resouces from search engines are not always correct, you should collect information from multiple sources and give the final answer after careful consideration.+""", # noqa+ model=DashScopeChatModel(+ model_name="qwen3-max-preview",+ api_key=os.environ["DASHSCOPE_API_KEY"],+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ enable_meta_tool=True,+ plan_notebook=PlanNotebook(),+ )+ user = UserAgent(name="user")++ msg = Msg(+ "user",+ "Review the recent changes in AgentScope GitHub repository "+ "over the past month.",+ "user",+ )+ while True:+ msg = await agent(msg)+ msg = await user(msg)+ if msg.get_text_content() == "exit":+ break+++asyncio.run(main())diff --git a/examples/functionality/plan/main_manual_plan.py b/examples/functionality/plan/main_manual_plan.pynew file mode 100644index 000000000..fc79db6ff--- /dev/null+++ b/examples/functionality/plan/main_manual_plan.py@@ -0,0 +1,101 @@+# -*- coding: utf-8 -*-+"""Manual specification plan example."""+import asyncio+import os++from agentscope.agent import ReActAgent, UserAgent+from agentscope.formatter import DashScopeChatFormatter+from agentscope.message import Msg+from agentscope.model import DashScopeChatModel+from agentscope.plan import PlanNotebook, SubTask+from agentscope.tool import (+ Toolkit,+ execute_shell_command,+ execute_python_code,+ write_text_file,+ insert_text_file,+ view_text_file,+)++plan_notebook = PlanNotebook()+++async def main() -> None:+ """The main entry point for the manual plan example."""++ # Create the plan manually+ await plan_notebook.create_plan(+ name="Comprehensive Report on AgentScope",+ description="Study the code of AgentScope and write a comprehensive "+ "report about this framework.",+ expected_outcome="A markdown format report summarizing the features, "+ "architecture, advantages/disadvantages, and "+ "potential improvements of AgentScope.",+ subtasks=[+ SubTask(+ name="Clone the repository",+ description="Clone the AgentScope GitHub repository from "+ "agentscope-ai/agentscope, and ensure it's the "+ "latest version.",+ expected_outcome="A local copy of the AgentScope repository.",+ ),+ SubTask(+ name="View the documentation",+ description="View the documentation of AgentScope in the "+ "repository.",+ expected_outcome="A comprehensive understanding of the "+ "features and usage of AgentScope.",+ ),+ SubTask(+ name="Study the code",+ description="Study the code of AgentScope, focusing on the "+ "core modules and their interactions.",+ expected_outcome="A deep understanding of the architecture "+ "and implementation of AgentScope.",+ ),+ SubTask(+ name="Summarize the findings",+ description="Summarize the findings from the documentation "+ "and code study, and write a comprehensive report "+ "in markdown format.",+ expected_outcome="A markdown format report",+ ),+ ],+ )++ # Add basic tools+ toolkit = Toolkit()+ toolkit.register_tool_function(execute_shell_command)+ toolkit.register_tool_function(execute_python_code)+ toolkit.register_tool_function(write_text_file)+ toolkit.register_tool_function(insert_text_file)+ toolkit.register_tool_function(view_text_file)++ # Create the agent+ agent = ReActAgent(+ name="Friday",+ sys_prompt="You're a helpful assistant named Friday. Your target is "+ "to finish the given task with careful planning.",+ model=DashScopeChatModel(+ model_name="qwen3-max-preview",+ api_key=os.environ["DASHSCOPE_API_KEY"],+ ),+ formatter=DashScopeChatFormatter(),+ toolkit=toolkit,+ plan_notebook=plan_notebook,+ )+ user = UserAgent(name="user")++ msg = Msg(+ "user",+ "Now start to finish the task by the given plan",+ "user",+ )+ while True:+ msg = await agent(msg)+ msg = await user(msg)+ if msg.get_text_content() == "exit":+ break+++asyncio.run(main())diff --git a/examples/react_agent/main.py b/examples/react_agent/main.pyindex ea3506a1d..31cef52bd 100644--- a/examples/react_agent/main.py+++ b/examples/react_agent/main.py@@ -17,6 +17,9 @@ from agentscope.tool import (async def main() -> None:"""The main entry point for the ReAct agent example."""+ import agentscope++ agentscope.init(tracing_url="")toolkit = Toolkit()toolkit.register_tool_function(execute_shell_command)toolkit.register_tool_function(execute_python_code)diff --git a/src/agentscope/agent/_react_agent.py b/src/agentscope/agent/_react_agent.pyindex fd1dacef4..581e6425d 100644--- a/src/agentscope/agent/_react_agent.py+++ b/src/agentscope/agent/_react_agent.py@@ -13,6 +13,7 @@ from ..formatter import FormatterBasefrom ..memory import MemoryBase, LongTermMemoryBase, InMemoryMemoryfrom ..message import Msg, ToolUseBlock, ToolResultBlock, TextBlockfrom ..model import ChatModelBase+from ..plan import PlanNotebookfrom ..tool import Toolkit, ToolResponsefrom ..tracing import trace_reply@@ -81,6 +82,8 @@ class ReActAgent(ReActAgentBase):enable_meta_tool: bool = False,parallel_tool_calls: bool = False,max_iters: int = 10,+ plan_notebook: PlanNotebook | None = None,+ print_hint_msg: bool = False,) -> None:"""Initialize the ReAct agent@@ -123,6 +126,9 @@ class ReActAgent(ReActAgentBase):them in parallel.max_iters (`int`, defaults to `10`):The maximum number of iterations of the reasoning-acting loops.+ print_hint_msg (`bool`, defaults to `False`):+ Whether to print the reasoning hint messages before each+ reasoning step."""super().__init__()@@ -170,7 +176,7 @@ class ReActAgent(ReActAgentBase):long_term_memory.retrieve_from_memory,)# Add a meta tool function to allow agent-controlled tool management- if enable_meta_tool:+ if enable_meta_tool or plan_notebook:self.toolkit.register_tool_function(self.toolkit.reset_equipped_tools,)@@ -178,6 +184,27 @@ class ReActAgent(ReActAgentBase):self.parallel_tool_calls = parallel_tool_callsself.max_iters = max_iters+ self.plan_notebook = None+ if plan_notebook:+ self.plan_notebook = plan_notebook+ self.toolkit.create_tool_group(+ "plan_related",+ description=self.plan_notebook.description,+ )+ for tool in asyncio.run(plan_notebook.list_tools()):+ self.toolkit.register_tool_function(+ tool,+ group_name="plan_related",+ )++ self.print_hint_msg = print_hint_msg++ # The hint messages that will be attached to the prompt to guide the+ # agent's behavior before each reasoning step, and cleared after+ # each reasoning step, meaning the hint messages is one-time use only.+ # We use an InMemoryMemory instance to store the hint messages+ self._reasoning_hint_msgs = InMemoryMemory()+# Variables to record the intermediate state# If required structured output model is provided@@ -291,12 +318,24 @@ class ReActAgent(ReActAgentBase):self,) -> Msg:"""Perform the reasoning process."""+ if self.plan_notebook:+ # Insert the reasoning hint from the plan notebook+ hint_msg = await self.plan_notebook.get_current_hint()+ if self.print_hint_msg and hint_msg:+ await self.print(hint_msg)+ await self._reasoning_hint_msgs.add(hint_msg)++ # Convert Msg objects into the required format of the model APIprompt = await self.formatter.format(msgs=[Msg("system", self.sys_prompt, "system"),*await self.memory.get_memory(),+ # The hint messages to guide the agent's behavior, maybe empty+ *await self._reasoning_hint_msgs.get_memory(),],)+ # Clear the hint messages after use+ await self._reasoning_hint_msgs.clear()res = await self.model(prompt,diff --git a/src/agentscope/mcp/_stateful_client_base.py b/src/agentscope/mcp/_stateful_client_base.pyindex 8d94bc5d2..88ca44034 100644--- a/src/agentscope/mcp/_stateful_client_base.py+++ b/src/agentscope/mcp/_stateful_client_base.py@@ -79,10 +79,10 @@ class StatefulClientBase(MCPClientBase, ABC):)try:- if self.stack:- await self.stack.aclose()-+ await self.stack.aclose()logger.info("MCP client closed.")+ except Exception as e:+ logger.warning("Error during MCP client cleanup: %s", e)finally:self.stack = Noneself.session = Nonediff --git a/src/agentscope/plan/__init__.py b/src/agentscope/plan/__init__.pynew file mode 100644index 000000000..9da080915--- /dev/null+++ b/src/agentscope/plan/__init__.py@@ -0,0 +1,21 @@+# -*- coding: utf-8 -*-+"""The plan module in AgentScope."""+from ._plan_model import (+ SubTask,+ Plan,+)+from ._plan_notebook import (+ DefaultPlanToHint,+ PlanNotebook,+)+from ._storage_base import PlanStorageBase+from ._in_memory_storage import InMemoryPlanStorage++__all__ = [+ "SubTask",+ "Plan",+ "DefaultPlanToHint",+ "PlanNotebook",+ "PlanStorageBase",+ "InMemoryPlanStorage",+]diff --git a/src/agentscope/plan/_in_memory_storage.py b/src/agentscope/plan/_in_memory_storage.pynew file mode 100644index 000000000..627c91f3c--- /dev/null+++ b/src/agentscope/plan/_in_memory_storage.py@@ -0,0 +1,61 @@+# -*- coding: utf-8 -*-+"""The in-memory plan storage class."""+from collections import OrderedDict++from ._plan_model import Plan+from ._storage_base import PlanStorageBase+++class InMemoryPlanStorage(PlanStorageBase):+ """In-memory plan storage."""++ def __init__(self) -> None:+ """Initialize the in-memory plan storage."""+ super().__init__()+ self.plans = OrderedDict()++ async def add_plan(self, plan: Plan, override: bool = True) -> None:+ """Add a plan to the storage.++ Args:+ plan (`Plan`):+ The plan to be added.+ override (`bool`, defaults to `True`):+ Whether to override the existing plan with the same ID.+ """+ if plan.id in self.plans and not override:+ raise ValueError(+ f"Plan with id {plan.id} already exists.",+ )+ self.plans[plan.id] = plan++ async def delete_plan(self, plan_id: str) -> None:+ """Delete a plan from the storage.++ Args:+ plan_id (`str`):+ The ID of the plan to be deleted.+ """+ self.plans.pop(plan_id, None)++ async def get_plans(self) -> list[Plan]:+ """Get all plans from the storage.++ Returns:+ `list[Plan]`:+ A list of all plans in the storage.+ """+ return list(self.plans.values())++ async def get_plan(self, plan_id: str) -> Plan | None:+ """Get a plan by its ID.++ Args:+ plan_id (`str`):+ The ID of the plan to be retrieved.++ Returns:+ `Plan | None`:+ The plan with the specified ID, or None if not found.+ """+ return self.plans.get(plan_id, None)diff --git a/src/agentscope/plan/_plan_model.py b/src/agentscope/plan/_plan_model.pynew file mode 100644index 000000000..8240bce18--- /dev/null+++ b/src/agentscope/plan/_plan_model.py@@ -0,0 +1,186 @@+# -*- coding: utf-8 -*-+"""The models used in the plan module."""+from typing import Literal++import shortuuid+from pydantic import BaseModel, Field++from .._utils._common import _get_timestamp+++class SubTask(BaseModel):+ """The subtask model used in the plan module."""++ name: str = Field(+ description=(+ "The subtask name, should be concise, descriptive and not"+ "exceed 10 words."+ ),+ )+ description: str = Field(+ description=(+ "The subtask description, including the constraints, target and "+ "outcome to be achieved. The description should be clear, "+ "specific and concise, and all the constraints, target and "+ "outcome should be specific and measurable."+ ),+ )+ expected_outcome: str = Field(+ description=(+ "The expected outcome of the subtask, which should be specific, "+ "concrete and measurable."+ ),+ )+ outcome: str | None = Field(+ description="The actual outcome of the subtask.",+ exclude=True,+ default=None,+ )+ state: Literal["todo", "in_progress", "done", "abandoned"] = Field(+ description="The state of the subtask.",+ default="todo",+ exclude=True,+ )+ created_at: str = Field(+ description="The time the subtask was created.",+ default_factory=_get_timestamp,+ )+ # Result related fields+ finished_at: str | None = Field(+ description="The time the subtask was finished.",+ default=None,+ exclude=True,+ )++ def finish(self, outcome: str) -> None:+ """Finish the subtask with the actual outcome."""+ self.state = "done"+ self.outcome = outcome+ self.finished_at = _get_timestamp()++ def to_oneline_markdown(self) -> str:+ """Convert the subtask to MarkDown format."""+ status_map = {+ "todo": "- []",+ "in_progress": "- [][WIP]",+ "done": "- [x]",+ "abandoned": "- [][Abandoned]",+ }+ return f"{status_map[self.state]} {self.name}"++ def to_markdown(self, detailed: bool = False) -> str:+ """Convert the subtask to MarkDown format.++ Args:+ detailed (`bool`, defaults to `False`):+ Whether to include detailed information about the subtask.+ """+ status_map = {+ "todo": "- [ ] ",+ "in_progress": "- [ ] [WIP]",+ "done": "- [x] ",+ "abandoned": "- [ ] [Abandoned]",+ }++ if detailed:+ markdown_strs = [+ f"{status_map[self.state]}{self.name}",+ f"\t- Created At: {self.created_at}",+ f"\t- Description: {self.description}",+ f"\t- Expected Outcome: {self.expected_outcome}",+ f"\t- State: {self.state}",+ ]++ if self.state == "done":+ markdown_strs.extend(+ [+ f"\t- Finished At: {self.finished_at}",+ f"\t- Actual Outcome: {self.outcome}",+ ],+ )++ return "\n".join(markdown_strs)++ return f"{status_map[self.state]}{self.name}"+++class Plan(BaseModel):+ """The plan model used in the plan module, contains a list of subtasks."""++ id: str = Field(exclude=True, default_factory=shortuuid.uuid)+ name: str = Field(+ description=(+ "The plan name, should be concise, descriptive and not exceed 10 "+ "words."+ ),+ )+ description: str = Field(+ description=(+ "The plan description, including the constraints, target and "+ "outcome to be achieved. The description should be clear, "+ "specific and concise, and all the constraints, target and "+ "outcome should be specific and measurable."+ ),+ )+ expected_outcome: str = Field(+ description=(+ "The expected outcome of the plan, which should be specific, "+ "concrete and measurable."+ ),+ )+ subtasks: list[SubTask] = Field(+ description=("A list of subtasks that make up the plan."),+ )+ created_at: str = Field(+ description="The time the plan was created.",+ default_factory=_get_timestamp,+ exclude=True,+ )+ state: Literal["todo", "in_progress", "done", "abandoned"] = Field(+ description="The state of the plan.",+ default="todo",+ exclude=True,+ )+ finished_at: str | None = Field(+ description="The time the plan was finished.",+ default=None,+ exclude=True,+ )+ outcome: str | None = Field(+ description="The actual outcome of the plan.",+ default=None,+ exclude=True,+ )++ def finish(+ self,+ state: Literal["done", "abandoned"],+ outcome: str,+ ) -> None:+ """Finish the plan."""+ self.state = state+ self.outcome = outcome+ self.finished_at = _get_timestamp()++ def to_markdown(self, detailed: bool = False) -> str:+ """Convert the plan to MarkDown format."""+ subtasks_markdown = "\n".join(+ [+ subtask.to_markdown(+ detailed=detailed,+ )+ for subtask in self.subtasks+ ],+ )++ return "\n".join(+ [+ f"# {self.name}",+ f"**Description**: {self.description}",+ f"**Expected Outcome**: {self.expected_outcome}",+ f"**State**: {self.state}",+ f"**Created At**: {self.created_at}",+ "## Subtasks",+ subtasks_markdown,+ ],+ )diff --git a/src/agentscope/plan/_plan_notebook.py b/src/agentscope/plan/_plan_notebook.pynew file mode 100644index 000000000..9830bc842--- /dev/null+++ b/src/agentscope/plan/_plan_notebook.py@@ -0,0 +1,829 @@+# -*- coding: utf-8 -*-+"""The plan notebook class, used to manage the plan, providing hints and+tool functions to the agent."""+from collections import OrderedDict+from typing import Callable, Literal, Coroutine, Any++from ._in_memory_storage import InMemoryPlanStorage+from ._plan_model import SubTask, Plan+from ._storage_base import PlanStorageBase+from .._utils._common import _execute_async_or_sync_func+from ..message import TextBlock, Msg+from ..module import StateModule+from ..tool import ToolResponse+++class DefaultPlanToHint:+ """The default function to generate the hint message based on the current+ plan to guide the agent on next steps."""++ hint_prefix: str = "<system-hint>"+ hint_suffix: str = "</system-hint>"++ no_plan: str = (+ "If the user's query is complex (e.g. programming a website, game or "+ "app), or requires a long chain of steps to complete (e.g. conduct "+ "research on a certain topic from different sources), you NEED to "+ "create a plan first by calling 'create_plan'. Otherwise, you can "+ "directly execute the user's query without planning."+ )++ at_the_beginning: str = (+ "The current plan:\n"+ "```\n"+ "{plan}\n"+ "```\n"+ "Your options include:\n"+ "- Mark the first subtask as 'in_progress' by calling "+ "'update_subtask_state' with subtask_idx=0 and state='in_progress', "+ "and start executing it.\n"+ "- If the first subtask is not executable, analyze why and what you "+ "can do to advance the plan, e.g. ask user for more information, "+ "revise the plan by calling 'revise_current_plan'.\n"+ "- If the user asks you to do something unrelated to the plan, "+ "prioritize the completion of user's query first, and then return "+ "to the plan afterward.\n"+ "- If the user no longer wants to perform the current plan, confirm "+ "with the user and call the 'finish_plan' function.\n"+ )++ when_a_subtask_in_progress: str = (+ "The current plan:\n"+ "```\n"+ "{plan}\n"+ "```\n"+ "Now the subtask at index {subtask_idx}, named '{subtask_name}', is "+ "'in_progress'. Its details are as follows:\n"+ "```\n"+ "{subtask}\n"+ "```\n"+ "Your options include:\n"+ "- Go on execute the subtask and get the outcome.\n"+ "- Call 'finish_subtask' with the specific outcome if the subtask is "+ "finished.\n"+ "- Ask the user for more information if you need.\n"+ "- Revise the plan by calling 'revise_current_plan' if necessary.\n"+ "- If the user asks you to do something unrelated to the plan, "+ "prioritize the completion of user's query first, and then return to "+ "the plan afterward."+ )++ when_no_subtask_in_progress: str = (+ "The current plan:\n"+ "```\n"+ "{plan}\n"+ "```\n"+ "The first {index} subtasks are done, and there is no subtask "+ "'in_progress'. Now Your options include:\n"+ "- Mark the next subtask as 'in_progress' by calling "+ "'update_subtask_state', and start executing it.\n"+ "- Ask the user for more information if you need.\n"+ "- Revise the plan by calling 'revise_current_plan' if necessary.\n"+ "- If the user asks you to do something unrelated to the plan, "+ "prioritize the completion of user's query first, and then return to "+ "the plan afterward."+ )++ at_the_end: str = (+ "The current plan:\n"+ "```\n"+ "{plan}\n"+ "```\n"+ "All the subtasks are done. Now your options are:\n"+ "- Finish the plan by calling 'finish_plan' with the specific "+ "outcome, and summarize the whole process and outcome to the user.\n"+ "- Revise the plan by calling 'revise_current_plan' if necessary.\n"+ "- If the user asks you to do something unrelated to the plan, "+ "prioritize the completion of user's query first, and then return to "+ "the plan afterward."+ )++ def __call__(self, plan: Plan | None) -> str | None:+ """Generate the hint message based on the input plan to guide the+ agent on next steps.++ Args:+ plan (`Plan | None`):+ The current plan, used to generate the hint message.++ Returns:+ `str | None`:+ The generated hint message, or None if the plan is None or+ there is no relevant hint.+ """+ if plan is None:+ hint = self.no_plan++ else:+ # Count the number of subtasks in each state+ n_todo, n_in_progress, n_done, n_abandoned = 0, 0, 0, 0+ in_progress_subtask_idx = None+ for idx, subtask in enumerate(plan.subtasks):+ if subtask.state == "todo":+ n_todo += 1++ elif subtask.state == "in_progress":+ n_in_progress += 1+ in_progress_subtask_idx = idx++ elif subtask.state == "done":+ n_done += 1++ elif subtask.state == "abandoned":+ n_abandoned += 1++ hint = None+ if n_in_progress == 0 and n_done == 0:+ # All subtasks are todo+ hint = self.at_the_beginning.format(+ plan=plan.to_markdown(),+ )++ elif n_in_progress > 0 and in_progress_subtask_idx is not None:+ # One subtask is in_progress+ hint = self.when_a_subtask_in_progress.format(+ plan=plan.to_markdown(),+ subtask_idx=in_progress_subtask_idx,+ subtask_name=plan.subtasks[in_progress_subtask_idx].name,+ subtask=plan.subtasks[in_progress_subtask_idx].to_markdown(+ detailed=True,+ ),+ )++ elif n_in_progress == 0 and n_done > 0:+ # No subtask is in_progress, and some subtasks are done+ hint = self.when_no_subtask_in_progress.format(+ plan=plan.to_markdown(),+ index=n_done,+ )++ elif n_done + n_abandoned == len(plan.subtasks):+ # All subtasks are done or abandoned+ hint = self.at_the_end.format(+ plan=plan.to_markdown(),+ )++ if hint:+ return f"{self.hint_prefix}{hint}{self.hint_suffix}"++ return hint+++class PlanNotebook(StateModule):+ """The plan notebook to manage the plan, providing hints and plan related+ tool functions to the agent."""++ _plan_change_hooks: dict[str, Callable[["PlanNotebook", Plan], None]]+ """The hooks that will be triggered when the plan is changed. For example,+ used to display the plan on the frontend."""++ description: str = (+ "The plan-related tools. Activate this tool when you need to execute "+ "complex task, e.g. building a website or a game. Once activated, "+ "you'll enter the plan mode, where you will be guided to complete "+ "the given query by creating and following a plan, and hint message "+ "wrapped by <system-hint></system-hint> will guide you to complete "+ "the task. If you think the user no longer wants to perform the "+ "current task, you need to confirm with the user and call the "+ "'finish_plan' function."+ )++ def __init__(+ self,+ max_subtasks: int | None = None,+ plan_to_hint: Callable[[Plan | None], str | None] | None = None,+ storage: PlanStorageBase | None = None,+ ) -> None:+ """Initialize the plan notebook.++ Args:+ max_subtasks (`int | None`, optional):+ The maximum number of subtasks in a plan.+ plan_to_hint (`Callable[[Plan | None], str | None] | None`, \+ optional):+ The function to generate the hint message based on the+ current plan. If not provided, a default `DefaultPlanToHint`+ object will be used.+ storage (`PlanStorageBase | None`, optional):+ The plan storage. If not provided, an in-memory storage will+ be used.+ """+ super().__init__()++ self.max_tasks = max_subtasks+ self.plan_to_hint = plan_to_hint or DefaultPlanToHint()+ self.storage = storage or InMemoryPlanStorage()++ self.current_plan: Plan | None = None++ self._plan_change_hooks = OrderedDict()++ # Register the current_plan state for state management+ self.register_state(+ "current_plan",+ custom_to_json=lambda _: _.model_dump_json() if _ else None,+ custom_from_json=lambda _: Plan.model_validate(_) if _ else None,+ )++ async def create_plan(+ self,+ name: str,+ description: str,+ expected_outcome: str,+ subtasks: list[SubTask],+ ) -> ToolResponse:+ """Create a plan by given name and sub-tasks.++ Args:+ name (`str`):+ The plan name, should be concise, descriptive and not exceed+ 10 words.+ description (`str`):+ The plan description, including the constraints, target and+ outcome to be achieved. The description should be clear,+ specific and concise, and all the constraints, target and+ outcome should be specific and measurable.+ expected_outcome (`str`):+ The expected outcome of the plan, which should be specific,+ concrete and measurable.+ subtasks (`list[SubTask]`):+ A list of sequential sub-tasks that make up the plan.++ Returns:+ `ToolResponse`:+ The response of the tool call.+ """+ plan = Plan(+ name=name,+ description=description,+ expected_outcome=expected_outcome,+ subtasks=subtasks,+ )++ if self.current_plan is None:+ res = ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Plan '{name}' created successfully.",+ ),+ ],+ )++ else:+ res = ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=(+ "The current plan named "+ f"'{self.current_plan.name}' is replaced by the "+ f"newly created plan named '{name}'."+ ),+ ),+ ],+ )++ self.current_plan = plan+ await self._trigger_plan_change_hooks()+ return res++ def _validate_current_plan(self) -> None:+ """Validate the current plan."""+ if self.current_plan is None:+ raise ValueError(+ "The current plan is None, you need to create a plan by "+ "calling create_plan() first.",+ )++ async def revise_current_plan(+ self,+ subtask_idx: int,+ action: Literal["add", "revise", "delete"],+ subtask: SubTask | None = None,+ ) -> ToolResponse:+ """Revise the current plan by adding, revising or deleting a sub-task.++ Args:+ subtask_idx (`int`):+ The index of the sub-task to be revised, starting from 0.+ action (`Literal["add", "revise", "delete"]`):+ The action to be performed on the sub-task. If "add", the+ sub-task will be inserted before the given index. If "revise",+ the sub-task at the given index will be revised. If "delete",+ the sub-task at the given index will be deleted.+ subtask (`SubTask | None`, optional):+ The sub-task to be added or revised. Required if action is+ "add" or "revise".++ Raises:+ `ValueError`:+ If the current plan is `None`, `ValueError` will be raised.++ Returns:+ `ToolResponse`:+ The response of the tool call.+ """+ if action not in ["add", "revise", "delete"]:+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Invalid action '{action}'. Must be one of "+ "'add', 'revise', 'delete'.",+ ),+ ],+ )++ if action in ["add", "revise"] and subtask is None:+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"The subtask must be provided when action is "+ f"'{action}', but got None.",+ ),+ ],+ )++ self._validate_current_plan()++ # validate subtask_idx+ if subtask_idx >= len(self.current_plan.subtasks):+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Invalid subtask_idx '{subtask_idx}'. Must "+ f"be between 0 and "+ f"{len(self.current_plan.subtasks) - 1}.",+ ),+ ],+ )++ if action == "delete":+ subtask = self.current_plan.subtasks.pop(subtask_idx)+ await self._trigger_plan_change_hooks()+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Subtask (named '{subtask.name}') at index "+ f"{subtask_idx} is deleted successfully.",+ ),+ ],+ )++ if action == "add" and subtask:+ self.current_plan.subtasks.insert(subtask_idx, subtask)+ await self._trigger_plan_change_hooks()+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"New subtask is added successfully at index "+ f"{subtask_idx}.",+ ),+ ],+ )++ self.current_plan.subtasks[subtask_idx] = subtask+ await self._trigger_plan_change_hooks()+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Subtask at index {subtask_idx} is revised "+ f"successfully.",+ ),+ ],+ )++ async def update_subtask_state(+ self,+ subtask_idx: int,+ state: Literal["todo", "in_progress", "deprecated"],+ ) -> ToolResponse:+ """Update the state of a subtask by given index and state. Note if you+ want to mark a subtask as done, you SHOULD call `finish_subtask`+ instead with the specific outcome.++ Args:+ subtask_idx (`int`):+ The index of the subtask to be updated, starting from 0.+ state (`Literal["todo", "in_progress", "abandoned"]`):+ The new state of the subtask. If you want to mark a subtask+ as done, you SHOULD call `finish_subtask` instead with the+ specific outcome.+ """+ self._validate_current_plan()++ if not 0 <= subtask_idx < len(self.current_plan.subtasks):+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Invalid subtask_idx '{subtask_idx}'. Must "+ f"be between 0 and "+ f"{len(self.current_plan.subtasks) - 1}.",+ ),+ ],+ )++ if state not in ["todo", "in_progress", "abandoned"]:+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Invalid state '{state}'. Must be one of "+ "'todo', 'in_progress', 'abandoned'.",+ ),+ ],+ )++ # Only one subtask can be in_progress at a time+ if state == "in_progress":+ # Check only one subtask is in_progress+ for idx, subtask in enumerate(self.current_plan.subtasks):+ # Check all previous subtasks are done or deprecated+ if idx < subtask_idx and subtask.state not in [+ "done",+ "deprecated",+ ]:+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=(+ f"Subtask (at index {idx}) named "+ f"'{subtask.name}' is not done yet. You "+ "should finish the previous subtasks "+ "first."+ ),+ ),+ ],+ )++ # Check no other subtask is in_progress+ if subtask.state == "in_progress":+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=(+ f"Subtask (at index {idx}) named "+ f"'{subtask.name}' is already "+ "'in_progress'. You should finish it "+ "first before starting another subtask."+ ),+ ),+ ],+ )++ self.current_plan.subtasks[subtask_idx].state = state+ await self._trigger_plan_change_hooks()+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Subtask at index {subtask_idx}, named "+ f"'{self.current_plan.subtasks[subtask_idx].name}' "+ f"is marked as '{state}' successfully.",+ ),+ ],+ )++ async def finish_subtask(+ self,+ subtask_idx: int,+ subtask_outcome: str,+ ) -> ToolResponse:+ """Label the subtask as done by given index and outcome.++ Args:+ subtask_idx (`int`):+ The index of the sub-task to be marked as done, starting+ from 0.+ subtask_outcome (`str`):+ The specific outcome of the sub-task, should exactly match the+ expected outcome in the sub-task description. SHOULDN't be+ what you did or general description, e.g. "I have searched+ xxx", "I have written the code for xxx", etc. It SHOULD be+ the specific data, information, or path to the file, e.g.+ "There are 5 articles about xxx, they are\n- xxx\n- xxx\n..."+ """+ self._validate_current_plan()++ if not 0 <= subtask_idx < len(self.current_plan.subtasks):+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Invalid subtask_idx '{subtask_idx}'. Must "+ f"be between 0 and "+ f"{len(self.current_plan.subtasks) - 1}.",+ ),+ ],+ )++ for idx, subtask in enumerate(+ self.current_plan.subtasks[0:subtask_idx],+ ):+ if subtask.state not in ["done", "deprecated"]:+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=(+ "Cannot finish subtask at index "+ f"{subtask_idx} because the previous "+ f"subtask (at index {idx}) named "+ f"'{subtask.name}' is not done yet. You "+ "should finish the previous subtasks first."+ ),+ ),+ ],+ )++ # Label the subtask as done+ self.current_plan.subtasks[subtask_idx].finish(subtask_outcome)+ # Auto activate the next subtask if exists+ if subtask_idx + 1 < len(self.current_plan.subtasks):+ self.current_plan.subtasks[subtask_idx + 1].state = "in_progress"+ next_subtask = self.current_plan.subtasks[subtask_idx + 1]+ await self._trigger_plan_change_hooks()+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=(+ f"Subtask (at index {subtask_idx}) named "+ f"'{self.current_plan.subtasks[subtask_idx].name}'"+ " is marked as done successfully. The next "+ f"subtask named '{next_subtask.name}' is "+ f"activated."+ ),+ ),+ ],+ )++ await self._trigger_plan_change_hooks()+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=(+ f"Subtask (at index {subtask_idx}) named "+ f"'{self.current_plan.subtasks[subtask_idx].name}'"+ " is marked as done successfully. "+ ),+ ),+ ],+ )++ async def view_subtasks(self, subtask_idx: list[int]) -> ToolResponse:+ """View the details of the sub-tasks by given indexes.++ Args:+ subtask_idx (`list[int]`):+ The indexes of the sub-tasks to be viewed, starting from 0.+ """+ self._validate_current_plan()++ gathered_strs = []+ invalid_subtask_idx = []+ for idx in subtask_idx:+ if not 0 <= idx < len(self.current_plan.subtasks):+ invalid_subtask_idx.append(idx)+ continue++ subtask_markdown = self.current_plan.subtasks[idx].to_markdown(+ detailed=True,+ )+ gathered_strs.append(+ f"Subtask at index {idx}:\n"+ "```\n"+ f"{subtask_markdown}\n"+ "```\n",+ )++ if invalid_subtask_idx:+ gathered_strs.append(+ f"Invalid subtask_idx '{invalid_subtask_idx}'. Must be "+ f"between 0 and {len(self.current_plan.subtasks) - 1}.",+ )++ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text="\n".join(gathered_strs),+ ),+ ],+ )++ async def finish_plan(+ self,+ state: Literal["done", "abandoned"],+ outcome: str,+ ) -> ToolResponse:+ """Finish the current plan by given outcome, or abandon it with the+ given reason if the user no longer wants to perform it. Note that you+ SHOULD confirm with the user before abandoning the plan.++ Args:+ state (`Literal["done", "abandoned"]`):+ The state to finish the plan. If "done", the plan will be+ marked as done with the given outcome. If "abandoned", the+ plan will be abandoned with the given reason.+ outcome (`str`):+ The specific outcome of the plan if state is "done", or the+ reason for abandoning the plan if state is "abandoned".+ """+ if self.current_plan is None:+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text="There is no plan to finish.",+ ),+ ],+ )++ self.current_plan.finish(state, outcome)++ # Store the finished plan into history+ await self.storage.add_plan(self.current_plan)++ self.current_plan = None+ await self._trigger_plan_change_hooks()+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"The current plan is finished successfully as "+ f"'{state}'.",+ ),+ ],+ )++ async def view_historical_plans(self) -> ToolResponse:+ """View the historical plans."""+ historical_plans = await self.storage.get_plans()++ plans_str = [+ f"""Plan named '{_.name}':+- ID: {_.id}+- Created at: {_.created_at}+- Description: {_.description}+- State: {_.state}+"""+ for _ in historical_plans+ ]++ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text="\n".join(plans_str),+ ),+ ],+ )++ async def recover_historical_plan(self, plan_id: str) -> ToolResponse:+ """Recover a historical plan by given plan ID, the plan ID can be+ obtained by calling `view_historical_plans`. Note the recover+ operation will override the current plan if exists.++ Args:+ plan_id (`str`):+ The ID of the historical plan to be recovered.+ """+ historical_plan = await self.storage.get_plan(plan_id)+ if historical_plan is None:+ return ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=f"Cannot find the plan with ID '{plan_id}'.",+ ),+ ],+ )++ # Store the current plan into history if exists+ if self.current_plan:+ if self.current_plan.state != "done":+ self.current_plan.finish(+ "abandoned",+ f"The plan execution is interrupted by a new plan "+ f"with ID '{historical_plan.id}'.",+ )+ await self.storage.add_plan(self.current_plan)+ res = ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=(+ "The current plan named "+ f"'{self.current_plan.name}' is replaced by the "+ f"historical plan named '{historical_plan.name}' "+ f"with ID '{historical_plan.id}'."+ ),+ ),+ ],+ )+ else:+ res = ToolResponse(+ content=[+ TextBlock(+ type="text",+ text=(+ f"Historical plan named '{historical_plan.name}' "+ f"with ID '{historical_plan.id}' is recovered "+ "successfully."+ ),+ ),+ ],+ )+ self.current_plan = historical_plan+ return res++ async def list_tools(+ self,+ ) -> list[Callable[..., Coroutine[Any, Any, ToolResponse]]]:+ """List all tool functions provided to agent++ Returns:+ `list[Callable[..., ToolResponse]]`:+ A list of all tool functions provided by the plan notebook to+ the agent.+ """+ return [+ self.view_subtasks,+ self.update_subtask_state,+ self.finish_subtask,+ self.create_plan,+ self.revise_current_plan,+ self.finish_plan,+ self.view_historical_plans,+ self.recover_historical_plan,+ ]++ async def get_current_hint(self) -> Msg | None:+ """Get the hint message based on the current plan and subtasks states.+ This function will call the `plan_to_hint` function to generate the+ hint message.++ Returns:+ `Msg | None`:+ The hint message wrapped by <system-hint></system-hint>, or+ None if there is no relevant hint.+ """+ hint_content = self.plan_to_hint(self.current_plan)+ if hint_content:+ msg = Msg(+ "user",+ hint_content,+ "user",+ )+ return msg++ return None++ def register_plan_change_hook(+ self,+ hook_name: str,+ hook: Callable[["PlanNotebook", Plan], None],+ ) -> None:+ """Register a plan hook that will be triggered when the plan is+ changed.++ Args:+ hook_name (`str`):+ The name of the hook, should be unique.+ hook (`Callable[[Plan], None]`):+ The hook function, which takes the current plan as input and+ returns nothing.+ """+ self._plan_change_hooks[hook_name] = hook++ def remove_plan_change_hook(self, hook_name: str) -> None:+ """Remove a plan change hook by given name.++ Args:+ hook_name (`str`):+ The name of the hook to be removed.+ """+ if hook_name in self._plan_change_hooks:+ self._plan_change_hooks.pop(hook_name)+ else:+ raise ValueError(f"Hook '{hook_name}' not found.")++ async def _trigger_plan_change_hooks(self) -> None:+ """Trigger all the plan change hooks."""+ for hook in self._plan_change_hooks.values():+ await _execute_async_or_sync_func(+ hook,+ self,+ self.current_plan,+ )diff --git a/src/agentscope/plan/_storage_base.py b/src/agentscope/plan/_storage_base.pynew file mode 100644index 000000000..e06afbefd--- /dev/null+++ b/src/agentscope/plan/_storage_base.py@@ -0,0 +1,26 @@+# -*- coding: utf-8 -*-+"""The base class for plan storage."""+from abc import abstractmethod++from agentscope.module import StateModule+from agentscope.plan._plan_model import Plan+++class PlanStorageBase(StateModule):+ """The base class for plan storage."""++ @abstractmethod+ async def add_plan(self, plan: Plan) -> None:+ """Add a plan to the storage."""++ @abstractmethod+ async def delete_plan(self, plan_id: str) -> None:+ """Delete a plan from the storage."""++ @abstractmethod+ async def get_plans(self) -> list[Plan]:+ """Get all plans from the storage."""++ @abstractmethod+ async def get_plan(self, plan_id: str) -> Plan | None:+ """Get a plan by its ID."""diff --git a/tests/plan_test.py b/tests/plan_test.pynew file mode 100644index 000000000..7b6225923--- /dev/null+++ b/tests/plan_test.py@@ -0,0 +1,271 @@+# -*- coding: utf-8 -*-+"""The plan module related tests."""+from unittest import IsolatedAsyncioTestCase++from agentscope.plan import SubTask, Plan, PlanNotebook+++class PlanTest(IsolatedAsyncioTestCase):+ """Test the plan module."""++ async def asyncSetUp(self) -> None:+ """Set up the test case."""+ self.subtask1 = SubTask(+ name="Task 1",+ description="Description 1",+ expected_outcome="Expected outcome 1",+ state="done",+ )++ self.subtask2 = SubTask(+ name="Task 2",+ description="Description 2",+ expected_outcome="Expected outcome 2",+ state="in_progress",+ )++ self.subtask3 = SubTask(+ name="Task 3",+ description="Description 3",+ expected_outcome="Expected outcome 3",+ state="todo",+ )++ self.plan = Plan(+ name="Create website",+ description="Create a personal portfolio website.",+ expected_outcome="A new personal portfolio website is created on "+ "GitHub.",+ subtasks=[self.subtask1, self.subtask2, self.subtask3],+ )++ async def test_plan_model(self) -> None:+ """Test the models used in plan module."""++ self.assertEqual(+ self.subtask1.to_markdown(detailed=True),+ f"""- [x] Task 1+\t- Created At: {self.subtask1.created_at}+\t- Description: Description 1+\t- Expected Outcome: Expected outcome 1+\t- State: done+\t- Finished At: None+\t- Actual Outcome: None""",+ )++ self.assertEqual(+ self.subtask1.to_markdown(detailed=False),+ """- [x] Task 1""",+ )++ self.assertEqual(+ self.plan.to_markdown(detailed=True),+ f"""# Create website+**Description**: Create a personal portfolio website.+**Expected Outcome**: A new personal portfolio website is created on GitHub.+**State**: todo+**Created At**: {self.plan.created_at}+## Subtasks+- [x] Task 1+\t- Created At: {self.subtask1.created_at}+\t- Description: Description 1+\t- Expected Outcome: Expected outcome 1+\t- State: done+\t- Finished At: None+\t- Actual Outcome: None+- [ ] [WIP]Task 2+\t- Created At: {self.subtask2.created_at}+\t- Description: Description 2+\t- Expected Outcome: Expected outcome 2+\t- State: in_progress+- [ ] Task 3+\t- Created At: {self.subtask3.created_at}+\t- Description: Description 3+\t- Expected Outcome: Expected outcome 3+\t- State: todo""",+ )++ self.assertEqual(+ self.plan.to_markdown(detailed=True),+ f"""# Create website+**Description**: Create a personal portfolio website.+**Expected Outcome**: A new personal portfolio website is created on GitHub.+**State**: todo+**Created At**: {self.plan.created_at}+## Subtasks+- [x] Task 1+\t- Created At: {self.subtask1.created_at}+\t- Description: Description 1+\t- Expected Outcome: Expected outcome 1+\t- State: done+\t- Finished At: None+\t- Actual Outcome: None+- [ ] [WIP]Task 2+\t- Created At: {self.subtask2.created_at}+\t- Description: Description 2+\t- Expected Outcome: Expected outcome 2+\t- State: in_progress+- [ ] Task 3+\t- Created At: {self.subtask3.created_at}+\t- Description: Description 3+\t- Expected Outcome: Expected outcome 3+\t- State: todo""",+ )++ async def test_plan_subtasks(self) -> None:+ """Test the plan and subtask models."""+ plan_notebook = PlanNotebook()++ self.assertListEqual(+ [_.__name__ for _ in await plan_notebook.list_tools()],+ [+ "view_subtasks",+ "update_subtask_state",+ "finish_subtask",+ "create_plan",+ "revise_current_plan",+ "finish_plan",+ "view_historical_plans",+ "recover_historical_plan",+ ],+ )++ plan_hint = await plan_notebook.get_current_hint()+ self.assertEqual(+ plan_hint.get_text_content(),+ "<system-hint>If the user's query is complex (e.g. "+ "programming a website, game or app), or requires a long chain of "+ "steps to complete (e.g. conduct research on a certain topic from "+ "different sources), you NEED to create a plan first by calling "+ "'create_plan'. Otherwise, you can directly execute the user's "+ "query without planning.</system-hint>",+ )++ res = await plan_notebook.create_plan(+ name="Example Plan",+ description="Example Description",+ expected_outcome="Example Expected Outcome",+ subtasks=[self.subtask1, self.subtask2, self.subtask3],+ )+ self.assertEqual(+ res.content[0]["text"],+ "Plan 'Example Plan' created successfully.",+ )++ res = await plan_notebook.view_subtasks([3])+ self.assertEqual(+ res.content[0]["text"],+ "Invalid subtask_idx '[3]'. Must be between 0 and 2.",+ )+ res = await plan_notebook.view_subtasks([0, 2])+ self.assertEqual(+ res.content[0]["text"],+ f"""Subtask at index 0:+```+- [x] Task 1+\t- Created At: {self.subtask1.created_at}+\t- Description: Description 1+\t- Expected Outcome: Expected outcome 1+\t- State: done+\t- Finished At: None+\t- Actual Outcome: None+```++Subtask at index 2:+```+- [ ] Task 3+\t- Created At: {self.subtask3.created_at}+\t- Description: Description 3+\t- Expected Outcome: Expected outcome 3+\t- State: todo+```+""",+ )++ await plan_notebook.revise_current_plan(+ 1,+ action="add",+ subtask=SubTask(+ name="Task 11",+ description="Description 11",+ expected_outcome="Expected outcome 11",+ ),+ )+ self.assertEqual(+ plan_notebook.current_plan.subtasks[1].name,+ "Task 11",+ )+ self.assertEqual(+ len(plan_notebook.current_plan.subtasks),+ 4,+ )++ res = await plan_notebook.revise_current_plan(+ 1,+ "delete",+ )+ self.assertEqual(+ res.content[0]["text"],+ "Subtask (named 'Task 11') at index 1 is deleted successfully.",+ )+ self.assertEqual(+ len(plan_notebook.current_plan.subtasks),+ 3,+ )++ res = await plan_notebook.revise_current_plan(+ 1,+ "revise",+ subtask=SubTask(+ name="Task 22",+ description="Description 22",+ expected_outcome="Expected outcome 22",+ ),+ )+ self.assertEqual(+ res.content[0]["text"],+ "Subtask at index 1 is revised successfully.",+ )+ self.assertEqual(+ plan_notebook.current_plan.subtasks[1].name,+ "Task 22",+ )+ self.assertEqual(+ len(plan_notebook.current_plan.subtasks),+ 3,+ )++ res = await plan_notebook.update_subtask_state(+ 2,+ "in_progress",+ )+ self.assertEqual(+ res.content[0]["text"],+ "Subtask (at index 1) named 'Task 22' is not done yet. "+ "You should finish the previous subtasks first.",+ )++ await plan_notebook.update_subtask_state(0, "in_progress")+ res = await plan_notebook.update_subtask_state(+ 1,+ "in_progress",+ )+ self.assertEqual(+ res.content[0]["text"],+ "Subtask (at index 0) named 'Task 1' is not done yet. You "+ "should finish the previous subtasks first.",+ )++ res = await plan_notebook.finish_subtask(+ 0,+ "Fake outcome for task 1",+ )+ self.assertEqual(+ res.content[0]["text"],+ "Subtask (at index 0) named 'Task 1' is marked as done "+ "successfully. The next subtask named 'Task 22' is activated.",+ )+ self.assertEqual(+ plan_notebook.current_plan.subtasks[1].state,+ "in_progress",+ )