7 高级技术
引言
高级提示工程将 AI 从简单的工具转变为复杂的推理伙伴。这些技术利用模型的元认知能力——它能够反思、评估和改进自身输出的能力。研究表明,与基本提示相比,高级提示技术在复杂推理任务中可以提升 20-40% 的性能(Zhou 等人,2024)。
本章涵盖了来自最新研究的经过验证的高级技术,并为生产系统提供实用的 Spring AI 实现。
┌─────────────────────────────────────────────────────────────────────────┐
│ 高级技术分类法 │
├─────────────────────────────────────────────────────────────────────────│
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 自我改进 │ │ 多步 │ │ 推理 │ │
│ │ 技术 │ │ 编排 │ │ 增强 │ │
│ ├─────────────────┤ ├─────────────────┤ ├─────────────────┤ │
│ │ • 自我批判 │ │ • 提示链 │ │ • 步退 │ │
│ │ • 反思 │ │ • 多轮 │ │ • 自洽 │ │
│ │ • 智能体-评论者 │ │ • 分解 │ │ • ToT/GoT/AoT │ │
│ │ • PACE │ │ • 聚合 │ │ • PAL │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ 元级 │ │ 输出控制 │ │ 新兴 │ │
│ │ 提示 │ │ 技术 │ │ 技术 │ │
│ ├─────────────────┤ ├─────────────────┤ ├─────────────────┤ │
│ │ • DSPy │ │ • 定向 │ │ • 情感提示 │ │
│ │ • OPRO │ │ • 对比 │ │ • RaR │ │
│ │ • 自动提示 │ │ • 框架 │ │ • 思维线 │ │
│ │ • PE2 │ │ • 操控 │ │ • 再阅读 │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
信息
性能基准: 自我批判在复杂推理任务中提高准确性 20-30%,自洽性提高 15-25%,步退提示提高 10-20%(Li 等人,2024)。
1. 自我批判与反思
自我批判使模型能够通过 结构化内省来评估和改进自身输出。反思框架(Shinn 等人,2023)将此形式化为迭代改进循环。
1.1 反思框架
反思通过跨尝试的记忆和持续学习扩展了简单的自我批判:
┌─────────────────────────────────────────────────────────────────────────┐
│ 反思架构 │
├─────────────────────────────────────────────────────────────────────────│
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 智能 │───────▶│ 评估器 │───────▶│ 反思 │ │
│ │ 体 (LLM) │ │ (LLM/代码) │ │ 历史 │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │ │ │
│ │ │ │
│ ▼ │ │
│ ┌─────────────┐ │ │
│ │ 响应 │ │ │
│ └─────────────┘ │ │
│ │ │ │
│ │ ┌─ ────────────────────────────────────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 记忆 (反思历史) │ │
│ │ "在尝试 1 中,我犯了错误 X。对于尝试 2, │ │
│ │ 我应该关注 Y 而不是 Z。" │ │
│ └─────────────────────────────────────────────────────┘ │
│ │ │
│ │ 输入下一次尝试 │
│ ▼ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 改进的智能体尝试 │ │
│ └─────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────┘
1.2 基础自我批判模式
在单个提示中最简单的自我批判形式:
public class SelfCritiqueService {
private final ChatClient chatClient;
private static final String SELF_CRITIQUE_TEMPLATE = """
<task>
使用自我批判解决以下问题。
</task>
<problem>
{problem}
</problem>
<process>
## 第一阶段:初始解决方案
生成你的第一个解决方案尝试。
## 第二阶段:批判分析
根据以下标准评估你的解决方案:
1. **正确性**:是否存在任何逻辑或事实错误?
2. **完整性**:是否遗漏了应该包含的内容?
3. **清晰度**:任何部分是否可以更清楚地解释?
4. **效率**:是否有更好的方法?
5. **边界情况**:是否考虑了边界条件?
## 第三阶段:改进的解决方案
根据你的批判,生成一个改进的解决方案。
明确解决每个识别出的问题。
## 第四阶段:验证
验证改进后的解决方案确实解决了问题。
</process>
<output_format>
### 初始解决方案
[你的第一次尝试]
### 批判
| 标准 | 发现的问题 | 严重程度 |
|-----------|-------------|----------|
| ... | ... | 高/中/低 |
### 改进的解决方案
[解决所有问题的改进方案]
### 验证
[问题已解决的确认]
</output_format>
""";
public String solveWithSelfCritique(String problem) {
return chatClient.prompt()
.user(u -> u.text(SELF_CRITIQUE_TEMPLATE)
.param("problem", problem))
.call()
.content();
}
}
1.3 多轮反思与记忆
对于复杂任务,实现带有持久记忆的迭代反思:
@Service
public class ReflexionService {
private final ChatClient chatClient;
private static final int MAX_ITERATIONS = 5;
private static final double SATISFACTION_THRESHOLD = 0.85;
public record ReflexionResult(
String finalAnswer,
List<ReflectionEntry> reflectionHistory,
int iterations,
double confidenceScore
) {}
public record ReflectionEntry(
int attempt,
String response,
String evaluation,
String reflection,
double score
) {}
public ReflexionResult solveWithReflexion(String problem) {
List<ReflectionEntry> history = new ArrayList<>();
String currentResponse = null;
for (int i = 0; i < MAX_ITERATIONS; i++) {
// 第 1 步:生成响应(智能体)
currentResponse = generateResponse(problem, history);
// 第 2 步:评估响应
EvaluationResult evaluation = evaluateResponse(problem, currentResponse);
// 第 3 步:检查是否令人满意
if (evaluation.score() >= SATISFACTION_THRESHOLD) {
history.add(new ReflectionEntry(
i + 1, currentResponse, evaluation.feedback(),
"解决方案被接受", evaluation.score()
));
return new ReflexionResult(currentResponse, history, i + 1, evaluation.score());
}
// 第 4 步:为下一次尝试生成反思
String reflection = generateReflection(problem, currentResponse, evaluation);
history.add(new ReflectionEntry(
i + 1, currentResponse, evaluation.feedback(),
reflection, evaluation.score()
));
}
return new ReflexionResult(currentResponse, history, MAX_ITERATIONS,
evaluateResponse(problem, currentResponse).score());
}
private String generateResponse(String problem, List<ReflectionEntry> history) {
String historyContext = formatReflectionHistory(history);
String prompt = """
<problem>
{problem}
</problem>
<previous_attempts>
{history}
</previous_attempts>
<instruction>
基于先前尝试的反思,生成改进的解决方案。
避免重复反思历史中识别出的相同错误。
</instruction>
""";
return chatClient.prompt()
.user(u -> u.text(prompt)
.param("problem", problem)
.param("history", historyContext.isEmpty() ? "没有先前尝试。" : historyContext))
.call()
.content();
}
private String generateReflection(String problem, String response, EvaluationResult eval) {
String prompt = """
<task>生成反思以改进下一次尝试</task>
<problem>{problem}</problem>
<response>{response}</response>
<evaluation>{evaluation}</evaluation>
<instruction>
分析出了什么错误并为下一次尝试提供具体、可行的指导。
关注:
1. 具体犯了什么错误
2. 为什么发生这些错误
3. 下次应该做什么不同的事情
4. 应该从这次尝试中保留什么
</instruction>
<format>
提供一个简洁的反思(2-3句话),将直接改进下一次尝试。
</format>
""";
return chatClient.prompt()
.user(u -> u.text(prompt)
.param("problem", problem)
.param("response", response)
.param("evaluation", eval.feedback()))
.call()
.content();
}
private String formatReflectionHistory(List<ReflectionEntry> history) {
return history.stream()
.map(e -> String.format("""
--- 尝试 %d (分数: %.2f) ---
响应摘要: %s
问题: %s
反思: %s
""", e.attempt(), e.score(),
truncate(e.response(), 200),
e.evaluation(),
e.reflection()))
.collect(Collectors.joining("\n"));
}
}
1.4 宪法式 AI 自我批判
受 Anthropic 宪法式 AI 启发,根据明确的原则评估响应:
public class ConstitutionalCritique {
private static final List<String> CONSTITUTION = List.of(
"响应必须准确且事实正确",
"响应必须有帮助并解决用户的实际需求",
"响应必须安全且不促进有害行为",
"响应必须诚实对待不确定性",
"响应必须简洁且结构良好"
);
private static final String CONSTITUTIONAL_TEMPLATE = """
<task>
根据宪法原则评估和修订响应。
</task>
<original_response>
{response}
</original_response>
<constitution>
{principles}
</constitution>
<process>
对于每个原则:
1. 评估响应是否遵循它(是/否/部分)
2. 如果是"否"或"部分",识别具体违规
3. 建议具体的改进
然后提供一个完全遵循所有原则的修订响应。
</process>
<output_format>
## 宪法审查
| 原则 | 遵循程度 | 问题 | 改进 |
|-----------|-----------|--------|-------------|
| ... | ... | ... | ... |
## 修订响应
[遵循所有原则的改进响应]
</output_format>
""";
public String critiqueConstitutionally(String response) {
String principles = IntStream.range(0, CONSTITUTION.size())
.mapToObj(i -> (i + 1) + ". " + CONSTITUTION.get(i))
.collect(Collectors.joining("\n"));
return chatClient.prompt()
.user(u -> u.text(CONSTITUTIONAL_TEMPLATE)
.param("response", response)
.param("principles", principles))
.call()
.content();
}
}
2. 迭代求精模式
迭代求精通过多个结构化轮次改进输出,每轮针对特定方面。