随着Chatpt的火爆,现在Spring官方也开始支持AI了并推出了Spring AI框架,目前还没发布正式版本,这里可以先看一下官方依赖的版本。
Spring官网地址可以看这里:Spring | Home
目前官网上是有这两个版本:1.0.0和1.1.0-SNAPSHOT两个版本。
现在我们在本地搭建SpringAI工程,这里需要注意两点:
1.SpringAI框架支持的版本为SpringBoot3.x版本。
2.SpringAI框架支持的JDK版本为17+。
话不多说,我们开始在本地搭建Maven项目,首先是引入Maven依赖:
<!--SpringBoot版本控制-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.8</version>
</parent>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring-ai.version>1.0.0-M5</spring-ai.version>
</properties>
<dependencies>
<!--SpringBoot Web 控制器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--openai和SpringBoot整合-->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
<!--SpringBoot Test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
<!--spring ai版本控制-->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>${spring-ai.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
依赖引入以后,我们需要对openai进行配置,下面仅以deepseek接入作为示例,接下来要配置applicaiton.properties文件。
#在DeepSeek上进行申请,不清楚的,待会会另开一个文章进行演示。
spring.ai.openai.api-key=sk-f0ca21bd****************
#deepseek的地址
spring.ai.openai.base-url=https://api.deepseek.com
#待调用的模型名称
spring.ai.openai.chat.options.model=deepseek-chat
#这个是生成结果的多样性的配置
spring.ai.openai.chat.options.temperature=0.7
配置文件也弄好了,接下来我们就可以开始编码了
@RestController
@RequestMapping("/openai")
public class DemoController {
@Autowired
OpenAiChatModel openAiChatModel;
@GetMapping(value = "/hello")
public String openaiHello(@RequestParam(value = "message", defaultValue = "你是谁") String message) {
String result = openAiChatModel.call(message);
System.out.println(result);
return result;
}
}
我们看看deepseek是怎么回答的
到这里,一个小DEMO就搭建好了