Prompts 模板语法
上节我们介绍了提示词工程,并通过设定SystemMessage获得了一个会骂人的AI。而本节介绍的内容仍然与提示词有关。
Spring AI为我们提供了提示词模板,允许我们通过一些模板,快速地动态生成提示词并发起提问。除此之外,我们还能使用Spring AI为我们提供的输出解析器将AI回复的内容解析为Bean对象。
5.1 PromptTemplate
PromptTemplate
能够帮助我们创建结构化提示词,是Spring AI提示词工程中的关键组件,该类实现了三个接口:PromptTemplateStringActions
、PromptTemplateActions
和PromptTemplateMessageActions
,这些接口的主要功能也有所不同:
PromptTemplateStringActions
: 主要用于创建和渲染提示词字符串,接口的返回值类型均是String类型,这是提示词的基本形式。PromptTemplateActions
: 主要用于创建Prompt对象,该对象可直接传递给ChatClient以生成响应。PromptTemplateMessageActions
:主要用于创建Message对象,这允许我们针对Message对象进行其他的相关操作。
例如,我们想定义一个这样的提示词:提供作者姓名,返回该作者最受欢迎的书,出版时间和书的内容概述。
@GetMapping("/template")
public String promptTemplate(String author){
// 提示词
final String template = "请问{author}最受欢迎的书是哪本书?什么时候发布的?书的内容是什么?";
PromptTemplate promptTemplate = new PromptTemplate(template);
// 动态地将author填充进去
Prompt prompt = promptTemplate.create(Map.of("author", author));
ChatResponse chatResponse = chatClient.call(prompt);
AssistantMessage assistantMessage = chatResponse.getResult().getOutput();
return assistantMessage.getContent();
}
我们除了可以通过定义字符串加载Template以外,我们还可以以Resource的形式加载Template,例如,我们在resouces下创建prompt.st
(文件后缀名合理即可),将刚刚的提示词模板写入到该文件中。
package com.ningning0111.controller;
import org.springframework.ai.chat.ChatClient;
import org.springframework.ai.chat.ChatResponse;
import org.springframework.ai.chat.messages.AssistantMessage;