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
英文地址,請注明出處:http://en.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-…