chore: Spring AI 重构

This commit is contained in:
abel533
2026-03-25 00:15:00 +08:00
parent a9c71002d2
commit 2afa4712cb
124 changed files with 11777 additions and 3530 deletions
+63 -42
View File
@@ -28,71 +28,92 @@
| [x] task C |
+-----------------------+
|
if rounds_since_todo >= 3:
inject <reminder> into tool_result
每次请求时通过 defaultSystem()
注入最新 todo 状态到系统提示
```
## 工作原理
1. TodoManager 存储带状态的项目。同一时间只允许一个 `in_progress`
```python
class TodoManager:
def update(self, items: list) -> str:
validated, in_progress_count = [], 0
for item in items:
status = item.get("status", "pending")
if status == "in_progress":
in_progress_count += 1
validated.append({"id": item["id"], "text": item["text"],
"status": status})
if in_progress_count > 1:
raise ValueError("Only one task can be in_progress")
self.items = validated
return self.render()
```
```java
public class TodoManager {
2. `todo` 工具和其他工具一样加入 dispatch map。
public record TodoItem(String id, String text, String status) {}
```python
TOOL_HANDLERS = {
# ...base tools...
"todo": lambda **kw: TODO.update(kw["items"]),
private List<TodoItem> items = new ArrayList<>();
@Tool(description = "Update the full task list to track progress. "
+ "Each item must have id, text, status (pending/in_progress/completed). "
+ "Only one task can be in_progress at a time. Max 20 items.")
public String updateTodos(
@ToolParam(description = "The complete list of todo items")
List<TodoItem> items) {
if (items.size() > 20) return "Error: Max 20 todos allowed";
List<TodoItem> validated = new ArrayList<>();
int inProgressCount = 0;
for (TodoItem item : items) {
String status = (item.status() != null)
? item.status().toLowerCase() : "pending";
if ("in_progress".equals(status)) inProgressCount++;
validated.add(new TodoItem(item.id(), item.text().trim(), status));
}
if (inProgressCount > 1)
return "Error: Only one task can be in_progress at a time";
this.items = validated;
return render();
}
}
```
3. nag reminder: 模型连续 3 轮以上不调用 `todo` 时注入提醒
2. `TodoManager` 通过 `defaultTools()` 注册, `@Tool` 注解方法自动暴露为工具
```python
if rounds_since_todo >= 3 and messages:
last = messages[-1]
if last["role"] == "user" and isinstance(last.get("content"), list):
last["content"].insert(0, {
"type": "text",
"text": "<reminder>Update your todos.</reminder>",
})
```java
ChatClient chatClient = ChatClient.builder(chatModel)
.defaultSystem(system)
.defaultTools(
new BashTool(),
new ReadFileTool(),
new WriteFileTool(),
new EditFileTool(),
todoManager // @Tool 注解方法自动注册
)
.build();
```
"同时只能有一个 in_progress" 强制顺序聚焦。nag reminder 制造问责压力 -- 你不更新计划, 系统就追着你问
3. 系统提示注入: 每次用户输入时, 将最新 todo 状态注入系统提示, 并强调更新指令
```java
// 动态系统提示:包含当前 todo 状态
String system = "You are a coding agent at " + workDir + ".\n"
+ "Use the todo tool to plan multi-step tasks. "
+ "Mark in_progress before starting, completed when done.\n"
+ "IMPORTANT: You MUST call updateTodos regularly.\n\n"
+ "<current-todos>\n" + todoManager.render() + "\n</current-todos>";
```
"同时只能有一个 in_progress" 强制顺序聚焦。系统提示中持续注入 todo 状态制造问责压力 -- 模型每次都能看到自己的计划, 不会忘记更新。
> **TIP**: Python 版在工具循环内追踪 `rounds_since_todo`, 连续 3 轮未调用 todo 时注入 `<reminder>` 文本。Spring AI 的 ChatClient 自动管理工具循环, 无法在循环内注入, 因此改用系统提示注入的方式实现同等效果。
## 相对 s02 的变更
| 组件 | 之前 (s02) | 之后 (s03) |
|----------------|------------------|--------------------------------|
| Tools | 4 | 5 (+todo) |
| 规划 | 无 | 带状态的 TodoManager |
| Nag 注入 | 无 | 3 轮后注入 `<reminder>` |
| Agent loop | 简单分发 | + rounds_since_todo 计数器 |
| 组件 | 之前 (s02) | 之后 (s03) |
|----------------|------------------|--------------------------------------|
| Tools | 4 | 5 (+TodoManager `@Tool`) |
| 规划 | 无 | 带状态的 TodoManager |
| 状态注入 | 无 | 系统提示注入 `<current-todos>` |
| ChatClient | 固定系统提示 | 每轮重建, 动态注入 todo 状态 |
## 试一试
```sh
cd learn-claude-code
python agents/s03_todo_write.py
mvn exec:java -Dexec.mainClass=io.mybatis.learn.s03.S03TodoWrite
```
试试这些 prompt (英文 prompt 对 LLM 效果更好, 也可以用中文):
1. `Refactor the file hello.py: add type hints, docstrings, and a main guard`
2. `Create a Python package with __init__.py, utils.py, and tests/test_utils.py`
3. `Review all Python files and fix any style issues`
1. `Refactor the file Hello.java: add JavaDoc, improve naming, and keep main method behavior unchanged`
2. `Create a Java package with utils and tests`
3. `Review all Java files and fix any style issues`