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: 10010

spring:
  application:
    name: spring-ai-alibaba-nacos-prompt-example

  # 指定监听的 prompt 配置
  config:
    import:
      - "optional:nacos:prompt-config.json"
  nacos:

    namespace: 8279be91-ac4e-465b-a87a-bbaa1fd66d26
    server-addr: 127.0.0.1:8848
    username: nacos
    password: nacos


  ai:
    # 开启 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 创建 prompt
        ConfigurablePromptTemplate 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 为:介绍 鲁迅,列出其生平经历和文学成就

<think> 我们注意到用户询问的是使用Spring AI Alibaba实现文生视频功能,但根据提供的引用内容,当前Spring Cloud Alibaba AI主要适配的是对话、文生图、文生语音等模型,并没有明确提到文生视频功能。 因此,我们需要基于现有信息进行回答,并指出文生视频可能尚未支持,同时提供可能的解决方案或建议。 步骤: 1. 分析引用内容:引用[1]明确说明当前适配的是对话、文生图、文生语音等模型;引用[2][3]也提到聊天和文生图功能,没有文生视频。 2. 直接回答:目前Spring Cloud Alibaba AI官方版本(截至当前最新版本)似乎尚未支持文生视频功能。 3. 提供替代方案或建议:虽然官方可能不支持,但可以探讨如何扩展或结合其他工具实现类似需求。 4. 保持专业和可靠:不确定的部分不要猜测,可以建议用户关注官方更新或使用其他方式。 注意:用户要求使用中文回答,并注意LaTeX格式(虽然此问题可能不需要数学公式,但如果有公式则需要按规则)。 由于问题不涉及数学公式,我们将重点放在文字回答上。 回答结构: 1. 当前支持情况:根据引用说明当前支持的功能,指出不支持文生视频。 2. 可能的变通方法:例如,如果用户需要生成视频,可以考虑先使用文生图生成多张图片,然后使用其他工具将图片合成为视频(但这并不是真正的文生视频)。 3. 建议:关注官方更新,或者使用其他支持文生视频的API(如阿里云的智能媒体生产服务),然后在Spring项目中集成。 4. 提供参考资料:引用官方文档和相关链接。 注意:用户问题中提到“文生视频”,即输入文本直接生成视频,这是一个复杂的功能,通常需要专门的模型(如阿里云的VideoGen等)。 另外,我们注意到用户引用的内容来自Spring Cloud Alibaba AI,而提问的是spring-ai-alibaba,实际上它们是同一个项目(引用[2]中提到Spring AI Alibaba开源项目基于Spring AI构建)。 因此,我们回答如下: </think> 基于提供的引用信息,Spring Cloud Alibaba AI 目前**未正式支持文生视频功能**。以下是详细分析和建议: ### 当前支持范围(引用[1][2][3]) 1. **已适配功能**: - 对话模型(如通义千问) - 文生图(Text-to-Image) - 文生语音(Text-to-Speech) - 工具能力:OutParser、Prompt Template、Stuff等 2. **官方示例**: - 官网提供了聊天、文生图、文生语音的示例(https://sca.aliyun.com) - 无文生视频相关文档或代码示例 ### 实现文生视频的挑战 1. **技术限制**: - 视频生成需处理时空连贯性,远复杂于单帧图像/语音 - 当前主流模型(如Sora、Pika)需大量算力,尚未集成到Spring生态 2. **框架定位**: - Spring AI Alibaba 聚焦基础生成能力(对话/图像/语音) - 视频生成需依赖专用引擎(如阿里云智能媒体生产IMS)[^1] ### 替代解决方案 若需实现类似功能,可考虑: 1. **分层架构**: ```mermaid graph LR A[Spring Boot应用] --> B[调用文生图API] A --> C[调用语音合成API] B & C --> D[FFmpeg视频合成] ``` 2. **集成阿里云API**: - 通过SDK调用[智能媒体生产(IMS)](https://help.aliyun.com/zh/ims)服务 - 示例依赖: ```xml <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-ims</artifactId> <version>最新版</version> </dependency> ``` ### 建议与展望 1. **短期方案**: - 组合现有能力:文本→图像→语音→手动合成视频 - 关注[Spring AI Roadmap](https://spring.io/projects/spring-ai)更新 2. **官方反馈渠道**: - 在[GitHub Issues](https://github.com/alibaba/spring-cloud-alibaba/issues)提交需求 - 参与阿里云[开发者社区](https://developer.aliyun.com/group/sca)讨论 > 📌 **总结**:目前需自行集成视频生成服务,建议结合阿里云IMS等PaaS服务实现端到端流程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非ban必选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值