六、使用Spring AI Alibaba实现聊天、文生图、文生音频

六、使用Spring AI Alibaba实现聊天、文生图、文生音频

==================================================================================

==================================================================================

参考资料:

==================================================================================

Spring AI Alibaba (java2ai.com)

在LinuxmacOS和Windows上配置APIKey为环境变量-大模型服务平台百炼-阿里云 (aliyun.com)

==================================================================================

在前面一篇springai_rag工程代码里直接写接口文件 AlibabaController.java

1、聊天

@RestController
@RequestMapping("/alibaba")
public class AlibabaController {

    private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手,请根据用户提问回答!";

    private final ChatClient dashScopeChatClient;

    public AlibabaController(ChatClient.Builder chatClientBuilder) {
        this.dashScopeChatClient = chatClientBuilder
                .defaultSystem(DEFAULT_PROMPT)
                // 实现 Chat Memory 的 Advisor
                // 在使用 Chat Memory 时,需要指定对话 ID,以便 Spring AI 处理上下文。
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(new InMemoryChatMemory())
                )
                // 实现 Logger 的 Advisor
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                )
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(
                        DashScopeChatOptions.builder()
                                .withTopP(0.7)
                                .build()
                )
                .build();
    }

    // 聊天
    @GetMapping("/chat")
    public String chat(String query) {
        return dashScopeChatClient.prompt(query).call().content();
    }
}

2、文生音频

@RestController
@RequestMapping("/alibaba")
public class AlibabaController {
    private static final String TEXT = "床前明月光, 疑是地上霜。 举头望明月, 低头思故乡。";
    private static final String PATH = "D:\\workspace\\springAI\\springboot-ai-demo\\springai_rag\\src\\main" +
            "\\resources\\tts";

    @Autowired
    private DashScopeSpeechSynthesisModel speechSynthesisModel;

    // 文生音频
    @GetMapping("/tts")
    public void tts() {
        //创建SpeechSynthesisOptions
        DashScopeSpeechSynthesisOptions options =
                DashScopeSpeechSynthesisOptions.builder()
                        .withSpeed(1.0)
                        .withPitch(0.9)
                        .withVolume(60)
                        .build();

        SpeechSynthesisResponse response = speechSynthesisModel.call(
                new SpeechSynthesisPrompt(TEXT, options)
        );
        File file = new File(PATH + "/output.mp3");
        try (FileOutputStream fos = new FileOutputStream(file)) {
            ByteBuffer byteBuffer = response.getResult().getOutput().getAudio();
            fos.write(byteBuffer.array());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

20c48b51-060b-4c23-8fb0-7f9615be6f80

接口没有返回内容,直接在指定目录下生成了output.mp3文件

3、文生图

@RestController
@RequestMapping("/alibaba")
public class AlibabaController {
    @Autowired
    private DashScopeImageModel imageModel;

    // 文生图
    @GetMapping("/image")
    public void getImage(@RequestParam(value = "msg", defaultValue = "生成一只可爱的小狗和一只可爱的小猫在一起玩耍")
                         String msg, HttpServletResponse response) {
        ImageResponse imageResponse = imageModel.call(
                new ImagePrompt(
                        msg,
                        DashScopeImageOptions.builder()
                                .withModel(DashScopeImageApi.DEFAULT_IMAGE_MODEL)
                                .withN(1)
                                .withHeight(1024)
                                .withWidth(1024)
                                .build()
                )
        );
        //获取生成图像的地址
        String imageUrl = imageResponse.getResult().getOutput().getUrl();
        //在浏览器输出
        try {
            URL url = URI.create(imageUrl).toURL();
            InputStream in = url.openStream();
            response.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
            response.getOutputStream().write(in.readAllBytes());
            response.getOutputStream().flush();
        } catch (Exception e) {
        }
    }
}

8b113841-2c86-4999-ad8e-e5ec3effdd8b

posted @ 2025-11-24 15:29  老羅  阅读(0)  评论(0)    收藏  举报