使用前介绍

我们以 Alibaba 的百炼平台作为Spring-AI的模型讲解,以最新稳定版作为架构。

spring-ai 的最新版本 1.1.2 ;alibaba-spring-ai 的最新版本 1.1.0.0-RC1。

需要注意一点:最新版本的 Spring Boot 4.0.0 不能适配,需要降低版本到 3.5.8。

  • 流式输出 :使得输出更流程,快捷,提升用户体验

  • ChatClient :把各个大模型的ChatModel统一接口化,使得代码中不需要依赖底层的具体模型

    注意: 1)若项目中只有一个模型,则Spring-AI 为自动装配上这个模型;

    ​ 2)若项目中有两个以上模型,则要明确指明是装配哪个模型。

代码部分

  • 项目依赖与配置:(略,上一篇有介绍)

  • Java 代码:

    package com.yiyi.coding.spring.ai;
    
    import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatModel;
    import org.junit.jupiter.api.Test;
    import org.springframework.ai.chat.client.ChatClient;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    
    @SpringBootTest
    public class DashScopeTest {
        @Test
        public void testChatModel(@Autowired DashScopeChatModel dashScopeChatModel) {
            System.out.println(dashScopeChatModel.call("你是谁"));
        }
    
        /**
         * 流式打印,输出 Flux<String>
         */
        @Test
        public void testChatModelStream(@Autowired DashScopeChatModel dashScopeChatModel) {
           dashScopeChatModel.stream("你是谁").toStream().forEach(System.out::println);
        }
    
        @Test
        public void testChatClient(@Autowired ChatClient.Builder chatClientBuilder) {
            ChatClient chatClient = chatClientBuilder.build();
            chatClient.prompt("你是谁").stream().content().toStream().forEach(System.out::println);
        }
    
        /**
         * 装配具体的模型
         */
        @Test
        public void testChatClient2( @Autowired DashScopeChatModel dashScopeChatModel) {
            ChatClient chatClient = ChatClient.builder(dashScopeChatModel).build();
            chatClient.prompt("你是谁").stream().content().toStream().forEach(System.out::println);
        }
    }
    
  • 运行后输出的其中一段内容,采用的是流式输出:

    我是
    通义千
    问,
    由
    阿里云研发的超大规模
    语言模型。我可以生成
    各种类型的文本,如文章
    、故事、诗歌、故事
    等,并能够根据不同的
    场景和需求进行变换和
    扩展。此外,我还能够
    回答各种问题,提供帮助
    和解决方案。我
    被设计用来协助
    用户撰写故事、诗歌
    、公文,
    提供信息查询,
    编程等,能够
    支持多种语言,满足
    国际化的使用需求。很高兴
    为您服务!
    
Logo

中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

更多推荐