Skip to content

提示语 Prompt 与模板 PromptTemplate

SpringAI 统一门面接口 ChatClient 中介绍了使用提示语的三个方法。

java
ChatClientRequestSpec prompt();
ChatClientRequestSpec prompt(String content);
ChatClientRequestSpec prompt(Prompt prompt);

其中第三个是最通用的方式,本章核心介绍 Prompt 的创建方式。

Prompt 类定义

java
public class Prompt implements ModelRequest<List<Message>> {
    /**
     * The messages to be sent to the model.
     * 请求内容
     */
    private final List<Message> messages;

    /**
     * The options to be used when calling the model.
     * 动态传入模型参数
     */
    @Nullable
    private ChatOptions chatOptions;
}

public interface Content {
    /**
     * 消息内容
     */
    String getText();
    /**
     * 消息元数据
     */
    Map<String, Object> getMetadata();
}

public interface Message extends Content {
	/**
	 * 消息类型
	 */
	MessageType getMessageType();
}

public enum MessageType {
	/**
	 * system 系统消息
	 */
	SYSTEM("system"),
	/**
	 * user 用户消息
	 */
	USER("user"),
	/**
	 * 助手消息
	 */
	ASSISTANT("assistant"),
	/**
	 * 工具响应消息
	 */
	TOOL("tool");
}

四种 MessageType

  • System Role: 通常用于设置人设
  • User Role: 用户输入
  • Assistant Role: AI 对于用户输入的响应,有时会作为下一轮输入的补充一起发送给大模型,联通整体流程
  • Tool Role: 工具返回的信息

使用 Message 和 PromptTemplate 构建提示语

java
@RequestMapping("/33")
public String execute33() {
    /*
     * 通过提示语模板创建系统消息
     */
    SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate("请以{person}的风格回复问题");
    Message systemMessage = systemPromptTemplate.createMessage(Map.of("person", "王家卫"));

    /*
     * 创建用户消息
     */
    UserMessage userMessage = new UserMessage("描述一下今天天很热这个场景");

    /*
     * 创建提示语
     */
    Prompt prompt = Prompt.builder()
            .messages(List.of(systemMessage, userMessage)) // 设置消息
            .chatOptions(new DefaultChatOptionsBuilder().temperature(0.9).build()) // 设置模型参数
            .build();

    /*
     * 调用
     */
    return chatClient.prompt(prompt).call().content();
}

说明:

  • 提示语模板是通过 TemplateRenderer 来渲染参数的,自定义渲染器和定制渲染器占位符的方式已经在 SpringAI 统一门面接口 ChatClient 介绍过,此处不再赘述。
  • chatOptions 用来在运行时设置模型参数,覆盖应用启动时的全局默认参数

使用 Resource 构建提示语模板

在 resource 目录下新建 prompts/system.st 文件,st 文件代表 StringTemplate 格式文件(StringTemplateSpringAI 默认使用的模板引擎),内容如下:

text
请以{person}的风格回复问题
java
@Value("classpath:/prompts/system.st")
private org.springframework.core.io.Resource systemResource;

@RequestMapping("/34")
public SystemPromptTemplate execute34() {
    /*
     * 通过 Reource 创建提示语模板
     */
    return new SystemPromptTemplate(systemResource);
}

文章的最后,如果您觉得本文对您有用,请打赏一杯咖啡!感谢!