二
快速开始:第一个 AI 对话接口
Quick Start
四步跑起来:建项目 → 加依赖 → 配 API Key → 写个接口。你需要一个阿里云百炼平台的 API Key(百炼控制台申请,新用户有免费额度)。下面是最小可跑版本。
第一步:pom.xml 加 spring-ai-alibaba-starter(版本以官方最新为准)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.x</version>
</parent>
<dependencies>
<artifactId>spring-boot-starter-web</artifactId>
<!-- spring-ai-alibaba 的 starter,自动装配 ChatModel -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter</artifactId>
<version>1.0.0.x</version>
</dependency>
</dependencies>
第二步:application.yml 配 API Key 和模型名
spring:
ai:
alibaba:
# 通义千问模型配置(以百炼控制台最新模型名为准)
chat:
options:
model: qwen-plus # 模型名:qwen-max / qwen-plus / qwen-turbo
temperature: 0.7 # 创造力:0 严谨,1 放飞
api-key: ${DASHSCOPE_API_KEY} # 从环境变量读,别硬编码在代码里!
申请 API Key 的步骤
没有 Key 啥也跑不起来。用阿里云百炼平台(DashScope),步骤很简单:
第一步:注册阿里云账号
去阿里云官网注册,完成实名。
大白话:没账号啥也干不了。
第二步:开通百炼大模型服务
搜索"百炼"或"Model Studio",开通服务。新用户一般有免费额度。
大白话:开通了才能调模型。
第三步:创建 API-KEY
在控制台"API-KEY 管理"里创建一个,复制下来(只显示一次)。
大白话:这就是你的"调模型门票",别给别人。
第四步:设为环境变量
export DASHSCOPE_API_KEY="sk-xxx"解析:别写进代码,见上面的坑。
跑不起来?先查这三点
第一次跑新东西,八成是配置问题,不是代码问题:
报 401 / unauthorized
API Key 不对。
检查:环境变量真的设了吗?Key 复制对了吗?有多余空格吗?账号欠费了吗?
报 404 / model not found
模型名写错了。
检查:application.yml 里的 model 名是不是控制台真实存在的(qwen-plus 还是 qwen-plus-latest)。
启动报 NoSuchBeanDefinition
starter 没装对或版本冲突。
检查:spring-ai-alibaba-starter 版本跟 Spring Boot 版本对得上吗?
API Key 千万别硬编码
上面用 ${DASHSCOPE_API_KEY} 从环境变量读。把 Key 直接写在 application.yml 里再提交到 Git,是新手经典事故——Key 泄露到 GitHub,别人拿去刷你的钱,几百块账单几小时就没了。生产环境用 Nacos 配置中心 + 加密,或用云厂商的密钥管理服务。
第三步:写一个 Controller,注入 ChatClient
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/ai")
public class ChatController {
// ChatClient 是 Spring AI 最核心的入口,starter 自动装配好
private final ChatClient chatClient;
public ChatController(ChatClient.Builder builder) {
this.chatClient = builder.build();
}
@GetMapping("/chat")
public String chat(@RequestParam String q) {
// 就这一行:把问题发给大模型,拿回答案
return chatClient.prompt(q).call().content();
}
}
第四步:启动,浏览器访问
# 启动前先设好环境变量(Mac/Linux)
export DASHSCOPE_API_KEY="sk-xxxxxxxx"
# 启动应用后访问:
# http://localhost:8080/ai/chat?q=用一句话解释什么是微服务
# 大模型的回答就返回给你了