Skip to content

Spring AI 提示工程

提示工程(Prompt Engineering)是开发有效与AI模型交互的提示的艺术与科学。Spring AI提供了丰富的提示工程工具,使开发人员能够构建结构化、可重用的提示。本文将介绍Spring AI中的提示工程技术。

提示基础

在Spring AI中,提示是与AI模型交互的基本单位。最简单的提示可以是一个字符串:

java
Prompt simplePrompt = new Prompt("总结以下文本:{text}");

提示模板

Spring AI提供了模板系统,支持变量替换和条件逻辑:

java
PromptTemplate template = new PromptTemplate("""
    你是一位专业的{role}。
    请{action}以下{contentType}:
    {content}
    """);

Map<String, Object> variables = Map.of(
    "role", "内容编辑",
    "action", "总结",
    "contentType", "文章",
    "content", "春天来了,花儿开了..."
);

Prompt prompt = template.create(variables);

系统消息与用户消息

Spring AI支持创建包含不同角色消息的复杂提示:

java
SystemMessage systemMessage = new SystemMessage("""
    你是一位专业的技术文档作者,擅长将复杂概念简化为易于理解的解释。
    使用简洁、清晰的语言回答问题。
    """);

UserMessage userMessage = new UserMessage("解释Spring Framework中的依赖注入");

Prompt prompt = new Prompt(List.of(systemMessage, userMessage));

提示目录管理

对于大型应用,可以使用提示目录管理多个提示模板:

java
@Configuration
public class PromptConfig {
    
    @Bean
    public PromptTemplateRegistry promptTemplateRegistry() {
        ClassPathPromptTemplateRegistry registry = new ClassPathPromptTemplateRegistry();
        registry.addTemplate("summary", "请总结以下内容:{content}");
        registry.addTemplate("translation", "请将以下{sourceLanguage}文本翻译成{targetLanguage}:{content}");
        return registry;
    }
}

使用注册的模板:

java
@Service
public class ContentService {
    
    private final ChatClient chatClient;
    private final PromptTemplateRegistry promptRegistry;
    
    // 构造函数注入
    
    public String summarizeContent(String content) {
        PromptTemplate template = promptRegistry.getPromptTemplate("summary");
        Prompt prompt = template.create(Map.of("content", content));
        return chatClient.call(prompt).getResult().getOutput().getContent();
    }
}

从文件加载提示模板

Spring AI支持从外部文件加载提示模板:

# src/main/resources/prompts/article_writer.st
您是一位专业的{industry}内容创作者。
请根据以下主题创作一篇{wordCount}字的{articleType}:
主题: {topic}

要点包括:
{{#each keyPoints}}
- {{this}}
{{/each}}

目标受众: {audience}
语调: {tone}

从文件加载:

java
@Bean
public PromptTemplateRegistry filePromptRegistry() {
    ResourcePromptTemplateRegistry registry = new ResourcePromptTemplateRegistry();
    registry.addTemplate("article_writer", new ClassPathResource("prompts/article_writer.st"));
    return registry;
}

链式提示与对话管理

Spring AI支持构建链式提示,用于多轮对话或复杂任务:

java
@Service
public class ConversationService {
    
    private final ChatClient chatClient;
    
    public String conductInterview(String candidateName, String position) {
        List<Message> conversation = new ArrayList<>();
        
        // 系统指令
        conversation.add(new SystemMessage("你是一位人力资源专家,正在进行技术面试"));
        
        // 初始提示
        conversation.add(new UserMessage("你正在面试" + candidateName + ",应聘" + position + "职位"));
        ChatResponse response = chatClient.call(new Prompt(conversation));
        
        // 添加回复到对话
        conversation.add(new AiMessage(response.getResult().getOutput().getContent()));
        
        // 后续提示
        conversation.add(new UserMessage("请提出3个关于技术背景的问题"));
        response = chatClient.call(new Prompt(conversation));
        
        return response.getResult().getOutput().getContent();
    }
}

提示优化技术

思维链提示(Chain-of-Thought Prompting)

引导模型逐步思考:

java
PromptTemplate cot = new PromptTemplate("""
    问题: {question}
    
    请一步一步思考:
    1. 理解问题
    2. 确定解决方案
    3. 应用解决方案
    4. 验证结果
    
    详细解答:
    """);

少样本学习(Few-Shot Learning)

提供示例帮助模型理解任务:

java
PromptTemplate fewShot = new PromptTemplate("""
    将以下句子翻译成{targetLanguage}。
    
    例子:
    英文: The weather is nice today.
    中文: 今天天气很好。
    
    英文: I like to read books.
    中文: 我喜欢读书。
    
    英文: {inputText}
    {targetLanguage}:
    """);

提示评估与测试

Spring AI支持对提示进行评估和测试:

java
@Service
public class PromptTestingService {
    
    private final ChatClient chatClient;
    
    public void evaluatePromptVariations(String basePrompt, List<String> variations, String testInput) {
        List<String> results = new ArrayList<>();
        
        for (String variation : variations) {
            String fullPrompt = variation.replace("{input}", testInput);
            ChatResponse response = chatClient.call(new Prompt(fullPrompt));
            results.add(response.getResult().getOutput().getContent());
        }
        
        // 分析结果,比较不同变体的效果
    }
}

最佳实践

  1. 使用明确的指令:给模型提供清晰、具体的指导
  2. 分解复杂任务:将复杂任务分解为多个步骤
  3. 使用模板变量:使提示可重用和可配置
  4. 提供示例:使用少样本学习提高模型理解
  5. 指定输出格式:明确要求模型以特定格式返回结果
  6. 迭代改进:基于结果不断优化提示

总结

Spring AI的提示工程工具提供了强大的方式来创建、管理和优化与AI模型的交互。通过利用提示模板、变量替换、条件逻辑和对话管理等功能,开发人员可以构建复杂而有效的AI应用程序。良好的提示工程是获取高质量AI模型输出的关键,Spring AI提供了实现这一目标所需的工具。