环境准备
约 483 字大约 2 分钟
布欧-Lewyon
2026-05-15
Spring AI 支持云端 AI 和本地 AI 两种模式。本文介绍两种方案的配置。
方案一:OpenAI(云端)
获取 API Key
- 访问 platform.openai.com/api-keys
- 创建新的 API Key
- 确保账号有足够的余额
配置
# application.yml
spring:
ai:
openai:
api-key: sk-xxxxx
base-url: https://api.openai.com
chat:
options:
model: gpt-4o-mini
temperature: 0.7方案二:Ollama(本地)
Ollama 在本地运行 LLM,完全免费,数据不出本机。
安装 Ollama
# macOS
brew install ollama
# Linux
curl -fsSL https://ollama.com/install.sh | sh
# 启动服务
ollama serve拉取模型
# 拉取轻量模型(推荐开发使用)
ollama pull llama3.2:1b
# 拉取更强大的模型(需要更多资源)
ollama pull llama3.2:3b
ollama pull qwen2.5:7b
# 查看已拉取的模型
ollama list
# 测试模型
ollama run llama3.2:1b "Hello"配置
# application.yml
spring:
ai:
ollama:
base-url: http://localhost:11434
chat:
options:
model: llama3.2:1b
temperature: 0.7方案三:Azure OpenAI(企业)
spring:
ai:
azure:
openai:
api-key: your-azure-api-key
endpoint: https://your-resource.openai.azure.com
chat:
options:
deployment-name: gpt-4oMaven 依赖
<!-- OpenAI -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
<!-- Ollama -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>
<!-- Azure OpenAI -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-azure-openai-spring-boot-starter</artifactId>
</dependency>BOM 与仓库
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-bom</artifactId>
<version>1.0.0-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>spring-milestones</id>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>验证环境
# 验证 Ollama 服务
curl http://localhost:11434/api/tags
# 验证 OpenAI Key
curl https://api.openai.com/v1/models \
-H "Authorization: Bearer sk-xxxxx"小结
- OpenAI:需 API Key 和余额,适合生产环境。
- Ollama:本地运行,免费,适合开发调试和数据隐私敏感场景。
- Azure OpenAI:企业级,Azure 生态集成。
- 开发阶段推荐 Ollama,生产推荐 OpenAI 或 Azure。
- 切换提供商只需换 Starter 和配置,代码几乎不变。
上一节:Spring AI 概览 下一节:第一个 Spring AI 应用
