001-Spring AI Alibaba Hello world 示例

本示例将引导您快速上手 Spring AI Alibaba,通过简单的 Hello World 项目演示如何使用 Spring AI Alibaba 与阿里云 DashScope 通义大模型进行对话。
1. 示例目标
我们将创建一个简单的 Spring Boot 应用,演示如何:
- 简单对话 (
/helloworld/simple/chat):通过 ChatClient 发送问题并获取 AI 回答。 - 流式对话 (
/helloworld/stream/chat):通过流式响应实时获取 AI 生成的回答。 - 使用 Advisor 增强对话 (
/helloworld/advisor/chat/{id}):通过 Advisor 模式实现功能增强,如日志记录和对话记忆。
2. 技术栈与核心依赖
- Spring Boot 3.x
- Spring AI Alibaba (用于对接阿里云 DashScope 通义大模型)
- Maven (项目构建工具)
在 pom.xml 中,你需要引入以下核心依赖:
<dependencies><!-- Spring Web 用于构建 RESTful API --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring AI Alibaba 核心启动器,集成 DashScope --><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-dashscope</artifactId></dependency>
</dependencies>3. 项目配置
在 src/main/resources/application.yml 文件中,配置你的 DashScope API Key。
server:port: 18080spring:application:name: spring-ai-alibaba-helloworldai:dashscope:api-key: ${AI_DASHSCOPE_API_KEY}重要提示:请将 AI_DASHSCOPE_API_KEY 环境变量设置为你从阿里云获取的有效 API Key。你也可以直接将其写在配置文件中,但这不推荐用于生产环境。
4. 编写 Java 代码
4.1 HelloworldApplication.java
Spring Boot 应用程序入口类。
package com.alibaba.cloud.ai.example.helloworld;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class HelloworldApplication {public static void main(String[] args) {SpringApplication.run(HelloworldApplication.class, args);}
}4.2 HelloworldController.java
实现对话功能的控制器类。
package com.alibaba.cloud.ai.example.helloworld;import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import jakarta.servlet.http.HttpServletResponse;
import reactor.core.publisher.Flux;import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/helloworld")
public class HelloworldController {private static final String DEFAULT_PROMPT = "你是一个博学的智能聊天助手,请根据用户提问回答!";private final ChatClient dashScopeChatClient;// 使用构造函数注入 ChatClientpublic HelloworldController(ChatClient.Builder chatClientBuilder) {this.dashScopeChatClient = chatClientBuilder.defaultSystem(DEFAULT_PROMPT)// 实现 Logger 的 Advisor.defaultAdvisors(new SimpleLoggerAdvisor())// 设置 ChatClient 中 ChatModel 的 Options 参数.defaultOptions(DashScopeChatOptions.builder().withTopP(0.7).build()).build();}/*** ChatClient 简单调用*/@GetMapping("/simple/chat")public String simpleChat(@RequestParam(value = "query", defaultValue = "你好,很高兴认识你,能简单介绍一下自己吗?")String query) {return dashScopeChatClient.prompt(query).call().content();}/*** ChatClient 流式调用*/@GetMapping("/stream/chat")public Flux<String> streamChat(@RequestParam(value = "query", defaultValue = "你好,很高兴认识你,能简单介绍一下自己吗?")String query, HttpServletResponse response) {response.setCharacterEncoding("UTF-8");return dashScopeChatClient.prompt(query).stream().content();}/*** ChatClient 使用自定义的 Advisor 实现功能增强.* eg:* http://127.0.0.1:18080/helloworld/advisor/chat/123?query=你好,我叫牧生,之后的会话中都带上我的名字* 你好,牧生!很高兴认识你。在接下来的对话中,我会记得带上你的名字。有什么想聊的吗?* http://127.0.0.1:18080/helloworld/advisor/chat/123?query=我叫什么名字?* 你叫牧生呀。有什么事情想要分享或者讨论吗,牧生?*/@GetMapping("/advisor/chat/{id}")public Flux<String> advisorChat(HttpServletResponse response,@PathVariable String id,@RequestParam String query) {response.setCharacterEncoding("UTF-8");return this.dashScopeChatClient.prompt(query).advisors(// TODO// 可以在这里添加 Chat Memory Advisor 等// a -> a// .param(CHAT_MEMORY_CONVERSATION_ID_KEY, id)// .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 100)).stream().content();}
}5. 运行与测试
- 启动应用:运行
HelloworldApplication的 main 方法,或使用 Maven 命令mvn spring-boot:run。 - 使用浏览器或 API 工具(如 Postman, curl)进行测试。
测试 1:简单对话
访问以下 URL,发送问题并获取 AI 回答。
http://localhost:18080/helloworld/simple/chat?query=你好,很高兴认识你,能简单介绍一下自己吗?预期响应:
你好!我是一个基于人工智能的聊天助手,很高兴认识你。我可以回答问题、提供信息、参与讨论,并尽力帮助你解决各种问题。无论是学习、工作还是日常生活中的疑问,我都很乐意为你提供支持。有什么我可以帮助你的吗?
测试 2:流式对话
访问以下 URL,以流式方式获取 AI 回答。
http://localhost:18080/helloworld/stream/chat?query=请简单介绍一下人工智能的发展历程预期响应:
人工智能(AI)的发展历程可以追溯到20世纪中期...
在1950年代,图灵测试被提出...
1960年代至1970年代是AI的第一次繁荣期...
(流式输出,内容逐步显示)
测试 3:使用 Advisor 增强对话
访问以下 URL,使用 Advisor 功能增强对话。
http://localhost:18080/helloworld/advisor/chat/123?query=你好,我叫牧生,之后的会话中都带上我的名字预期响应:
你好,牧生!很高兴认识你。在接下来的对话中,我会记得带上你的名字。有什么想聊的吗?
接着发送:
http://localhost:18080/helloworld/advisor/chat/123?query=我叫什么名字?预期响应:
你叫牧生呀。有什么事情想要分享或者讨论吗,牧生?
6. 实现思路与扩展建议
实现思路
本示例的核心思想是简化 Spring AI Alibaba 的使用流程,通过以下方式实现:
- 简洁的 API 设计:ChatClient 提供了流畅的 API,使开发者能够轻松构建 AI 对话功能。
- 灵活的配置方式:通过构造函数注入和 Builder 模式,支持灵活配置 ChatClient。
- 可扩展的 Advisor 模式:通过 Advisor 机制,可以方便地添加日志记录、对话记忆等功能增强。
- 多种调用方式:支持简单调用和流式调用,满足不同场景的需求。
扩展建议
- 实现对话记忆功能:取消代码中 Chat Memory Advisor 的注释,并实现相应的对话记忆功能,使 AI 能够记住之前的对话内容。
- 添加更多 Advisor:可以自定义 Advisor,实现如内容过滤、请求限流、性能监控等功能。
- 集成更多模型:通过配置不同的模型参数,可以尝试使用 DashScope 提供的其他模型,如 qwen-plus、qwen-max 等。
- 添加身份验证:在实际应用中,可以添加身份验证和授权机制,保护 API 接口。
- 实现多轮对话:基于对话记忆功能,实现更复杂的多轮对话场景,如客服系统、智能助手等。
