spring-ai 第二提示词介绍

0 阅读1分钟

spring-ai 第二提示词介绍

提示词介绍

提示词(Prompt)是引导AI模型生成特定输出的输入 随着时间的推移,提示由只是简单的字符串发展为占位符

  • 入口链路

ChatModel -> call() -> Message

针对Message,角色分类如下

  • “USER:” 用户角色:代表用户输入一一他们的询问、指令或对AI的陈述

  • “ASSISTANT:” 助手角色:AI 对用户输入的回应,不仅仅是回答或反应,保持对话的连贯性至关重要

  • “SYSTEM:” 系统角色:指导AI的行为和响应风格,设定AI解释和回复输入的参数或规则

  • TOOL:” 工具/功能角色:工具/功能角色专注于在响应工具调用助手消息时返回附加信息

  • 整体结构图 Image text

提示模板

关键组件是PromptTemplate类,主要为了创建结构化的提示,将这些提示发送到AI模型进行处理

  • 通过StTemplateRenderer 进行渲染

demo(Prompt来构建SystemPromptTemplate实例)

String userText = """
    Tell me about three famous pirates from the Golden Age of Piracy and why they did.
    Write at least a sentence for each pirate.
    """;

Message userMessage = new UserMessage(userText);

String systemText = """
  You are a helpful AI assistant that helps people find information.
  Your name is {name}
  You should reply to the user's request with your name and also in the style of a {voice}.
  """;

SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemText);
Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", name, "voice", voice));

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

List<Generation> response = chatModel.call(prompt).getResults();

加载外部提示词模板

@Value("classpath:/prompts/system-message.st")
private Resource systemResource;

SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);

整体demo

源码

gitee.com/kcnf\_open/…

模型(智谱)

充值前 还得人脸识别(坑),随便一点充值

open.bigmodel.cn/

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-starter-model-zhipuai</artifactId>
</dependency>


# In application.yml
spring:
  ai:
    zhipuai:
      api-key: ${ZHIPUAI_API_KEY}

启动命令

Image text

测试结果

http://127.0.0.1:8082/ai/simple

Image text

http://127.0.0.1:8082/ai/prompt

Image text