spring-ai-alibaba动态 Prompt 最佳实践

Spring AI Alibaba 使用 Nacos 的配置中心能力来动态管理 AI 应用的 Prompt。以此来实现动态更新 Prompt 的功能。

环境准备

Nacos: 具备配置中心能力的 Nacos,本例中使用 Nacos 3.0.2。Nacos 2.X 亦可,

spring-ai版本1.0.0 ,spring-ai-alibaba版本1.0.0.3 ,jdk17 

https://github.com/TalkIsCheapGiveMeMoney/spring-ai-alibaba-examples/tree/main/spring-ai-alibaba-nacos-prompt-exampleExample 工程地址:https://github.com/TalkIsCheapGiveMeMoney/spring-ai-alibaba-examples/tree/main/spring-ai-alibaba-nacos-prompt-example

Pom.xml

Tips: 项目中已经引入了 Spring AI Alibaba Bom 和 Spring Boot Bom。因此这里省略了版本号。有关 bom 定义参考如上的 Github 仓库地址。

 

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-dashscope</artifactId>
</dependency><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-nacos-prompt</artifactId>
</dependency>

Application.yml

在配置文件中加入 Nacos 监听的 DataID 以及 Nacos Server 的用户名和密码等信息。

# Copyright 2024-2025 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.server:port: 10010spring:application:name: spring-ai-alibaba-nacos-prompt-example# 指定监听的 prompt 配置config:import:- "optional:nacos:prompt-config.json"nacos:namespace: 8279be91-ac4e-465b-a87a-bbaa1fd66d26server-addr: 127.0.0.1:8848username: nacospassword: nacosai:# 开启 nacos 的 prompt tmpl 监听功能nacos:prompt:template:enabled: true

 Controller

/** Copyright 2024 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      https://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package com.alibaba.cloud.ai.example.nacos.controller;import java.util.Map;import com.alibaba.cloud.ai.prompt.ConfigurablePromptTemplate;
import com.alibaba.cloud.ai.prompt.ConfigurablePromptTemplateFactory;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import reactor.core.publisher.Flux;import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;/*** @author : huangzhen*/@RestController
@RequestMapping("/nacos")
public class PromptController {private static final Logger logger = org.slf4j.LoggerFactory.getLogger(PromptController.class);private final ChatClient client;private final ConfigurablePromptTemplateFactory promptTemplateFactory;public PromptController(ChatModel chatModel,ConfigurablePromptTemplateFactory promptTemplateFactory) {this.client = ChatClient.builder(chatModel).build();this.promptTemplateFactory = promptTemplateFactory;}@GetMapping("/books")public Flux<String> generateJoke(@RequestParam(value = "author", required = false, defaultValue = "鲁迅") String authorName,HttpServletResponse response) {// 防止输出乱码response.setCharacterEncoding("UTF-8");// 使用 nacos 的 prompt tmpl 创建 promptConfigurablePromptTemplate template = promptTemplateFactory.create("author","please list the three most famous books by this {author}.");Prompt prompt = template.create(Map.of("author", authorName));logger.info("最终构建的 prompt 为:{}", prompt.getContents());return client.prompt(prompt).stream().content();}}

Nacos 配置添加

  1. 启动 Nacos 服务;

  2. 写入配置,dataId 为:spring.ai.alibaba.configurable.prompt

  3. 在配置中写入如下配置:

[{"name":"author","template":"列出 {author} 有名的著作","model":{"key":"余华"}}
]

功能演示

完成上述配置之后,启动项目:

  1. 在启动日志中,可以看到如下输出,表明已经开始监听此 DataID 的配置:

2025-07-30T09:25:52.794+08:00  INFO 25312 --- [spring-ai-alibaba-nacos-prompt-example] [           main] .c.a.p.ConfigurablePromptTemplateFactory : OnPromptTemplateConfigChange,templateName:author,template:列出 {author} 有名的著作,model:{key=余华}

发送请求查看输出:

Tips: 这里输出了鲁迅的作品集是因为在 controller 中设置了 defaultValue 为鲁迅.

 

查看控制台输出:

2025-07-30T09:27:27.937+08:00  INFO 25312 --- [spring-ai-alibaba-nacos-prompt-example] [io-10010-exec-1] c.a.c.a.e.n.controller.PromptController  : 最终构建的 prompt 为:列出 鲁迅 有名的著作

动态更新 Nacos 的 Prompt 配置,再次查看请求查看效果

Tips: 因为 controller 中设置了 defaultValue 为鲁迅,因此 Prompt 变更仍然和文学作家相关。

变更 Prompt 为:

[{"name": "author","template": "介绍 {author},列出其生平经历和文学成就","model": {"key": "余华"}}
]

点击发布之后,看到控制台输出如下,证明变更成功:

2025-07-30T09:28:38.227+08:00  INFO 25312 --- [spring-ai-alibaba-nacos-prompt-example] [listener.task-0] .c.a.p.ConfigurablePromptTemplateFactory : OnPromptTemplateConfigChange,templateName:author,template:介绍 {author},列出其生平经历和文学成就,model:{key=余华}

再次发送请求:

最终构建的 Prompt 为: 

2025-07-30T09:28:44.736+08:00  INFO 25312 --- [spring-ai-alibaba-nacos-prompt-example] [io-10010-exec-5] c.a.c.a.e.n.controller.PromptController  : 最终构建的 prompt 为:介绍 鲁迅,列出其生平经历和文学成就

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/93599.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/93599.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于词频统计、关键词提取、情感分析与AI大模型自动生成系统的设计与实现

文章目录有需要本项目的代码或文档以及全部资源&#xff0c;或者部署调试可以私信博主一、研究背景与项目意义二、项目目标与研究内容三、系统架构与功能模块1. AI对话生成模块2. 分词与关键词提取模块3. 情感分析模块4. 行为预测模块5. 系统管理模块6. 可视化展示模块四、技术…

JVM工具

首先&#xff0c;JDK 自带了很多监控工具&#xff0c;都位于 JDK 的 bin 目录下&#xff0c;其中最常用的是 jconsole 和 jvisualvm 这两款视图监控工具。 一、jps(Java Process Status) 用于查看有权访问的虚拟机的进程&#xff0c;并显示他们的进程号 -v&#xff1a;列出虚拟…

VisionPro系列讲解 - 03 Simulator 模拟器使用

一、VisionOS Simulator 简介 VisionOS Simulator 模拟器是专为 VisionOS 操作系统开发的调试和测试工具。它允许开发者在没有实际硬件设备的情况下&#xff0c;在计算机上模拟 VisionOS 环境&#xff0c;进行应用的开发、调试和优化。该模拟器帮助开发者快速验证应用的功能和界…

huggingface是什么?2025-07-30

huggingface被我看做是ai模型的试用空间 体验了一下image edit的功能&#xff0c;去除背景的功能不错 models 模型库 dataset 目前对我来说没用 spaces huggingface的spaces是什么&#xff1f; 演示空间吧。 令人震惊的背景移除能力H200是什么&#xff1f;

mysql索引下推和索引失效

索引下推&#xff1a;ICP过滤的条件可以不限于用于索引查找&#xff08;index lookup&#xff09;的字段。只要存储引擎在扫描当前索引时能够访问到该字段的值&#xff0c;就可以用它来过滤。索引可以分为聚簇索引和非聚簇索引没有索引下推&#xff1a;当使用聚簇索引的时候&am…

【电赛学习笔记】MaixCAM 的OCR图片文字识别

前言 本文是对MaixPy官方文档 MaixCAM MaixPy 实现 OCR 图片文字识别 - MaixPy 的项目实践整理与拓展&#xff0c;侵权即删。 功能介绍 OCR是MaixCAM中功能强大的数字文字识别模块&#xff0c;可以做到轻松的识别各种数字与文字。 OCR官方例程解析 工程源码 from maix im…

如何在生成式引擎优化(GEO)中取得成功

如果你希望您的内容出现在 AI Overviews、ChatGPT 和 Gemini 中&#xff1f;以下是设置 GEO 广告系列的方法。 任何好的 GEO 活动的第一步是创造一些东西实际上想要链接到或引用。 GEO 策略组件 想象一些你合理预期不会直接在 ChatGPT 或类似系统中找到的体验&#xff1a; 例如…

WPFC#超市管理系统(3)商品管理

超市管理系统6. 商品管理6.1 添加商品6.1 商品管理主界面6.3 修改商品6. 商品管理 将前文中的GoodsView全部改成和数据库一致的ProductView新增枚举类型商品类型ProductType.cs namespace 超市管理系统.Enums {public enum ProductType{水果类,休闲食品类,粮油类,饮料类,日用…

openwrt中br-lan,eth0,eth0.1,eth0.2

CPU是QCA9558 有两个以太网接口 这个好像没有外接交换机直接印出来的 openwrt中br-lan,eth0,eth0.1,eth0.2 https://blog.csdn.net/f2157120/article/details/119460852 这个哥用的是 链接: DomyWifi DW33D 路由器 CPU是QCA9558 有两个以太网接口 因为CPU没集成千兆交换&…

RAG实战指南 Day 29:RAG系统成本控制与规模化

【RAG实战指南 Day 29】RAG系统成本控制与规模化 开篇 欢迎来到"RAG实战指南"系列的第29天&#xff01;今天我们将深入探讨RAG系统的成本控制与规模化部署策略。当RAG系统从原型阶段进入生产环境时&#xff0c;如何经济高效地扩展系统规模、控制运营成本成为关键挑…

React 中获取当前路由信息

在 React 中获取当前路由信息&#xff0c;根据使用的路由库不同&#xff08;如 React Router v5/v6 或 Next.js&#xff09;&#xff0c;方法也有所区别。以下是常见场景的解决方案&#xff1a;1. 使用 React Router v6 获取当前路径&#xff08;pathname&#xff09;、查询参数…

Sklearn 机器学习 随机森林 网格搜索获取最优参数

💖亲爱的技术爱好者们,热烈欢迎来到 Kant2048 的博客!我是 Thomas Kant,很开心能在CSDN上与你们相遇~💖 本博客的精华专栏: 【自动化测试】 【测试经验】 【人工智能】 【Python】 Sklearn 机器学习:随机森林 + 网格搜索获取最优参数实战指南 在构建机器学习模型时,…

力扣-101.对称二叉树

题目链接 101.对称二叉树 class Solution {public boolean check(TreeNode l, TreeNode r) {if (l null && r null)return true;if ((l null && r ! null) || (r null && l ! null))return false;if (l.val ! r.val)return false;return check(l…

从句--02-1--done,doing ,prep 做定语

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录定语1.done&#xff08;过去分词&#xff09;做定语一、过去分词作定语的位置二、过去分词作定语的语义特点三、过去分词作定语与现在分词作定语的区别四、过去分词作…

JVM全面解析

摘要&#xff1a;JVM是Java程序运行的核心环境&#xff0c;负责解释执行字节码并管理内存。其核心功能包括类加载与验证、字节码执行优化、内存管理与垃圾回收&#xff08;GC&#xff09;、跨平台支持及安全性保障。JVM架构包含程序计数器、虚拟机栈、本地方法栈、堆和方法区等…

SDC命令详解:使用write_script命令进行输出

相关阅读 SDC输出命令https://blog.csdn.net/weixin_45791458/category_12993272.html?spm1001.2014.3001.5482 write_script命令用于将设计中的属性设置命令输出为脚本文件&#xff08;其实它并不是一个SDC命令&#xff0c;归为此类只是为了方便管理&#xff09;&#xff0c…

‌CASE WHEN THEN ELSE END‌

‌CASE WHEN THEN ELSE END‌ 是SQL中实现条件逻辑的核心表达式&#xff0c;支持单字段匹配和多条件判断&#xff0c;适用于数据处理、分类统计等场景。‌基本语法形式‌SQL中CASE表达式有两种标准形式&#xff1a;1‌ 简单CASE表达式‌&#xff08;字段直接匹配&#xff09;C…

飞单诱因:管理漏洞与人性交织

飞单看似是 “员工个人行为”&#xff0c;实则是餐厅管理、激励机制、外部环境等多重因素共同作用的结果。要根治飞单&#xff0c;需先理清背后的 “动力源”—— 员工为何选择冒险&#xff1f;一、“收入失衡”&#xff1a;薪资与付出不匹配的 “补偿心理”基层员工&#xff0…

工作笔记-----FreeRTOS中的lwIP网络任务为什么会让出CPU

工作笔记-----FreeRTOS中的lwIP网络任务为什么会让出CPU Author: 明月清了个风Date&#xff1a; 2025.7.30Ps:最近接触了在FreeRTOS中使用lwIP实现的网络任务&#xff0c;但是在看项目代码的过程中出现了一些疑问——网络任务的优先级为所有任务中最高的&#xff0c;并且任务框…

在 CentOS 系统上安装 Docker

在 CentOS 系统上安装 Docker&#xff0c;可按以下步骤操作&#xff1a;一、卸载旧版本&#xff08;如存在&#xff09;bashsudo yum remove docker \docker-client \docker-client-latest \docker-common \docker-latest \docker-latest-logrotate \docker-logrotate \docker-…