diff --git a/README.md b/README.md
index d0f361efe..c7c5521bb 100644
--- a/README.md
+++ b/README.md
@@ -167,6 +167,8 @@ the following libraries.
- [Conversation with Customized Tools](https://github.com/modelscope/agentscope/blob/main/examples/conversation_with_customized_services/)
- [Mixture of Agents Algorithm](https://github.com/modelscope/agentscope/blob/main/examples/conversation_mixture_of_agents/)
- [Conversation in Stream Mode](https://github.com/modelscope/agentscope/blob/main/examples/conversation_in_stream_mode/)
+ - [Conversation with CodeAct Agent](https://github.com/modelscope/agentscope/blob/main/examples/conversation_with_codeact_agent/)
+
- Game
- [Gomoku](https://github.com/modelscope/agentscope/blob/main/examples/game_gomoku)
diff --git a/README_ZH.md b/README_ZH.md
index a82e53e12..8c89ff927 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -153,10 +153,14 @@ AgentScope支持使用以下库快速部署本地模型服务。
- [通过对话查询SQL信息](./examples/conversation_nl2sql/)
- [与RAG智能体对话](./examples/conversation_with_RAG_agents)
- [与gpt-4o模型对话](./examples/conversation_with_gpt-4o)
+ - [与自定义服务对话](./examples/conversation_with_customized_services/)
+
- [与SoftWare Engineering智能体对话](./examples/conversation_with_swe-agent/)
- [自定义工具函数](./examples/conversation_with_customized_services/)
- [Mixture of Agents算法](https://github.com/modelscope/agentscope/blob/main/examples/conversation_mixture_of_agents/)
- [流式对话](https://github.com/modelscope/agentscope/blob/main/examples/conversation_in_stream_mode/)
+ - [与CodeAct智能体对话](https://github.com/modelscope/agentscope/blob/main/examples/conversation_with_codeact_agent/)
+
- 游戏
- [五子棋](./examples/game_gomoku)
diff --git a/docs/sphinx_doc/en/source/tutorial/204-service.md b/docs/sphinx_doc/en/source/tutorial/204-service.md
index 38b4047b0..0cfaec6a3 100644
--- a/docs/sphinx_doc/en/source/tutorial/204-service.md
+++ b/docs/sphinx_doc/en/source/tutorial/204-service.md
@@ -15,6 +15,7 @@ The following table outlines the various Service functions by type. These functi
| Service Scene | Service Function Name | Description |
|-----------------------------|----------------------------|----------------------------------------------------------------------------------------------------------------|
| Code | `execute_python_code` | Execute a piece of Python code, optionally inside a Docker container. |
+| | `NoteBookExecutor.run_code_on_notebook` | Compute Execute a segment of Python code in the IPython environment of the NoteBookExecutor, adhering to the IPython interactive computing style. |
| Retrieval | `retrieve_from_list` | Retrieve a specific item from a list based on given criteria. |
| | `cos_sim` | Compute the cosine similarity between two different embeddings. |
| SQL Query | `query_mysql` | Execute SQL queries on a MySQL database and return results. |
diff --git a/docs/sphinx_doc/zh_CN/source/tutorial/204-service.md b/docs/sphinx_doc/zh_CN/source/tutorial/204-service.md
index 23c145a05..00de68001 100644
--- a/docs/sphinx_doc/zh_CN/source/tutorial/204-service.md
+++ b/docs/sphinx_doc/zh_CN/source/tutorial/204-service.md
@@ -12,6 +12,7 @@
| Service场景 | Service函数名称 | 描述 |
|------------|-----------------------|-----------------------------------------|
| 代码 | `execute_python_code` | 执行一段 Python 代码,可选择在 Docker 容器内部执行。 |
+| | `NoteBookExecutor.run_code_on_notebook` | 在 NoteBookExecutor 的 IPython 环境中执行一段 Python 代码,遵循 IPython 交互式计算风格。 |
| 检索 | `retrieve_from_list` | 根据给定的标准从列表中检索特定项目。 |
| | `cos_sim` | 计算2个embedding的余弦相似度。 |
| SQL查询 | `query_mysql` | 在 MySQL 数据库上执行 SQL 查询并返回结果。 |
diff --git a/examples/conversation_with_codeact_agent/codeact_agent.py b/examples/conversation_with_codeact_agent/codeact_agent.py
new file mode 100644
index 000000000..d09b7fda4
--- /dev/null
+++ b/examples/conversation_with_codeact_agent/codeact_agent.py
@@ -0,0 +1,166 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=C0301
+"""An agent class that implements the CodeAct agent.
+This agent can execute code interactively as actions.
+More details can be found at the paper of codeact agent
+https://arxiv.org/abs/2402.01030
+and the original repo of codeact https://github.com/xingyaoww/code-act
+"""
+from agentscope.agents import AgentBase
+from agentscope.message import Msg
+from agentscope.service import (
+ ServiceResponse,
+ ServiceExecStatus,
+ NoteBookExecutor,
+)
+from agentscope.parsers import RegexTaggedContentParser
+
+SYSTEM_MESSAGE = """
+You are a helpful assistant that gives helpful, detailed, and polite answers to the user's questions.
+You should interact with the interactive Python (Jupyter Notebook) environment and receive the corresponding output when needed. The code written by assistant should be enclosed using tag, for example: print('Hello World!') .
+You should attempt fewer things at a time instead of putting too much code in one block. You can install packages through PIP by !pip install [package needed] and should always import packages and define variables before starting to use them.
+You should stop and provide an answer when they have already obtained the answer from the execution result. Whenever possible, execute the code for the user using instead of providing it.
+Your response should be concise, but do express their thoughts. Always write the code in block to execute them.
+You should not ask for the user's input unless necessary. Solve the task on your own and leave no unanswered questions behind.
+You should do every thing by your self.
+""" # noqa
+
+EXAMPLE_MESSAGE = """
+Additionally, you are provided with the following code available:
+{example_code}
+The above code is already available in your interactive Python (Jupyter Notebook) environment, allowing you to directly use these variables and functions without needing to redeclare them.
+""" # noqa
+
+
+class CodeActAgent(AgentBase):
+ """
+ The implementation of CodeAct-agent.
+ The agent can execute code interactively as actions.
+ More details can be found at the paper of codeact agent
+ https://arxiv.org/abs/2402.01030
+ and the original repo of codeact https://github.com/xingyaoww/code-act
+ """
+
+ def __init__(
+ self,
+ name: str,
+ model_config_name: str,
+ example_code: str = "",
+ ) -> None:
+ """
+ Initialize the CodeActAgent.
+ Args:
+ name(`str`):
+ The name of the agent.
+ model_config_name(`str`):
+ The name of the model configuration.
+ example_code(Optional`str`):
+ The example code to be executed bewfore the interaction.
+ You can import reference libs, define variables
+ and functions to be called. For example:
+
+ ```python
+ from agentscope.service import bing_search
+ import os
+
+ api_key = "{YOUR_BING_API_KEY}"
+
+ def search(question: str):
+ return bing_search(question, api_key=api_key, num_results=3).content
+ ```
+
+ """ # noqa
+ super().__init__(
+ name=name,
+ model_config_name=model_config_name,
+ )
+ self.n_max_executions = 5
+ self.example_code = example_code
+ self.code_executor = NoteBookExecutor()
+
+ sys_msg = Msg(name="system", role="system", content=SYSTEM_MESSAGE)
+ example_msg = Msg(
+ name="user",
+ role="user",
+ content=EXAMPLE_MESSAGE.format(example_code=self.example_code),
+ )
+
+ self.memory.add(sys_msg)
+
+ if self.example_code != "":
+ code_execution_result = self.code_executor.run_code_on_notebook(
+ self.example_code,
+ )
+ code_exec_msg = self.handle_code_result(
+ code_execution_result,
+ "Example Code excuted: ",
+ )
+ self.memory.add(example_msg)
+ self.memory.add(code_exec_msg)
+ self.speak(code_exec_msg)
+
+ self.parser = RegexTaggedContentParser(try_parse_json=False)
+
+ def handle_code_result(
+ self,
+ code_execution_result: ServiceResponse,
+ content_pre_sring: str = "",
+ ) -> Msg:
+ """return the message from code result"""
+ code_exec_content = content_pre_sring
+ if code_execution_result.status == ServiceExecStatus.SUCCESS:
+ code_exec_content += "Excution Successful:\n"
+ else:
+ code_exec_content += "Excution Failed:\n"
+ code_exec_content += "Execution Output:\n" + str(
+ code_execution_result.content,
+ )
+ return Msg(name="user", role="user", content=code_exec_content)
+
+ def reply(self, x: Msg = None) -> Msg:
+ """The reply function that implements the codeact agent."""
+
+ self.memory.add(x)
+
+ excution_count = 0
+ while (
+ self.memory.get_memory(1)[-1].role == "user"
+ and excution_count < self.n_max_executions
+ ):
+ prompt = self.model.format(self.memory.get_memory())
+ model_res = self.model(prompt)
+ msg_res = Msg(
+ name=self.name,
+ content=model_res.text,
+ role="assistant",
+ )
+ self.memory.add(msg_res)
+ self.speak(msg_res)
+ res = self.parser.parse(model_res)
+ code = res.parsed.get("execute")
+ if code is not None:
+ code = code.strip()
+ code_execution_result = (
+ self.code_executor.run_code_on_notebook(code)
+ )
+ excution_count += 1
+ code_exec_msg = self.handle_code_result(code_execution_result)
+ self.memory.add(code_exec_msg)
+ self.speak(code_exec_msg)
+
+ if excution_count == self.n_max_executions:
+ assert self.memory.get_memory(1)[-1].role == "user"
+ code_max_exec_msg = Msg(
+ name="assitant",
+ role="assistant",
+ content=(
+ "I have reached the maximum number "
+ f"of executions ({self.n_max_executions=}). "
+ "Can you assist me or ask me another question?"
+ ),
+ )
+ self.memory.add(code_max_exec_msg)
+ self.speak(code_max_exec_msg)
+ return code_max_exec_msg
+
+ return msg_res
diff --git a/examples/conversation_with_codeact_agent/codeact_agent_example_modeling.ipynb b/examples/conversation_with_codeact_agent/codeact_agent_example_modeling.ipynb
new file mode 100644
index 000000000..f7b80eba2
--- /dev/null
+++ b/examples/conversation_with_codeact_agent/codeact_agent_example_modeling.ipynb
@@ -0,0 +1,201 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# Conversation with CodeAct Agent\n",
+ "\n",
+ "CodeAct agent is an agent that not only chats but also writes and executes Python code for you.\n",
+ "More details can be found in the project's related [github repo](https://github.com/xingyaoww/code-act). In the example here, we implement the CodeAct agent, and provide a simple example of how to use the CodeAct agent.\n",
+ "\n",
+ "## Prerequisites\n",
+ "\n",
+ "- Follow [READMD.md](https://github.com/modelscope/agentscope) to install AgentScope. We require the lastest version, so you should build from source by running `pip install -e .` instead of intalling from pypi. \n",
+ "- Prepare a model configuration. AgentScope supports both local deployed model services (CPU or GPU) and third-party services. More details and example model configurations please refer to our [tutorial](https://modelscope.github.io/agentscope/en/tutorial/203-model.html).\n",
+ "\n",
+ "## Note\n",
+ "- The example is tested with the following models. For other models, you may need to adjust the prompt.\n",
+ " - qwen-max"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "YOUR_MODEL_CONFIGURATION_NAME = \"{YOUR_MODEL_CONFIGURATION_NAME}\"\n",
+ "\n",
+ "YOUR_MODEL_CONFIGURATION = {\n",
+ " \"model_type\": \"xxx\", \n",
+ " \"config_name\": YOUR_MODEL_CONFIGURATION_NAME\n",
+ " \n",
+ " # ...\n",
+ "}"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "### Step 1: Initalize the CodeAct-agent\n",
+ "\n",
+ "Here we load the CodeAct agent."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from codeact_agent import CodeActAgent\n",
+ "\n",
+ "import agentscope\n",
+ "\n",
+ "agentscope.init(model_configs=YOUR_MODEL_CONFIGURATION)\n",
+ "\n",
+ "import nest_asyncio\n",
+ "nest_asyncio.apply()\n",
+ "agent = CodeActAgent(\n",
+ " name=\"assistant\",\n",
+ " model_config_name=YOUR_MODEL_CONFIGURATION_NAME,\n",
+ ")\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "###Step 2: Ask the CodeAct-agent to execute tasks\n",
+ "\n",
+ "Here, we ask the CodeAct-agent to implement a statistical simulation and modeling procedure."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2024-05-16 19:48:01.620 | INFO | agentscope.models.model:__init__:201 - Initialize model by configuration [dashscope_chat-qwen-max]\n",
+ "2024-05-16 19:48:01.624 | INFO | agentscope.utils.monitor:register:417 - Register metric [qwen-max.call_counter] to SqliteMonitor with unit [times] and quota [None]\n",
+ "2024-05-16 19:48:01.627 | INFO | agentscope.utils.monitor:register:417 - Register metric [qwen-max.prompt_tokens] to SqliteMonitor with unit [token] and quota [None]\n",
+ "2024-05-16 19:48:01.630 | INFO | agentscope.utils.monitor:register:417 - Register metric [qwen-max.completion_tokens] to SqliteMonitor with unit [token] and quota [None]\n",
+ "2024-05-16 19:48:01.632 | INFO | agentscope.utils.monitor:register:417 - Register metric [qwen-max.total_tokens] to SqliteMonitor with unit [token] and quota [None]\n",
+ "user: Given y = 0.9x + 6.1, randomly sample data points as pairs of (x, y). Then fit a linear regression on the sampled data and plot the points, fitted line, and ground-truth line.\n",
+ "assistant: To accomplish this task, I will follow these steps:\n",
+ "\n",
+ "1. Generate random `x` values within a reasonable range.\n",
+ "2. Use the equation `y = 0.9x + 6.1` to compute the corresponding `y` values for each `x`.\n",
+ "3. Add some noise to the `y` values to simulate real-world data variability.\n",
+ "4. Split the data into training and testing sets (though for simplicity and since you didn't specify, we'll just use all the data for fitting).\n",
+ "5. Fit a linear regression model on the generated data.\n",
+ "6. Plot the original data points, the fitted line from the regression, and the ground-truth line.\n",
+ "\n",
+ "Let's start by generating the data points and fitting the regression model.\n",
+ "\n",
+ "[execute]\n",
+ "import numpy as np\n",
+ "import matplotlib.pyplot as plt\n",
+ "from sklearn.linear_model import LinearRegression\n",
+ "\n",
+ "# Set a seed for reproducibility\n",
+ "np.random.seed(42)\n",
+ "\n",
+ "# Generate random x values between 0 and 100\n",
+ "x_values = np.random.rand(100) * 100\n",
+ "\n",
+ "# Compute the corresponding y values without noise\n",
+ "y_values_ground_truth = 0.9 * x_values + 6.1\n",
+ "\n",
+ "# Add some noise to y values\n",
+ "noise = np.random.normal(0, 10, size=x_values.shape)\n",
+ "y_values_noisy = y_values_ground_truth + noise\n",
+ "\n",
+ "# Combine into a single dataset\n",
+ "data = np.column_stack((x_values, y_values_noisy))\n",
+ "\n",
+ "# Fit a linear regression model\n",
+ "model = LinearRegression()\n",
+ "model.fit(data[:, 0].reshape(-1, 1), data[:, 1])\n",
+ "\n",
+ "# Prepare to plot\n",
+ "plt.figure(figsize=(10, 6))\n",
+ "[/execute]\n",
+ "user: Execution Output:\n",
+ "['