Spring AI 1.0 快速入门
一、Spring AI 1.0 快速入门
1. 添加依赖
以 Maven 为例,添加 Spring AI 的 Starter 依赖(以 OpenAI 为例):
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai-spring-boot-starter</artifactId><version>1.0.0</version>
</dependency>
其他模型如百度文心一言、MiniMax、Azure 等,只需更换对应的 starter。
2. 配置 API Key
在 application.yml
或 application.properties
文件中配置 OpenAI 的 API Key:
spring:ai:openai:api-key: sk-xxxxxxx
3. 编写代码调用 AI 能力
以最常用的文本生成(Chat)为例:
import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/ai")
public class AiController {@Autowiredprivate OpenAiChatClient openAiChatClient;@PostMapping("/chat")public String chat(@RequestBody String prompt) {UserMessage userMessage = new UserMessage(prompt);return openAiChatClient.call(userMessage).getResult().getOutput().getContent();}
}
二、案例:实现一个简单的 AI 聊天接口
1. 启动类
@SpringBootApplication
public class AiDemoApplication {public static void main(String[] args) {SpringApplication.run(AiDemoApplication.class, args);}
}
2. 控制器
@RestController
@RequestMapping("/ai")
public class AiController {@Autowiredprivate OpenAiChatClient openAiChatClient;@PostMapping("/chat")public String chat(@RequestBody String prompt) {UserMessage userMessage = new UserMessage(prompt);return openAiChatClient.call(userMessage).getResult().getOutput().getContent();}
}
3. 请求示例
使用 Postman 或 curl 发送请求:
curl -X POST http://localhost:8080/ai/chat -H "Content-Type: application/json" -d "\"你好,帮我写一段自我介绍\""
返回结果会是 AI 回复的内容。
三、支持的 AI 服务商
Spring AI 1.0 支持多种大模型,常见的依赖如下:
- OpenAI:
spring-ai-openai-spring-boot-starter
- Azure OpenAI:
spring-ai-azure-openai-spring-boot-starter
- 百度文心一言:
spring-ai-baidu-spring-boot-starter
- MiniMax:
spring-ai-minimax-spring-boot-starter
- Google Gemini:
spring-ai-google-gemini-spring-boot-starter
只需替换依赖和配置即可切换不同大模型。
四、常见用法
- 对话/文本生成(如上案例)
- 函数调用(Function Calling)
- 图片生成(通过 Image API)
- 向量检索/嵌入(Vector Store/Embedding)