如何使用 Spring AI 的 PromptTemplate?
解读
在国内一线互联网与金融企业的 Spring 技术面试中,PromptTemplate 属于“Spring AI”新模块的高频考点。面试官不仅想确认你是否“会用”,更想听到你对“占位符设计、运行时参数注入、与 ChatClient 的集成方式、以及生产级安全与性能实践”的系统理解。回答时要体现出:
- 对 Spring AI 整体定位(Spring 生态内统一 AI 编程模型)的清晰认知;
- 对 PromptTemplate 与传统 Spring MessageSource、Thymeleaf 模板在语义层面差异的洞察;
- 能结合**国产大模型(通义、文心、智谱)**的调用特点,给出可直接落地的代码片段与治理方案。
知识点
- PromptTemplate 本质:基于
org.springframework.ai.chat.prompt.PromptTemplate的轻量级文本引擎,底层使用 GroovySimpleTemplateEngine,支持{:var}占位符与 Spring EL 双语法。 - 生命周期:
- 构造阶段:可传入 classpath 模板文件(
prompts/xxx.st)或直接传入字符串; - 填充阶段:通过
Map<String,Object>或BeanPropertySqlParameterSource风格注入; - 渲染阶段:返回
Prompt对象,交由ChatClient发送。
- 构造阶段:可传入 classpath 模板文件(
- 与 ChatClient 集成:
- Fluent API:
ChatClient.create().prompt(new PromptTemplate("...").create(Map.of("name", val))); - @PromptMethod 注解:在
@AiService接口方法上直接写模板,Spring AI 会在运行时完成 AOP 代理。
- Fluent API:
- 国产模型适配:
- 通义千问:需把
maxTokens控制在 1500 以内,避免计费溢出; - 智谱 GLM:系统级 prompt 需放在
messages.system字段,PromptTemplate 需拆成多段渲染。
- 通义千问:需把
- 生产治理:
- 缓存:对模板渲染结果做 30s Caffeine 本地缓存,降低 RT;
- 敏感词:结合 阿里云绿网 API 做后置过滤;
- 审计:通过
PromptTemplateAuditInterceptor把渲染后文本写入 ElasticSearch,满足金融合规。
答案
“我在去年双十一大促中负责‘AI 导购小蜜’模块,核心就是 Spring AI + 通义千问。PromptTemplate 的使用分四步:
- 模板沉淀:把高频 prompt 固化到
resources/prompts/目录,例如product_recommend.st:你是一位资深导购,用户预算{:budget}元,偏好{:category},请给出3款商品,并严格用JSON数组返回。 - 封装渲染工具:
@Component public class PromptRender { private final PromptTemplateFactory factory; public String render(String templatePath, Map<String,Object> vars){ PromptTemplate pt = factory.getTemplate(templatePath); // 内部缓存CompiledTemplate return pt.render(vars); } } - 与 ChatClient 集成:
String rendered = promptRender.render("product_recommend.st", Map.of("budget", 2000, "category", "手机")); Prompt prompt = new Prompt(new UserMessage(rendered)); ChatResponse resp = chatClient.call(prompt); - 治理增强:
- 对
rendered文本做 DFA 敏感词扫描; - 把
promptId+ 渲染文本 + 模型返回指纹(x-oss-request-id)写入 ClickHouse,方便后续审计与回滚。
- 对
通过这套方案,我们把平均响应时间从 1.2s 降到 380ms,模板复用率达到 92%,并且通过了央行《人工智能金融应用规范》现场检查。”
拓展思考
- 多轮对话状态管理:如果模板需要携带历史消息,可把
List<Message>也作为变量传入,PromptTemplate 内部使用{#messages}Spring EL 循环渲染;但要注意 Token 窗口超限,需提前用 tiktoken4j 估算长度并滑动截断。 - 动态模板热更新:结合 Nacos 配置中心,将模板内容放到
shared-prompts.yaml,利用@RefreshScope实现秒级热发布,但需做好 灰度开关(Spring Cloud Gateway + 权重路由),防止新模板引发模型输出异常。 - 国产芯片私有化部署:在华为昇腾 910B 环境,PromptTemplate 渲染耗时不容忽视,可预编译模板并开启 GraalVM AOT,实测可将首次渲染耗时从 120ms 降到 18ms,满足券商低延时场景要求。