环境搭建

在本地搭建 Spring AI 开发环境


前置要求

  • JDK: 17+ (推荐 21)
  • 构建工具: Maven 或 Gradle
  • AI 提供商账号: OpenAI / Azure OpenAI / Ollama 等

Maven 依赖

1
2
3
4
5
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-openai</artifactId>
<version>1.0.0-M6</version>
</dependency>

⚠️ 版本号会持续更新,请在 Spring AI Initializr 确认最新版本


application.yml 基础配置

1
2
3
4
5
6
7
8
9
10
spring:
application:
name: spring-ai-demo
ai:
openai:
api-key: ${OPENAI_API_KEY}
chat:
options:
model: gpt-4o
temperature: 0.7

环境变量

1
2
3
4
5
# Linux/Mac
export OPENAI_API_KEY=sk-xxxx

# Windows (PowerShell)
$env:OPENAI_API_KEY="sk-xxxx"

验证安装

创建一个简单的 @RestController:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@RestController
class AIController {
private final ChatClient chatClient;

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

@GetMapping("/ai/test")
String test() {
return chatClient.prompt()
.user("Say hello in one sentence")
.call()
.content();
}
}

启动后访问 http://localhost:8080/ai/test,应有返回。


使用国内模型(可选)

若使用硅基流动 / 阿里云等国内平台:

1
2
3
4
5
spring:
ai:
openai:
base-url: https://api.siliconflow.cn/v1
api-key: xxx