Skip to content
Open
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
1 change: 0 additions & 1 deletion data-agent-backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,6 @@
<groupId>io.agentscope</groupId>
<artifactId>agentscope-extensions-nacos-skill</artifactId>
<version>${agentscope.version}</version>
<optional>true</optional>
</dependency>

<dependency>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
public class DataAgentApplication {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,33 +79,27 @@ public void init() {
}

public Flux<ChatStreamEvent> chatStream(
int userId,
String sessionId,
String userInput,
List<ChatRequest.ToolResultInput> toolResults,
Integer datasourceId) {
return Flux.defer(
() -> streamAgent(userId, sessionId, userInput, toolResults, datasourceId))
.onErrorResume(this::toErrorEvent);
ToolCallContext context, List<ChatRequest.ToolResultInput> toolResults) {
Flux<ChatStreamEvent> stream = Flux.defer(() -> streamAgent(context, toolResults));
if (!context.scheduled()) {
return stream.onErrorResume(this::toErrorEvent);
}
return stream;
}

private Flux<ChatStreamEvent> streamAgent(
int userId,
String sessionId,
String userInput,
List<ChatRequest.ToolResultInput> toolResults,
Integer datasourceId) {
// 首次访问声明归属;已绑定会被 INSERT IGNORE 忽略
sessionService.bindUserSession(userId, sessionId);
if (datasourceId != null) {
datasourceService.bindSessionDatasource(sessionId, datasourceId);
ToolCallContext context, List<ChatRequest.ToolResultInput> toolResults) {
if (context.userId() != null) {
sessionService.bindUserSession(context.userId(), context.sessionId());
}
if (context.datasourceId() != null) {
datasourceService.bindSessionDatasource(context.sessionId(), context.datasourceId());
}
ReActAgent agent =
createAgent(ToolCallContext.builder().sessionId(sessionId).userId(userId).build());
ReActAgent agent = createAgent(context);

Session session = sessionService.getOrCreateSession(sessionId);
agent.loadIfExists(session, sessionId);
Msg userMsg = buildUserMessage(userInput, toolResults);
Session session = sessionService.getOrCreateSession(context.sessionId());
agent.loadIfExists(session, context.sessionId());
Msg userMsg = buildUserMessage(context.userInput(), toolResults);

StreamOptions streamOptions =
StreamOptions.builder()
Expand All @@ -128,13 +122,13 @@ private Flux<ChatStreamEvent> streamAgent(
signalType ->
log.info(
"SSE chat stream finished: sessionId={}, signal={}",
sessionId,
context.sessionId(),
signalType))
.subscribeOn(Schedulers.boundedElastic())
.flatMapIterable(eventConverter::map)
.doFinally(
signalType -> {
agent.saveTo(session, sessionId);
agent.saveTo(session, context.sessionId());
MDC.remove(TraceIdFilter.TRACE_ID_MDC_KEY);
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,9 @@
import lombok.Builder;

@Builder
public record ToolCallContext(String sessionId, Integer userId) {}
public record ToolCallContext(
String sessionId,
String userInput,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ToolCallContext定位是 “向工具传递业务上下文”, 详细看文档 “https://java.agentscope.io/v1/zh/docs/quickstart/agent.html#id4”
所以不要把 userInput、datasourceId 这种不向 工具传递业务上下文的放在这个对象。
userid需要保留在这个工具,因为后面鉴权的时候工具需要依赖它。

Integer datasourceId,
Integer userId,
boolean scheduled) {}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import io.agentscope.core.tool.Tool;
import io.agentscope.core.tool.ToolParam;
import io.agentscope.core.tool.ToolSuspendException;
import io.github.malonetalk.agent.ToolCallContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

Expand All @@ -34,8 +35,13 @@ public class AskUserTool implements MarkAgentTool {
+ " confirmation. Execution resumes after the user responds.")
public String askUser(
@ToolParam(name = "question", description = "The question to ask the user.")
String question) {
String question,
ToolCallContext ctx) {
log.info("Agent asks user: {}", question);
if (ctx.scheduled()) {
return "Cannot ask the user during this run. Explain what information is missing and"
+ " stop.";
}
throw new ToolSuspendException(question);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,15 @@ public final class Constants {
public static final String SORT_ORDER_ASC = "asc";
public static final String SORT_ORDER_DESC = "desc";

/** 管理员角色 id:AuthInterceptor 靠 role_id==1 判 @AdminOnly,删掉即永久锁死管理员。 */
/**
* 管理员角色 id:AuthInterceptor 靠 role_id==1 判 @AdminOnly,删掉即永久锁死管理员。
*/
public static final int ADMIN_ROLE_ID = 1;

public static final String PROPERTIES_PREFIX = "io.github.malonetalk";

public static final String SCHEDULE_PROPERTIES_PREFIX = PROPERTIES_PREFIX + ".schedule";

private Constants() {
throw new IllegalCallerException("No Constants Instance for You!");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/*
* 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.config;

import static io.github.malonetalk.common.Constants.SCHEDULE_PROPERTIES_PREFIX;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.time.Duration;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

@Validated
@Component
@ConfigurationProperties(prefix = SCHEDULE_PROPERTIES_PREFIX)
@Data
public class ScheduledAgentScheduleProperties {

@Positive private int batchSize;

private long dispatchDelayMs;

@NotNull private Duration lockDuration;

@Valid @NotNull private Executor executor = new Executor();

@Data
public static class Executor {

@Positive private int corePoolSize;

@Positive private int maxPoolSize;

@Positive private int queueCapacity;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import io.agentscope.core.message.Msg;
import io.github.malonetalk.agent.AgentService;
import io.github.malonetalk.agent.SessionService;
import io.github.malonetalk.agent.ToolCallContext;
import io.github.malonetalk.common.ErrorCode;
import io.github.malonetalk.common.Result;
import io.github.malonetalk.common.UserContext;
Expand Down Expand Up @@ -57,16 +58,17 @@ public class AgentController {
@PostMapping(value = "/chat/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<ChatStreamEvent>> chatStream(
@Valid @RequestBody ChatRequest request) {
// 在 servlet 线程抓 userId,避免 Reactor 线程拿不到 ThreadLocal
int userId = UserContext.require().userId();
log.info("SSE chat stream started: sessionId={}, userId={}", request.sessionId(), userId);
ToolCallContext context =
ToolCallContext.builder()
.sessionId(request.sessionId())
.userInput(request.message())
.datasourceId(request.datasourceId())
.userId(userId)
.build();
return agentService
.chatStream(
userId,
request.sessionId(),
request.message(),
request.toolResults(),
request.datasourceId())
.chatStream(context, request.toolResults())
.map(
event ->
ServerSentEvent.<ChatStreamEvent>builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* 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.controller;

import io.github.malonetalk.common.Result;
import io.github.malonetalk.dto.ScheduledAgentTaskRequest;
import io.github.malonetalk.dto.ScheduledAgentTaskResponse;
import io.github.malonetalk.service.ScheduledAgentTaskService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/scheduled-agent-tasks")
public class ScheduledAgentTaskController {

private final ScheduledAgentTaskService taskService;

@PostMapping
public Result<Void> create(@Valid @RequestBody ScheduledAgentTaskRequest request) {
taskService.create(request);
return Result.success();
}

@PutMapping("/{id}")
public Result<Void> update(
@PathVariable @Positive(message = "id must be positive.") Integer id,
@Valid @RequestBody ScheduledAgentTaskRequest request) {
taskService.update(id, request);
return Result.success();
}

@DeleteMapping("/{id}")
public Result<Void> delete(
@PathVariable @Positive(message = "id must be positive.") Integer id) {
taskService.delete(id);
return Result.success();
}

@GetMapping
public Result<List<ScheduledAgentTaskResponse>> listAll() {
return Result.success(taskService.listAll());
}

@PatchMapping("/{id}/enabled")
public Result<Void> setEnabled(
@PathVariable @Positive(message = "id must be positive.") Integer id,
@Valid @RequestBody EnabledRequest request) {
taskService.setEnabled(id, request.enabled());
return Result.success();
}

@PostMapping("/{id}/run")
public Result<Boolean> runNow(
@PathVariable @Positive(message = "id must be positive.") Integer id) {
return Result.success(taskService.runNow(id));
}

private record EnabledRequest(@NotNull(message = "enabled cannot be null.") Boolean enabled) {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* 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.dto;

import io.github.malonetalk.enums.ScheduledAgentScheduleType;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

public record ScheduledAgentTaskRequest(
@NotBlank(message = "name cannot be blank.") String name,
@NotBlank(message = "prompt cannot be blank.") String prompt,
@NotNull(message = "scheduleType cannot be null.") ScheduledAgentScheduleType scheduleType,
@NotBlank(message = "scheduleExpr cannot be blank.") String scheduleExpr,
Boolean enabled) {}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* 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.dto;

import io.github.malonetalk.entity.ScheduledAgentTask;
import java.time.LocalDateTime;
import lombok.Builder;

@Builder
public record ScheduledAgentTaskResponse(
Integer id,
String name,
String prompt,
String scheduleType,
String scheduleExpr,
Boolean enabled,
Boolean running,
LocalDateTime nextRunAt,
String lastStatus,
String lastError) {

public static ScheduledAgentTaskResponse from(ScheduledAgentTask task) {
return ScheduledAgentTaskResponse.builder()
.id(task.getId())
.name(task.getName())
.prompt(task.getPrompt())
.scheduleType(task.getScheduleType())
.scheduleExpr(task.getScheduleExpr())
.enabled(task.getEnabled())
.running(task.getRunning())
.nextRunAt(task.getNextRunAt())
.lastStatus(task.getLastStatus())
.lastError(task.getLastError())
.build();
}
}
Loading
Loading