跳到主要内容

快速入门

本指南将帮助您快速开始使用 Spring AI 构建 AI 应用程序。

环境准备

系统要求

  • JDK 17 或更高版本
  • Maven 3.6+ 或 Gradle 7+
  • 支持的 IDE (IntelliJ IDEA, VS Code, Eclipse 等)

获取 API Key

您需要从模型提供商处获取 API Key:

创建新项目

使用 Spring Initializr

  1. 访问 https://start.spring.io
  2. 选择项目元数据
  3. 添加依赖:
    • Spring Web
    • Spring AI OpenAI (或其他模型提供商)

Maven 配置

pom.xml 中添加 Spring AI 依赖:

<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>

<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
</dependencies>

基本配置

application.yml 中配置模型:

spring:
ai:
openai:
api-key: ${OPENAI_API_KEY}
base-url: https://api.openai.com
chat:
options:
model: gpt-3.5-turbo
temperature: 0.7

创建第一个 AI 应用

简单聊天控制器

@RestController
public class ChatController {

private final ChatClient chatClient;

public ChatController(ChatClient chatClient) {
this.chatClient = chatClient;
}

@GetMapping("/chat")
public String chat(@RequestParam String message) {
return chatClient.call(message);
}
}

运行应用

./mvnw spring-boot:run

测试:

curl "http://localhost:8080/chat?message=你好,Spring AI"

下一步

  • 学习提示词工程技巧
  • 探索向量数据库集成
  • 了解高级功能如 Tool Calling 和 RAG

通过这个快速入门指南,您已经成功创建了第一个 Spring AI 应用程序!