Spring Ai超简单教程系列 - 03提示词

在网上找了一些Spring AI相关的教程,因为官方API更新较快的原因,大部分教程的内容都已过时。所以在参照官方参考文档学习的同时,沉淀每篇文章,为同样热爱学习的你,提供参考。
本系列教程参考Spring AI官方1.1.x版本文档:https://docs.spring.io/spring-ai/reference/1.1/index.html

提示词

在Spring AI中,提示词(Prompt)是引导AI模型生成特定输出的输入,其设计与措辞显著影响模型响应。
在最底层交互上,Spring AI处理提示词的方式类似Spring MVC中的“视图”,即创建含占位符的大段文本,后续根据用户请求或代码动态替换。另一类比是含占位符的SQL语句。
随着Spring AI发展,它将引入更高级的抽象。基础类(如ChatModel)类似JDK中的JDBC核心,而ChatClient类似JdbcClient,它在ChatModel之上构建,并通过Advisor提供更高级功能(如结合历史交互、增强上下文文档、引入代理行为)。

提示词模版

在AI应用开发中,会在提示词中设置占位符,通过业务参数传递的方式填充到提示词中。

@GetMapping("/ai/prompt/template")
public String promptTemplate(@RequestParam("book") String book) {
    PromptTemplate template = new PromptTemplate("{book}的作者是谁?");
    Prompt prompt = template.create(Map.of("book", book));
    return this.chatModel.call(prompt).getResult().getOutput().getText();
}
调用示例

image

系统提示词

通过系统提示词,构建带有系统角色的消息,将用户角色的消息与系统角色的消息合并,形成最终的Prompt。该Prompt再传递给 ChatModel,以获取生成式响应。

@GetMapping("/ai/prompt/system")
public String systemPrompt(@RequestParam("book") String book) {
    String systemPromptText = """
        你是一个AI助手,你的名字叫{name},每次回答问题时,你应该以{name}的名义回答。
        如果用户问书籍的作者,你只回答中国四大名著内的作者,其它书籍直接回复你不知道请自行查阅资料"
        """;
    SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemPromptText);
    Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "Codest"));

    String userPromptText = """
            {book}的作者是谁?
            """;
    PromptTemplate userPromptTemplate = new PromptTemplate(userPromptText);
    Message userMessage = userPromptTemplate.createMessage(Map.of("book", book));

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

    return this.chatModel.call(prompt).getResult().getOutput().getText();
}
调用示例1

image

调用示例2

image

自定义提示词模版渲染器

可以通过实现TemplateRenderer接口并将其传递给PromptTemplate构造器来使用自定义模板渲染器。也可以继续使用默认的StTemplateRenderer并使用自定义配置。

例如,默认情况下,模板变量使用{}语法标识。但是在提示词中包JSON格式内容,为了避免与JSON语法冲突,需要改用其他分隔符,例如<>

@GetMapping("/ai/prompt/renderer")
public String templateRenderer(@RequestParam("book") String book) {
    PromptTemplate template = PromptTemplate.builder()
            .renderer(StTemplateRenderer.builder().startDelimiterToken('<').endDelimiterToken('>').build())
            .template("<book>的作者是谁?")
            .build();

    Prompt prompt = template.create(Map.of("book", book));

    return this.chatModel.call(prompt).getResult().getOutput().getText();
}
调用示例

image

posted @ 2026-09-02 18:03  codest  阅读(3)  评论(0)    收藏  举报