Prompt 工程
大约 7 分钟
第九章:Prompt工程
9.1 Prompt设计原则
Prompt设计是AI应用成功的关键,良好的Prompt设计能够显著提高AI模型的输出质量。
9.1.1 清晰明确
// 不好的Prompt
String badPrompt = "Tell me about Spring AI";
// 好的Prompt
String goodPrompt = "Explain Spring AI framework to a beginner developer, including its main features, benefits, and how to get started with a simple code example.";9.1.2 具体详细
// 不好的Prompt
String vaguePrompt = "Write a blog post";
// 好的Prompt
String specificPrompt = "Write a 500-word blog post about Spring AI for Java developers, including code examples and best practices. The tone should be professional but accessible.";9.1.3 上下文丰富
// 缺乏上下文的Prompt
String noContextPrompt = "What is the best way to handle errors?";
// 有上下文的Prompt
String withContextPrompt = "In a Spring AI application, what are the best practices for handling API errors from AI services? Consider retry mechanisms, fallback strategies, and user experience.";9.1.4 角色设定
// 无角色的Prompt
String noRolePrompt = "Explain Spring Boot features";
// 有角色的Prompt
String withRolePrompt = "As a senior Spring developer with 10 years of experience, explain the key features of Spring Boot 3.x and how they improve developer productivity.";9.2 Prompt模板
Spring AI提供了强大的Prompt模板系统,支持动态Prompt生成。
9.2.1 基础Prompt模板
@RestController
public class PromptTemplateController {
private final ChatClient chatClient;
public PromptTemplateController(ChatClient chatClient) {
this.chatClient = chatClient;
}
@GetMapping("/prompt/template")
public String useTemplate(@RequestParam String topic) {
PromptTemplate promptTemplate = new PromptTemplate(
"Tell me about {topic} in 100 words"
);
Prompt prompt = promptTemplate.create(Map.of("topic", topic));
return chatClient.prompt(prompt).call().content();
}
}9.2.2 复杂Prompt模板
@GetMapping("/prompt/complex-template")
public String useComplexTemplate(
@RequestParam String name,
@RequestParam String role,
@RequestParam String question) {
PromptTemplate promptTemplate = new PromptTemplate(
"""
You are {role}.
User: {name} asks: {question}
Please provide a detailed answer with examples.
"""
);
Prompt prompt = promptTemplate.create(
Map.of("role", role, "name", name, "question", question)
);
return chatClient.prompt(prompt).call().content();
}9.2.3 条件Prompt模板
@GetMapping("/prompt/conditional-template")
public String useConditionalTemplate(
@RequestParam String language,
@RequestParam String code) {
PromptTemplate promptTemplate = new PromptTemplate(
"""
Convert the following {language} code to Java:
{code}
"""
);
Prompt prompt = promptTemplate.create(
Map.of("language", language, "code", code)
);
return chatClient.prompt(prompt).call().content();
}9.2.4 多语言Prompt模板
@GetMapping("/prompt/multi-language")
public Map<String, String> generateMultiLanguagePrompts(
@RequestParam String basePrompt,
@RequestParam List<String> languages) {
Map<String, String> prompts = new HashMap<>();
for (String language : languages) {
PromptTemplate template = new PromptTemplate(
"Translate the following to " + language + ":\n\n" + basePrompt
);
Prompt prompt = template.create(Map.of());
prompts.put(language, chatClient.prompt(prompt).call().content());
}
return prompts;
}9.3 Prompt优化技巧
9.3.1 分步思考(Chain of Thought)
@GetMapping("/prompt/chain-of-thought")
public String useChainOfThought(@RequestParam String complexProblem) {
String prompt = """
Let's solve this problem step by step:
Problem: {problem}
Step 1: Understand the problem
Step 2: Identify key components
Step 3: Develop a solution approach
Step 4: Implement the solution
Step 5: Verify the result
Now, let's apply this to: {problem}
""".replace("{problem}", complexProblem);
return chatClient.prompt(prompt).call().content();
}9.3.2 自我纠正
@GetMapping("/prompt/self-correction")
public String useSelfCorrection(@RequestParam String task) {
String prompt = """
Task: {task}
First, provide an initial solution.
Then, critically evaluate your solution for potential issues.
Finally, improve the solution based on your evaluation.
Now, let's apply this to: {task}
""".replace("{task}", task);
return chatClient.prompt(prompt).call().content();
}9.3.3 示例驱动
@GetMapping("/prompt/example-driven")
public String useExampleDriven(@RequestParam String concept) {
String prompt = """
Explain the concept of {concept} with the following examples:
Example 1: Simple case
Example 2: Edge case
Example 3: Complex case
Now, let's apply this to: {concept}
""".replace("{concept}", concept);
return chatClient.prompt(prompt).call().content();
}9.3.4 限制和约束
@GetMapping("/prompt/constraints")
public String useConstraints(@RequestParam String task) {
String prompt = """
Task: {task}
Constraints:
- Output must be under 200 words
- Use simple language
- Include code examples
- Focus on practical applications
Now, let's apply this to: {task}
""".replace("{task}", task);
return chatClient.prompt(prompt).call().content();
}9.4 动态Prompt生成
9.4.1 基于上下文的Prompt生成
@Service
public class DynamicPromptService {
private final ChatClient chatClient;
public DynamicPromptService(ChatClient chatClient) {
this.chatClient = chatClient;
}
public String generateDynamicPrompt(
String userContext,
String task,
Map<String, Object> constraints) {
StringBuilder prompt = new StringBuilder();
prompt.append("User context: ").append(userContext).append("\n\n");
prompt.append("Task: ").append(task).append("\n\n");
if (!constraints.isEmpty()) {
prompt.append("Constraints:\n");
for (Map.Entry<String, Object> entry : constraints.entrySet()) {
prompt.append("- ").append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
}
}
return chatClient.prompt(prompt.toString()).call().content();
}
}9.4.2 基于历史的Prompt生成
@Service
public class HistoricalPromptService {
private final ChatClient chatClient;
public HistoricalPromptService(ChatClient chatClient) {
this.chatClient = chatClient;
}
public String generateHistoricalPrompt(
List<String> conversationHistory,
String currentMessage) {
StringBuilder prompt = new StringBuilder();
prompt.append("Conversation history:\n");
for (String message : conversationHistory) {
prompt.append("- ").append(message).append("\n");
}
prompt.append("\nCurrent message: ").append(currentMessage);
return chatClient.prompt(prompt.toString()).call().content();
}
}9.4.3 基于用户偏好的Prompt生成
@Service
public class PersonalizedPromptService {
private final ChatClient chatClient;
public PersonalizedPromptService(ChatClient chatClient) {
this.chatClient = chatClient;
}
public String generatePersonalizedPrompt(
UserPreferences preferences,
String task) {
String prompt = "User preferences: " + preferences + "\n\n" +
"Task: " + task;
return chatClient.prompt(prompt).call().content();
}
}
public class UserPreferences {
private String language;
private String tone;
private List<String> interests;
// getters and setters
}9.5 Prompt测试与评估
9.5.1 Prompt测试框架
public class PromptTester {
private final ChatClient chatClient;
public PromptTester(ChatClient chatClient) {
this.chatClient = chatClient;
}
public PromptTestResult testPrompt(String prompt, String expectedOutput) {
String actualOutput = chatClient.prompt(prompt).call().content();
double similarity = calculateSimilarity(expectedOutput, actualOutput);
boolean passed = similarity > 0.8; // 阈值
return new PromptTestResult(prompt, actualOutput, similarity, passed);
}
private double calculateSimilarity(String expected, String actual) {
// 实现相似度计算
return 0.9;
}
}
public class PromptTestResult {
private String prompt;
private String actualOutput;
private double similarity;
private boolean passed;
// getters and setters
}9.5.2 Prompt优化循环
public class PromptOptimizer {
private final ChatClient chatClient;
private final PromptTester promptTester;
public PromptOptimizer(ChatClient chatClient, PromptTester promptTester) {
this.chatClient = chatClient;
this.promptTester = promptTester;
}
public String optimizePrompt(String initialPrompt, String expectedOutput) {
String currentPrompt = initialPrompt;
double bestSimilarity = 0;
for (int i = 0; i < 5; i++) { // 最多优化5次
PromptTestResult result = promptTester.testPrompt(currentPrompt, expectedOutput);
if (result.getSimilarity() > bestSimilarity) {
bestSimilarity = result.getSimilarity();
currentPrompt = refinePrompt(currentPrompt, result);
}
}
return currentPrompt;
}
private String refinePrompt(String prompt, PromptTestResult result) {
// 基于测试结果优化Prompt
return prompt + " (optimized)";
}
}9.6 实际应用示例
9.6.1 代码生成Prompt优化
@Service
public class CodePromptOptimizer {
private final ChatClient chatClient;
public CodePromptOptimizer(ChatClient chatClient) {
this.chatClient = chatClient;
}
public String optimizeCodePrompt(
String requirement,
String language,
CodeStylePreferences preferences) {
String basePrompt = "Generate " + language + " code for: " + requirement;
// 添加风格偏好
String styledPrompt = basePrompt + "\nStyle: " + preferences.getStyle();
// 添加最佳实践
String optimizedPrompt = styledPrompt + "\nFollow best practices and include comments.";
return optimizedPrompt;
}
}
public class CodeStylePreferences {
private String style;
private boolean includeComments;
private boolean followBestPractices;
// getters and setters
}9.6.2 内容生成Prompt优化
@Service
public class ContentPromptOptimizer {
private final ChatClient chatClient;
public ContentPromptOptimizer(ChatClient chatClient) {
this.chatClient = chatClient;
}
public String optimizeContentPrompt(
String topic,
ContentPreferences preferences) {
String prompt = "Write content about " + topic;
if (preferences.isIncludeExamples()) {
prompt += " with examples";
}
if (preferences.isIncludeStatistics()) {
prompt += " including relevant statistics";
}
if (preferences.isIncludeReferences()) {
prompt += " and references";
}
return prompt;
}
}
public class ContentPreferences {
private boolean includeExamples;
private boolean includeStatistics;
private boolean includeReferences;
// getters and setters
}9.7 性能优化
9.7.1 Prompt缓存
@Configuration
@EnableCaching
public class PromptCacheConfig {
@Bean
public CacheManager cacheManager() {
SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(
new ConcurrentMapCache("optimized-prompts"),
new ConcurrentMapCache("prompt-results")
));
return cacheManager;
}
}9.7.2 Prompt预编译
@Service
public class PrecompiledPromptService {
private final Map<String, Prompt> precompiledPrompts = new ConcurrentHashMap<>();
public Prompt getPrecompiledPrompt(String key) {
return precompiledPrompts.computeIfAbsent(key, this::compilePrompt);
}
private Prompt compilePrompt(String key) {
// 预编译Prompt逻辑
return new Prompt("Precompiled prompt content");
}
}9.8 错误处理
9.8.1 Prompt验证
@Service
public class PromptValidator {
public boolean isValidPrompt(String prompt) {
// 检查Prompt是否有效
return prompt != null && !prompt.trim().isEmpty();
}
public List<String> validatePrompt(String prompt) {
List<String> issues = new ArrayList<>();
if (prompt == null || prompt.trim().isEmpty()) {
issues.add("Prompt cannot be empty");
}
if (prompt.length() > 4000) {
issues.add("Prompt is too long");
}
return issues;
}
}9.8.2 Prompt失败处理
@Service
public class PromptFallbackService {
private final ChatClient chatClient;
public PromptFallbackService(ChatClient chatClient) {
this.chatClient = chatClient;
}
public String handlePromptFailure(String prompt) {
try {
return chatClient.prompt(prompt).call().content();
} catch (Exception ex) {
// 使用备用Prompt
String fallbackPrompt = createFallbackPrompt(prompt);
return chatClient.prompt(fallbackPrompt).call().content();
}
}
private String createFallbackPrompt(String originalPrompt) {
// 创建备用Prompt
return "Simple version: " + originalPrompt;
}
}9.9 监控与日志
9.9.1 Prompt性能监控
@RestController
public class PromptMetricsController {
private final MeterRegistry meterRegistry;
public PromptMetricsController(MeterRegistry meterRegistry) {
this.meterRegistry = meterRegistry;
}
@GetMapping("/prompt/metrics")
public Map<String, Object> getMetrics() {
return Map.of(
"totalPrompts", meterRegistry.counter("prompt.total").count(),
"averageProcessingTime", meterRegistry.timer("prompt.duration").mean(),
"optimizationRate", meterRegistry.counter("prompt.optimizations").count() /
(meterRegistry.counter("prompt.total").count() + 1.0)
);
}
}9.9.2 Prompt日志记录
@Configuration
public class PromptLogging {
@Bean
public ChatClient loggingChatClient(ChatClient chatClient) {
return new ChatClient() {
@Override
public ChatResponse call(Prompt prompt) {
long startTime = System.currentTimeMillis();
try {
ChatResponse response = chatClient.call(prompt);
long duration = System.currentTimeMillis() - startTime;
log.info("Prompt处理 - 耗时: {}ms, Prompt: {}", duration, prompt);
return response;
} catch (Exception ex) {
log.error("Prompt处理失败", ex);
throw ex;
}
}
// 实现其他方法...
};
}
}9.10 小结
本章详细介绍了Prompt工程的高级技术:
- 设计原则:掌握清晰、具体、上下文丰富、角色设定等原则
- Prompt模板:学习基础和复杂Prompt模板的使用
- 优化技巧:了解分步思考、自我纠正、示例驱动等技巧
- 动态生成:掌握基于上下文、历史和用户偏好的Prompt生成
- 测试评估:学习Prompt测试框架和优化循环
- 实际应用:了解代码生成和内容生成的Prompt优化
- 性能优化:掌握Prompt缓存和预编译
- 错误处理:了解Prompt验证和失败处理
- 监控日志:掌握Prompt性能监控和日志记录
在下一章中,我们将学习函数调用与工具集成的技术。 点击这里👇🏻获取:100万QPS短链系统、复杂的商城微服务系统、智能翻译助手AI Agent、SaaS点餐系统、刷题吧小程序、商城系统、秒杀系统、AI项目、代码生成神器、苏三demo项目、智能天气播报AI Agent、智能代码审查AI Agent等 10 个项目的:项目源代码、开发教程和技术答疑
