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 中集成各大模型,并实现高度可配置的系统提示词管理。

相关推荐
用户8307196840822 天前
spring ai alibaba + nacos +mcp 实现mcp服务负载均衡调用实战
spring boot·spring·mcp
NE_STOP5 天前
springMVC-HTTP消息转换器与文件上传、下载、异常处理
spring
JavaGuide6 天前
Claude Opus 4.6 真的用不起了!我换成了国产 M2.5,实测真香!!
java·spring·ai·claude code
玹外之音6 天前
Spring AI MCP 实战:将你的服务升级为 AI 可调用的智能工具
spring·ai编程
来一斤小鲜肉6 天前
Spring AI入门:第一个AI应用跑起来
spring·ai编程
NE_STOP6 天前
springMVC-常见视图组件与RESTFul编程风格
spring
what丶k6 天前
Spring AI 多模态开发全解析:从入门到企业级落地
后端·spring·ai编程
NE_STOP7 天前
springMVC-获取前端请求的数据与三个作用域
spring
莫寒清7 天前
Spring MVC:@PathVariable 注解详解
java·spring·mvc