你的第一个 AI 应用

30 分钟跑通 Spring AI Hello World


项目创建

使用 Spring Initializr 创建项目,选择以下依赖:

  • Spring Web
  • Spring AI OpenAI

完整示例代码

1. Controller 层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestController
@RequestMapping("/ai")
public class AIController {

private final ChatClient chatClient;

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

@GetMapping("/chat")
public String chat(@RequestParam String userInput) {
return chatClient.prompt()
.user(userInput)
.call()
.content();
}
}

2. Service 层(推荐)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Service
public class AIService {

private final ChatClient chatClient;

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

public String think(String userMessage) {
return chatClient.prompt()
.system("你是一位资深的Java架构师,帮助回答技术问题。")
.user(userMessage)
.call()
.content();
}
}

运行效果

1
2
3
curl "http://localhost:8080/ai/chat?userInput=什么是Spring AI"

# 返回: Spring AI 是一个用于在 Spring 生态中集成 AI 能力的框架...

常见错误

错误解决方案
401 Unauthorized检查 API Key 是否正确配置
Connection Timeout检查网络 + 代理设置
Model not found确认模型名称是否正确(如 gpt-4o)