Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.agentscope.core.agent.EventType;
import io.agentscope.core.agent.StreamOptions;
import io.agentscope.core.memory.InMemoryMemory;
import io.agentscope.core.memory.Memory;
import io.agentscope.core.message.ContentBlock;
import io.agentscope.core.message.Msg;
import io.agentscope.core.message.MsgRole;
Expand Down Expand Up @@ -278,16 +279,20 @@ private Flux<ChatStreamEvent> toErrorEvent(Throwable exception) {
}

private ReActAgent createAgent(ToolCallContext toolCallContext) {
var memory = new InMemoryMemory();
ToolExecutionContext context =
ToolExecutionContext.builder().register(toolCallContext).build();
ToolExecutionContext.builder()
.register(toolCallContext)
.register(Memory.class, memory)
.build();
return ReActAgent.builder()
.name("DataAgent")
.sysPrompt(systemPrompt())
.model(modelFactory.getInstance(modelProperties))
.toolkit(toolkit)
.toolExecutionContext(context)
.skillBox(skillBox)
.memory(new InMemoryMemory())
.memory(memory)
.maxIters(10)
.enablePendingToolRecovery(true)
.build();
Expand All @@ -305,6 +310,8 @@ private String systemPrompt() {
先调用 get_datasources;调用 get_tables、get_table_schema、get_metric_caliber、
execute_sql 或 export_table 时,如果存在多个可选数据源,必须传 datasource_id。
不同数据源的同名表不能混用。
用户需要图表时,先执行 SQL 获取 Result ID,再调用 generate_chart,图表数值必须来自该查询结果。
SQL 负责聚合与排序;绘图只指定字段映射。修改图表类型时可复用本会话已有的 Result ID。
"""
.formatted(today, today.minusDays(1), today.plusDays(1));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ public AuthorizedSqlBo authorizeSelect(DatasourcePo datasource, String sql, Inte
return sqlPermissions.authorize(userId, datasource, parseAllowedSelect(sql));
}

public AuthorizedSqlBo authorizeSelect(
DatasourcePo datasource,
String sql,
Integer userId,
Map<String, Set<String>> previousColumns) {
return sqlPermissions.authorize(
userId, datasource, parseAllowedSelect(sql), previousColumns);
}

public String validateSelectSql(String sql) {
parseAllowedSelect(sql);
return trimTrailingSemicolon(sql);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
*/
package io.github.malonetalk.agent.tools.impls;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.ToolParam;
import io.github.malonetalk.agent.ToolCallContext;
Expand All @@ -30,8 +28,10 @@
import io.github.malonetalk.agent.tools.ToolDatasourceResolver;
import io.github.malonetalk.agent.tools.ToolExceptionMapper;
import io.github.malonetalk.agent.tools.ToolResultBoConverter;
import io.github.malonetalk.model.bo.QuerySnapshotBo;
import io.github.malonetalk.model.bo.SqlToolMetadataBo;
import io.github.malonetalk.model.bo.ToolResultBo;
import io.github.malonetalk.model.converter.ChartConverter;
import io.github.malonetalk.model.po.DatasourcePo;
import java.util.Map;
import lombok.AllArgsConstructor;
Expand All @@ -44,7 +44,7 @@ public class ExecuteSqlTool implements DataAgentTool {
private final ToolDatasourceResolver datasourceResolver;
private final SqlExecutor sqlExecutor;
private final ToolExceptionMapper toolExceptionMapper;
private final ObjectMapper objectMapper;
private final ChartConverter chartConverter;

@RestTool
@Tool(
Expand Down Expand Up @@ -80,9 +80,17 @@ public ToolResultBo executeSql(
.returnedRows(execution.result().rows().size())
.truncated(execution.result().truncated())
.build();
Map<String, Object> resultMetadata =
objectMapper.convertValue(metadata, new TypeReference<>() {});
return new ToolResultBo(formatResult(execution.result()), resultMetadata);
Map<String, Object> resultMetadata = chartConverter.toMetadata(metadata);
var snapshot = chartConverter.snapshot(sql, execution.result());
snapshot.ifPresent(
value -> resultMetadata.put(QuerySnapshotBo.METADATA_KEY, value));
String reference =
snapshot.map(value -> "Result ID: " + value.get("resultId") + "\n")
.orElse(
"Chart snapshot exceeds size limit. Select fewer"
+ " columns or aggregate the SQL.\n");
return new ToolResultBo(
reference + formatResult(execution.result()), resultMetadata);
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
/*
* Copyright (C) 2026 github.com/MaloneTalk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* limitations under the License.
*/
package io.github.malonetalk.agent.tools.impls;

import io.agentscope.core.memory.Memory;
import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.ToolParam;
import io.github.malonetalk.agent.ToolCallContext;
import io.github.malonetalk.agent.tools.DataAgentTool;
import io.github.malonetalk.agent.tools.ToolExceptionMapper;
import io.github.malonetalk.agent.tools.ToolResultBoConverter;
import io.github.malonetalk.model.bo.ChartPayloadBo;
import io.github.malonetalk.model.bo.ChartSpecBo;
import io.github.malonetalk.model.bo.ToolResultBo;
import io.github.malonetalk.model.converter.ChartConverter;
import io.github.malonetalk.service.ChartService;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class GenerateChartTool implements DataAgentTool {
private final ChartService chartService;
private final ChartConverter converter;
private final ToolExceptionMapper toolExceptionMapper;

@Tool(
name = "generate_chart",
converter = ToolResultBoConverter.class,
description =
"""
根据本会话 execute_sql 的真实查询结果生成交互图表,图表会直接展示在聊天中。
必须先执行 SQL 并获得 Result ID,再调用本工具;只填写图表类型和字段映射,不传数据或代码。
SQL 应先完成聚合和 ORDER BY;截断、空结果或重复维度需要先调整 SQL。
支持 bar、line、pie、scatter。折线图和柱状图支持多个指标及可选分组。
饼图仅支持一个非负指标且不分组;散点图要求横纵轴均为数值。
改图时可复用同一个 Result ID。成功后无需重复输出图表配置或数据。
""")
public ToolResultBo generateChart(
@ToolParam(name = "result_id", description = "Result ID returned by execute_sql")
String resultId,
@ToolParam(name = "chart_type", description = "bar, line, pie or scatter")
String chartType,
@ToolParam(name = "title", description = "Short chart title") String title,
@ToolParam(
name = "x_field",
description = "Query column for the category or scatter x axis")
String xField,
@ToolParam(name = "y_fields", description = "Numeric query columns for measures")
List<String> yFields,
@ToolParam(
name = "series_field",
description = "Optional query column for grouping",
required = false)
String seriesField,
Memory memory,
ToolCallContext context) {
return toolExceptionMapper.runResult(
() -> {
var spec =
ChartSpecBo.builder()
.chartType(chartType)
.title(title)
.xField(xField)
.yFields(yFields)
.seriesField(Optional.ofNullable(seriesField).orElse(""))
.build();
var chart =
chartService.generate(resultId, spec, memory.getMessages(), context);
return new ToolResultBo(
"Chart generated: " + title,
Map.of(ChartPayloadBo.METADATA_KEY, converter.toMetadata(chart)));
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.github.malonetalk.enums.ChatStreamEventType;
import io.github.malonetalk.model.bo.ChartPayloadBo;
import java.util.Map;
import lombok.Builder;

Expand All @@ -46,5 +48,11 @@ public record ToolResultInfo(
public ToolResultInfo(String id, String name, String output, boolean suspended) {
this(id, name, output, suspended, Map.of());
}

@JsonProperty("chart")
@JsonInclude(JsonInclude.Include.NON_NULL)
public Object chart() {
return metadata.get(ChartPayloadBo.METADATA_KEY);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2026 github.com/MaloneTalk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* limitations under the License.
*/
package io.github.malonetalk.model.bo;

import java.util.List;
import java.util.Map;

public record ChartPayloadBo(ChartSpecBo spec, List<Map<String, Object>> rows) {
public static final String METADATA_KEY = "chart";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* Copyright (C) 2026 github.com/MaloneTalk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* limitations under the License.
*/
package io.github.malonetalk.model.bo;

import java.util.List;
import lombok.Builder;

/** Only field mappings are supplied by the model; values come from a query snapshot. */
@Builder
public record ChartSpecBo(
String chartType, String title, String xField, List<String> yFields, String seriesField) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (C) 2026 github.com/MaloneTalk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* limitations under the License.
*/
package io.github.malonetalk.model.bo;

import io.github.malonetalk.agent.datasource.QueryResult;

/** Query data retained in tool metadata and restored with the conversation. */
public record QuerySnapshotBo(String resultId, String originalSql, QueryResult result) {
public static final String METADATA_KEY = "querySnapshot";
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* Copyright (C) 2026 github.com/MaloneTalk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
* limitations under the License.
*/
package io.github.malonetalk.model.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.malonetalk.agent.datasource.QueryResult;
import io.github.malonetalk.model.bo.ChartPayloadBo;
import io.github.malonetalk.model.bo.QuerySnapshotBo;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@RequiredArgsConstructor
public class ChartConverter {
private static final int MAX_SNAPSHOT_BYTES = 256 * 1024;
private final ObjectMapper objectMapper;

public Optional<Map<String, Object>> snapshot(String sql, QueryResult result)
throws JsonProcessingException {
List<Map<String, Object>> rows = result.rows().stream().map(this::jsonRow).toList();
var snapshot =
new QuerySnapshotBo(
UUID.randomUUID().toString(),
sql,
new QueryResult(
result.columns(), rows, result.totalRows(), result.truncated()));
Map<String, Object> value = toMetadata(snapshot);
return objectMapper.writeValueAsBytes(value).length <= MAX_SNAPSHOT_BYTES
? Optional.of(value)
: Optional.empty();
}

public Map<String, Object> toMetadata(Object value) {
return objectMapper.convertValue(value, new TypeReference<>() {});
}

public Map<String, Object> toMetadata(ChartPayloadBo chart) {
var spec = chart.spec();
List<Map<String, Object>> rows =
chart.rows().stream()
.map(
row -> {
Map<String, Object> converted = new LinkedHashMap<>(row);
if (!"scatter".equals(spec.chartType())) {
converted.computeIfPresent(
spec.xField(), (field, value) -> value.toString());
}
if (StringUtils.hasText(spec.seriesField())) {
converted.computeIfPresent(
spec.seriesField(),
(field, value) -> value.toString());
}
return converted;
})
.toList();
return toMetadata((Object) new ChartPayloadBo(spec, rows));
}

private Map<String, Object> jsonRow(Map<String, Object> row) {
Map<String, Object> converted = new LinkedHashMap<>();
row.forEach(
(field, value) ->
converted.put(
field,
value == null
|| value instanceof String
|| value instanceof Number
|| value instanceof Boolean
? value
: value.toString()));
return converted;
}
}
Loading
Loading