前言
当前各种AI项目层出不穷,但绝大多数都是用python写的,现在Spring开源了Spring AI项目,让Java开发者也可以轻松给自己的springboot项目集成AI能力。目前spring AI正式版本为0.8.1,支持接入openAI、Ollama、Azure openAI、Huggingface等,可实现聊天、embedding、图片生成、语音转文字、向量数据库、function calling、prompt模板、outputparser、RAG等功能,就像Java版本的langchain。
Spring AI有以下特点:
1、在AI的聊天、文生图、嵌入模型等方面提供API级别的支持
2、与模型之间支持同步式和流式交互(还记得ChatGPT返回内容时,是逐字生成的吗,这就是流式交互的效果)
3、多种模型支持
使用Spring AI
版本
maven:3.8.1
jdk:17
springboot:3.2.4
spring ai:0.8.1 (稳定版)
OpenAI
使用OpenAI需要对应账号及api key才行,这里可以使用自己账号也可以借助网络免费使用chatGPT的方法
https://gitcode.com/chatanywhere/GPT_API_free/overview
运行AI
创建一个maven工程
pom
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.imaniy</groupId>
<artifactId>hello-springai</artifactId>
<version>1.0-SNAPSHOT</version>
<description>Simple AI Application demos</description>
<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>0.8.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>spring-milestones