spring ai alibaba 使用 SystemPromptTemplate 很方便的集成 系统提示词

系统提示词可以是.st 文件了,便于修改和维护

1提示词内容:

st 复制代码
你是一个有用的AI助手。
你是一个帮助人们查找信息的人工智能助手。
您的名字是{name}
你应该用你的名字和{voice}的风格回复用户的请求。
每一次回答的时候都要增加一个65字以内的标题形如:【这是标题】
然后在展开回答用户的问题

2赋值方式

java 复制代码
    @Value("classpath:/prompts/system-message.st")
    private Resource systemResource;
    @PostMapping(value = "/askQuestion" ,produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<String>> streamForSystemMessage(@RequestBody
      QuestionVO questionVO, HttpServletRequest request
    ) {
         String prompt=questionVO.getPrompt();
        String platform=questionVO.getPlatform();
           UserMessage userMessage = new UserMessage(prompt);
            SystemPromptTemplate systemPromptTemplate = new SystemPromptTemplate(systemResource);
            //这里是赋值 也可以从前端页面传递过来
            Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "张三", "voice", "鲁迅"));
            return  ChatClient.builder(dashScopeChatModel).build().prompt(new Prompt(List.of(userMessage,systemMessage))).stream().content()
                    .map(content -> {
                        stringBuffer.append(content);
                        System.out.println(stringBuffer.toString());
                        JSONObject  jsonObject=new  JSONObject();
                        jsonObject.put("content",content);
                        String jobject=jsonObject.toString();
                        return ServerSentEvent.builder(jobject).event("message").build();
                    })
                    //问题回答结速标识,以便前端消息展示处理
                    .concatWithValues(ServerSentEvent.builder("[DONE]").build())
                    .onErrorResume(e -> Flux.just(ServerSentEvent.builder("Error: " +e.getMessage()).event("error").build()));
 }   

解释: Message systemMessage = systemPromptTemplate.createMessage(Map.of("name", "张三", "voice", "鲁迅")); 张三和 鲁迅都可以从页面传递过来

3 展示结果

4:ollama openAI qwen deepseek 等大模型都支持

5、总结

  1. 核心步骤

    • 使用 SystemPromptTemplate 直接加载 .st 模板文件。
  2. 优势

    • 代码简洁:无需手动解析模板,直接使用 Spring AI 提供的工具类。
    • 灵活性高:支持动态变量、条件逻辑和多模板管理。
    • 维护方便:模板与代码分离,修改提示词无需重新编译。
  3. 注意事项

    • 变量名需与模板中的占位符一致(如 {name} 对应 `Map.of("name", "张三", "voice", "鲁迅"))。

通过这种方式,可以高效地在 Spring AI 中集成各大模型,并实现高度可配置的系统提示词管理。

相关推荐
JAVA面经实录9175 小时前
Java初级最终完整版学习路线图
java·spring·eclipse·maven
释怀°Believe6 小时前
Spring解析
java·后端·spring
小新同学^O^7 小时前
简单学习 --> Spring事务
数据库·学习·spring
xuhaoyu_cpp_java8 小时前
SpringMVC学习(二)
java·经验分享·笔记·学习·spring
霸道流氓气质13 小时前
Spring AI 实战:Ollama 本地模型工具调用与 Prompt 模板全解析
人工智能·spring·prompt
YOU OU14 小时前
SpringBoot
java·spring boot·spring
凯瑟琳.奥古斯特14 小时前
SpringBoot快速入门指南
java·开发语言·spring boot·后端·spring
咖啡八杯15 小时前
GoF设计模式——抽象工厂模式
java·后端·spring·设计模式·抽象工厂模式
Ting-yu15 小时前
SpringCloud快速入门(1)---- 微服务介绍
后端·spring·spring cloud
庞轩px16 小时前
第八篇:Spring与微服务——从SpringBoot到SpringCloud的演进
spring boot·spring·微服务·nacos·gateway·sentinel