Skip to content

Commit 876e6b9

Browse files
authored
Feat/add python capbility (#59)
* feat(python): add execute_python agent tool Add a sandboxed execute_python tool that runs analysis code with a concurrency cap (Semaphore, max 5) and a 30s timeout, invoked via python3 -I in an isolated temp dir that is cleaned up afterward. Targets statistical workloads (correlation, regression, distribution tests) that SQL cannot express. * docs: document Python data-analysis capability in README Update the README to reflect the new execute_python tool: restate the product as a data-analysis agent, add a Python analysis feature bullet, list Python in the tool set, and add Python 3+ (with pandas/numpy/scipy) to prerequisites.
1 parent cd04d6f commit 876e6b9

2 files changed

Lines changed: 129 additions & 3 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
> An LLM-powered data query agent that maps business language to data through a semantic layer.
44
5-
**Data Agent** 是一个面向业务人员的自然语言数据查询智能体:你用中文提问,它把问题理解成 SQL、在目标数据库上执行,并以流式对话的方式把结果与分析返回给你。它内置**语义层**,把"业务语言"映射到"数据表示",让 LLM 真正"懂业务"。
5+
**Data Agent** 是一个面向业务人员的自然语言数据分析智能体:你用中文提问,它把问题理解成 SQL 或 Python 分析代码、执行查询与统计计算,并以流式对话的方式把结果与分析返回给你。它内置**语义层**,把"业务语言"映射到"数据表示",让 LLM 真正"懂业务"。
66

77
[![Backend CI](https://github.com/MaloneTalk/DataAgent/actions/workflows/backend.yml/badge.svg)](https://github.com/MaloneTalk/DataAgent/actions/workflows/backend.yml)
88
[![Frontend CI](https://github.com/MaloneTalk/DataAgent/actions/workflows/frontend.yml/badge.svg)](https://github.com/MaloneTalk/DataAgent/actions/workflows/frontend.yml)
@@ -14,6 +14,7 @@
1414
## ✨ 特性
1515

1616
- **自然语言查数**:基于 LLM + ReAct 工具调用,把自然语言转为 SQL 并在目标库执行,全程流式输出。
17+
- **Python 数据分析**:对查询结果自动执行统计分析(相关性、回归、分布检验),补齐 SQL 在复杂统计计算上的短板。
1718
- **多模型可切换**:内置 OpenAI / Ollama / 通义 DashScope / Anthropic 等提供商,换底座模型不影响已沉淀的业务知识。
1819
- **多数据源**:支持查询 MySQL、PostgreSQL、Oracle。
1920
- **语义层**:域(Domain)/ 逻辑表 / 逻辑列 / 表关系 / 指标口径的业务映射,让 LLM 真正"懂业务"。
@@ -30,7 +31,7 @@
3031
▼
3132
AgentService (ReAct 循环)
3233
┌───────────────┴───────────────┬──────────────────┐
33-
LLM(可切换底座) 工具集(SQL/Schema/反问/报表) 语义层 (MySQL)
34+
LLM(可切换底座) 工具集(SQL/Schema/Python/反问/报表) 语义层 (MySQL)
3435
│
3536
▼
3637
目标数据源 (MySQL / PG / Oracle)
@@ -45,7 +46,7 @@
4546

4647
> 完整、带截图的步骤见 [docs/getting-started.md](docs/getting-started.md)。
4748
48-
**前置依赖**:JDK 17+、Maven 3.9+、Node 18+、pnpm 8+、MySQL 8+。
49+
**前置依赖**:JDK 17+、Maven 3.9+、Node 18+、pnpm 8+、MySQL 8+、Python 3+(需安装 pandas、numpy、scipy)。
4950

5051
```bash
5152
# 1. 建元数据库并初始化表结构
Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
/*
2+
* Copyright (C) 2026 github.com/MaloneTalk
3+
*
4+
* This program is free software: you can redistribute it and/or modify
5+
* it under the terms of the GNU Affero General Public License as
6+
* published by the Free Software Foundation, either version 3 of the
7+
* License, or any later version.
8+
*
9+
* This program is distributed in the hope that it will be useful,
10+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12+
* GNU Affero General Public License for more details.
13+
*
14+
* You should have received a copy of the GNU Affero General Public License
15+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
16+
* limitations under the License.
17+
*/
18+
package io.github.malonetalk.agent.tools;
19+
20+
import io.agentscope.core.tool.Tool;
21+
import io.agentscope.core.tool.ToolParam;
22+
import java.io.IOException;
23+
import java.nio.charset.StandardCharsets;
24+
import java.nio.file.Files;
25+
import java.nio.file.Path;
26+
import java.util.Comparator;
27+
import java.util.concurrent.Semaphore;
28+
import java.util.concurrent.TimeUnit;
29+
import lombok.extern.slf4j.Slf4j;
30+
import org.springframework.stereotype.Component;
31+
32+
@Slf4j
33+
@Component
34+
public class ExecutePythonTool implements MarkAgentTool {
35+
36+
private static final int TIMEOUT_SECONDS = 30;
37+
private static final int MAX_CONCURRENT = 5;
38+
private final Semaphore semaphore = new Semaphore(MAX_CONCURRENT);
39+
40+
@Tool(
41+
name = "execute_python",
42+
description =
43+
"""
44+
Execute Python code for data analysis. \
45+
Available libraries: pandas, numpy, scipy. \
46+
SQL query results have already been obtained in the conversation; \
47+
include the data directly in the Python code. \
48+
Print analysis results to stdout using print(). \
49+
Only use this when statistical computation \
50+
(correlation, regression, distribution tests, etc.) cannot be done in SQL.\
51+
""")
52+
public String executePython(
53+
@ToolParam(
54+
name = "code",
55+
description =
56+
"""
57+
Python code to execute for data analysis. \
58+
Must be self-contained and include any data inline.\
59+
""")
60+
String code) {
61+
62+
if (!semaphore.tryAcquire()) {
63+
return String.format(
64+
"Error: too many concurrent Python executions (max %d), try again later.",
65+
MAX_CONCURRENT);
66+
}
67+
try {
68+
return doExecute(code);
69+
} finally {
70+
semaphore.release();
71+
}
72+
}
73+
74+
private String doExecute(String code) {
75+
Path tmpDir = null;
76+
try {
77+
tmpDir = Files.createTempDirectory("pyexec-");
78+
Path script = tmpDir.resolve("script.py");
79+
Files.writeString(script, code);
80+
81+
var process =
82+
new ProcessBuilder("python3", "-I", script.toString())
83+
.directory(tmpDir.toFile())
84+
.redirectErrorStream(true)
85+
.start();
86+
87+
boolean finished = process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS);
88+
if (!finished) {
89+
process.destroyForcibly();
90+
process.waitFor(5, TimeUnit.SECONDS);
91+
return "Error: execution timed out after " + TIMEOUT_SECONDS + " seconds.";
92+
}
93+
94+
String output =
95+
new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
96+
97+
if (process.exitValue() != 0) {
98+
return "Error (exit " + process.exitValue() + "):\n" + output;
99+
}
100+
return output;
101+
} catch (IOException e) {
102+
log.error("Python execution I/O error", e);
103+
return "Error: " + e.getMessage();
104+
} catch (InterruptedException e) {
105+
Thread.currentThread().interrupt();
106+
return "Error: execution interrupted.";
107+
} finally {
108+
if (tmpDir != null) {
109+
try (var walk = Files.walk(tmpDir)) {
110+
walk.sorted(Comparator.reverseOrder())
111+
.forEach(
112+
p -> {
113+
try {
114+
Files.deleteIfExists(p);
115+
} catch (IOException ignored) {
116+
// best-effort cleanup
117+
}
118+
});
119+
} catch (IOException ignored) {
120+
// best-effort cleanup
121+
}
122+
}
123+
}
124+
}
125+
}

0 commit comments

Comments
 (0)