Continue AI tasks in a fresh context after compaction
This commit is contained in:
1 parent
db82325ed7
commit
e48ae583f9
7 files changed
+358
-16
No files matched your search
@@ -244,6 +244,62 @@ public class TaskService {
|
||||
.toList();
|
||||
}
|
||||
|
||||
record AgentHistory(List<JsonNode> messages, String summary, int through, int last) {
|
||||
boolean canRotate() {
|
||||
return through < 0 ? messages.size() > 2 : last > through;
|
||||
}
|
||||
}
|
||||
|
||||
AgentHistory agentHistory(UUID id) {
|
||||
var saved =
|
||||
db.queryForList(
|
||||
"SELECT through_sequence,summary FROM ai_task_context_checkpoints WHERE task_id=?", id);
|
||||
int through =
|
||||
saved.isEmpty() ? -1 : ((Number) saved.getFirst().get("through_sequence")).intValue();
|
||||
String summary = saved.isEmpty() ? "" : saved.getFirst().get("summary").toString();
|
||||
var rows =
|
||||
db.queryForList(
|
||||
"SELECT sequence_no,payload FROM ai_task_messages WHERE task_id=? AND"
|
||||
+ " (sequence_no=0 OR sequence_no>?) ORDER BY sequence_no",
|
||||
id,
|
||||
through);
|
||||
var messages = new ArrayList<JsonNode>(rows.size());
|
||||
for (var row : rows) {
|
||||
try {
|
||||
messages.add(json.readTree(row.get("payload").toString()));
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
int last = rows.isEmpty() ? through : ((Number) rows.getLast().get("sequence_no")).intValue();
|
||||
return new AgentHistory(messages, summary, through, last);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void checkpoint(UUID id, String lease, AgentHistory history, String summary) {
|
||||
locked(id, lease);
|
||||
if (!history.canRotate()) return;
|
||||
if (history.through() < 0) {
|
||||
db.update(
|
||||
"INSERT INTO ai_task_context_checkpoints(task_id,through_sequence,summary) VALUES"
|
||||
+ " (?,?,?)",
|
||||
id,
|
||||
history.last(),
|
||||
summary);
|
||||
} else {
|
||||
int updated =
|
||||
db.update(
|
||||
"UPDATE ai_task_context_checkpoints SET through_sequence=?,summary=?"
|
||||
+ " WHERE task_id=? AND through_sequence=?",
|
||||
history.last(),
|
||||
summary,
|
||||
id,
|
||||
history.through());
|
||||
if (updated != 1) throw new ApiError.Failure(409, "任务上下文交接记录已更新");
|
||||
}
|
||||
event(id, "CONTEXT_COMPACTED", "已自动压缩上下文并开启下一段对话,继续当前任务");
|
||||
}
|
||||
|
||||
public Map<String, Object> config(UUID id) {
|
||||
return db.queryForMap("SELECT * FROM ai_tasks WHERE id=?", id);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user