当前位置: 首页 > article >正文

Spring AI入门示例HelloWorld

本文重点介绍,基于Spring AI框架,并使用阿里百炼大模型服务平台的AI服务,快速搭建一个springboot工程,并进行简单的AI问答,初步验证Spring AI框架的易用性,以及与阿里巴巴AI框架spring-ai-alibaba-starter的友好集成性。

1、使用Spring AI前提条件

  • JDK为17以上版本,本人使用的jdk21版本;
  • SpringBoot版本为3.x以上,本项目使用的是SpringBoot 3.3.3版本;
  • 开通阿里大模型服务(目前是免费6个月),获取 API-KEY,后面代码里要使用。具体操作,请参考阿里云大模型服务平台百炼:如何获取API Key_大模型服务平台百炼(Model Studio)-阿里云帮助中心

2、创建SpringBoot工程

通过IDEA开发工具,创建一个普通的Java工程,注意JDK版本至少是17以上,我这里使用的是jdk21版本。

3、配置pom.xml文件

工程创建完成后,在pom.xml里添加依赖。

首先,需要在项目中添加 spring-boot-starter-parent声明,指定springboot框架的版本号:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.3</version>
        <relativePath/>
    </parent>

在dependencies标签中引入spring-boot-starter-web依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

然后,需要在项目中添加 spring-ai-alibaba-starter依赖:

        <dependency>
            <groupId>com.alibaba.cloud.ai</groupId>
            <artifactId>spring-ai-alibaba-starter</artifactId>
            <version>1.0.0-M3.2</version>
        </dependency>

由于 spring-ai 相关依赖包还没有发布到中央仓库,如出现 spring-ai-core 等相关依赖解析问题,请在您项目的 pom.xml 依赖中加入如下仓库配置。

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

最后pom.xml文件完整内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yuncheng</groupId>
    <artifactId>spring-ai-helloworld</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.3.3</version>
        <relativePath/>
    </parent>

    <dependencies>
        <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</artifactId>
            <version>1.0.0-M3.2</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>

4、配置yml文件

在工程的resources目录下的application-dev.yml文件里增加如下配置:

注意: api-key要替换成自己从阿里百炼平台申请的key

server:
  port: 8080

spring:
  application:
    name: spring-ai-helloworld
  ai:
    dashscope:
      api-key: sk-b90ad31bb3eb4a158524928354f39ac5
    chat:
      client:
        enabled: true

chat.client.enabled=true 这个配置表示的是ChatClient自动装配,如果通过编程方式创建ChatClient,这里需要设置成false。

5、创建ChatController

创建一个普通 Controller Bean类, 注入 ChatClient 实例,这样你的 Bean 就具备与 AI 大模型智能对话的能力了。

在这个示例中,根据用户提问并从模型得到文本回答,首先设置了用户消息的内容,call 方法向 AI 模型发送请求,content 方法以字符串形式返回 AI 模型的响应。

package com.yuncheng;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ai")
public class ChatController {
    private static final Logger log = LoggerFactory.getLogger(ChatController.class);
    private final ChatClient chatClient;

    public ChatController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @GetMapping("/chat")
    public String chat(String input) {
        log.info("人工提问:"+input);

        String reply =  this.chatClient.prompt()
                .user(input)
                .call()
                .content();

        log.info("大模型回复:"+reply);
        return reply;
    }
}

以上示例中,ChatClient 调用大模型使用的是默认参数,Spring AI Alibaba 还支持通过 DashScopeChatOptions 调整与模型对话时的参数,DashScopeChatOptions 支持两种不同维度的配置方式:

  • 全局默认值,即 ChatClient 实例初始化参数,可以在 application.yaml 文件中指定。
  • 每次 Prompt 调用前动态指定。

6、创建Application启动类

package com.yuncheng;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

@SpringBootApplication
public class AiApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext application = SpringApplication.run(AiApplication.class, args);
        Environment env = application.getEnvironment();
        String port = env.getProperty("server.port");
        System.out.println("AiApplication启动成功,服务端口为:" + port);

    }
}

7、启动Springboot工程并测试

    工程启动成功后,可以向大模型提问,打开浏览器,在地址栏输入:

    http://localhost:8080/ai/chat?input=世界上一共有多少个国家

    AI大模型回复:

    截至2023年,世界上共有195个国家。其中,193个是联合国的会员国,2个是非会员观察员国(梵蒂冈和巴勒斯坦)。需要注意的是,由于政治、历史等因素,某些地区的国家地位存在争议,这导致不同组织或国家对于世界国家总数的统计可能略有差异。但通常情况下,195这个数字被广泛接受。

    8、总结

    通过以上项目验证,证明了在Java语言中,基于Spring Boot + Spring AI开源框架,并使用阿里云国内大模型服务,在SpringBoot工程中集成并使用AI大模型服务是初步可行的。


    http://www.kler.cn/a/511332.html

    相关文章:

  1. 基于微信小程序的购物系统设计与实现(LW+源码+讲解)
  2. 【江西新能源科技职业学院主办 | JPCS(ISSN: 1742-6588)出版,快速见刊检索】2025年可再生能源与节能国际会议(REEC 2025)
  3. Windows中安装RabbitMQ
  4. TrueNas Webui页面自定义
  5. 2024年度总结:从后端Java到全栈成长的蜕变
  6. python3GUI--仿崩坏三二次元登录页面(附下载地址) By:PyQt5
  7. 如何优化前端性能,减少页面加载时间?
  8. 解决 IntelliJ IDEA 项目包后出现“% classes”和“% lines covered”的问题
  9. 在 Ubuntu 上安装 Nginx 的详细指南
  10. 智能阅读时代:基于NLP的自动新闻摘要技术解析
  11. 【VRChat · 改模】Unity工程导入人物模型;并添加着色器教程;
  12. 简述mysql 主从复制原理及其工作过程,配置一主两从并验证
  13. 论文阅读(一):下一代基因组学和遗传学的概率图模型
  14. 简述mysql 主从复制原理及其工作过程,配置一主两从并验证。
  15. 利用免费GIS工具箱实现高斯泼溅切片,将 PLY 格式转换为 3dtiles
  16. 使用numpy求解线性代数相关问题
  17. HTML<center>标签
  18. CTF随题思路—[BSidesSF2019]zippy
  19. hdrnet,Deep Bilateral Learning for Real-Time Image Enhancement解读
  20. C++入门基础篇:域、C++的输入输出、缺省参数、函数重载、引用、inline、nullptr