Spring AI Alibaba 实现了与阿里云通义模型的完整适配,接下来,我们将学习如何使用 spring ai alibaba 开发一个基于通义模型服务的智能聊天应用。
一、快速体验示例
注意:因为 Spring AI Alibaba 基于 Spring Boot 3.x 开发,因此本地 JDK 版本要求为 17 及以上。
-
下载项目 运行以下命令下载源码,进入 helloworld 示例目录:
git clone --depth=1 https://github.com/alibaba/spring-ai-alibaba.git cd spring-ai-alibaba/spring-ai-alibaba-examples/helloworld-example
-
运行项目 首先,需要获取一个合法的 API-KEY 并设置
AI_DASHSCOPE_API_KEY
环境变量,可跳转 阿里云百炼平台 了解如何获取 API-KEY。export AI_DASHSCOPE_API_KEY=${REPLACE-WITH-VALID-API-KEY}
启动示例应用:
./mvnw compile exec:java -Dexec.mainClass="com.alibaba.cloud.ai.example.helloworld.HelloWorldExampleApplication"
访问
http://localhost:8080/ai/chat?input=给我讲一个笑话吧
,向通义模型提问并得到回答。
二、示例开发指南
以上示例本质上就是一个普通的 Spring Boot 应用,我们来通过源码解析看一下具体的开发流程。
-
添加依赖
首先,需要在项目中添加
spring-ai-alibaba-starter
依赖,它将通过 Spring Boot 自动装配机制初始化与阿里云通义大模型通信的ChatClient
、ChatModel
相关实例。<dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId><version>1.0.0-M2.1</version></dependency>
注意:由于 spring-ai 相关依赖包还没有发布到中央仓库,如出现 spring-ai-core 等相关依赖解析问题,请在您项目的 pom.xml 依赖中加入如下仓库配置。
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
-
注入 ChatClient
接下来,在普通 Controller Bean 中注入
ChatClient
实例,这样你的 Bean 就具备与 AI 大模型智能对话的能力了。@RestController@RequestMapping("/ai")public class ChatController {private final ChatClient chatClient;public ChatController(ChatClient.Builder builder) {this.chatClient = builder.build();}@GetMapping("/chat")public String chat(String input) {return this.chatClient.prompt().user(input).call().content();}}
以上示例中,ChatClient 调用大模型使用的是默认参数,Spring AI Alibaba 还支持通过
DashScopeChatOptions
调整与模型对话时的参数,DashScopeChatOptions
支持两种不同维度的配置方式:-
全局默认值,即
ChatClient
实例初始化参数可以在
application.yaml
文件中指定spring.ai.dashscope.chat.options.*
或调用构造函数ChatClient.Builder.defaultOptions(options)
、DashScopeChatModel(api, options)
完成配置初始化。 -
每次 Prompt 调用前动态指定
ChatResponse response = chatModel.call(new Prompt("Generate the names of 5 famous pirates.",DashScopeChatOptions.builder().withModel("qwen-plus").withTemperature(0.4F).build()));
关于
DashScopeChatOptions
配置项的详细说明,请查看参考手册。
-
三、开发实例:RAG介绍
检索增强生成 (RAG) 是一种使用来自私有或专有数据源的信息来辅助文本生成的技术。它将检索模型(设计用于搜索大型数据集或知识库)和生成模型(例如大型语言模型 (LLM),此类模型会使用检索到的信息生成可供阅读的文本回复)结合在一起。
通过从更多数据源添加背景信息,以及通过训练来补充 LLM 的原始知识库,检索增强生成能够提高搜索体验的相关性。这能够改善大型语言模型的输出,但又无需重新训练模型。额外信息源的范围很广,从训练 LLM 时并未用到的互联网上的新信息,到专有商业背景信息,或者属于企业的机密内部文档,都会包含在内。
RAG 对于诸如回答问题和内容生成等任务,具有极大价值,因为它能支持生成式 AI 系统使用外部信息源生成更准确且更符合语境的回答。它会实施搜索检索方法(通常是语义搜索或混合搜索)来回应用户的意图并提供更相关的结果。
下图是一个RAG链路的两个阶段,包括Indexing pipeline阶段和RAG的阶段。
从上图可以看到, indexing pipeline的阶段主要是将结构化或者非结构化的数据或文档进行加载和解析、chunk切分、文本向量化并保存到向量数据库。 RAG的阶段主要包括将prompt文本内容转为向量、从向量数据库检索内容、对检索后的文档chunk进行重排和prompt重写、最后调用大模型进行结果的生成。
1、RAG调用
引入依赖:
<?xml version="1.0" encoding="UTF-8"?><!--Copyright 2023-2024 the original author or authors.Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License athttps://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.
--><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.3.3</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.alibaba.cloud.ai</groupId><artifactId>rag-example</artifactId><version>0.0.1-SNAPSHOT</version><name>rag-example</name><description>Demo project for Spring AI Alibaba</description><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><maven.compiler.source>17</maven.compiler.source><maven.compiler.target>17</maven.compiler.target><maven-deploy-plugin.version>3.1.1</maven-deploy-plugin.version><!-- Spring AI --><spring-ai-alibaba.version>1.0.0-M3.2</spring-ai-alibaba.version><spring-ai.version>1.0.0-M3</spring-ai.version><!-- utils --><commons-lang3.version>3.14.0</commons-lang3.version></properties><dependencies><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId><version>${spring-ai-alibaba.version}</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-pdf-document-reader</artifactId><version>${spring-ai.version}</version></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-elasticsearch-store-spring-boot-starter</artifactId><version>${spring-ai.version}</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-deploy-plugin</artifactId><version>${maven-deploy-plugin.version}</version><configuration><skip>true</skip></configuration></plugin></plugins></build><repositories><repository><id>spring-milestones</id><name>Spring Milestones</name><url>https://repo.spring.io/milestone</url><snapshots><enabled>false</enabled></snapshots></repository></repositories></project>
知识库内容导入
下边是将pdf文档导入到知识库的代码
DashScopeApi dashscopeApi = ...;// 1. 解析文档和chunk切分
String filePath = "新能源产业有哪些-36氪.pdf";
DashScopeDocumentCloudReader reader = new DashScopeDocumentCloudReader(filePath, dashscopeApi, null);
List<Document> documentList = reader.get();
DashScopeDocumentTransformer transformer = new DashScopeDocumentTransformer(dashscopeApi);
List<Document> transformerList = transformer.apply(documentList);
System.out.println(transformerList.size());// 2. 文档向量化
DashScopeEmbeddingModel embeddingModel = new DashScopeEmbeddingModel(dashscopeApi);
Document document = new Document("你好阿里云");
float[] vectorList = embeddingModel.embed(document);// 3. 导入文档内容到向量存储
DashScopeCloudStore cloudStore = new DashScopeCloudStore(dashscopeApi, new DashScopeStoreOptions("bailian-knowledge"));
cloudStore.add(Arrays.asList(document));// 4. 删除文档
cloudStore.delete(Arrays.asList(document.getId()));
知识问答
下边代码将根据之前创建的知识库,进行知识问答的代码:
DocumentRetriever retriever = new DashScopeDocumentRetriever(dashscopeApi, DashScopeDocumentRetrieverOptions.builder().withIndexName("bailian-knowledge").build());ChatClient chatClient = ChatClient.builder(dashscopeChatModel).defaultAdvisors(new DocumentRetrievalAdvisor(retriever)).build();ChatResponse response = chatClient.prompt().user("如何快速开始百炼?").call().chatResponse();
String content = response.getResult().getOutput().getContent();
Assertions.assertNotNull(content);logger.info("content: {}", content);
如果需要返回检索召回后,模型采纳和引用的文档内容, 可以通过以下代码实现:
DocumentRetriever retriever = new DashScopeDocumentRetriever(dashscopeApi,DashScopeDocumentRetrieverOptions.builder().withIndexName("spring-ai知识库").build());ChatClient chatClient = ChatClient.builder(dashscopeChatModel).defaultAdvisors(new DashScopeDocumentRetrievalAdvisor(retriever, true)).build();ChatResponse response = chatClient.prompt().user("如何快速开始百炼?").call().chatResponse();String content = response.getResult().getOutput().getContent();
Assertions.assertNotNull(content);
logger.info("content: {}", content);//获取引用的内容
List<Document> documents = (List<Document>) response.getMetadata().get(DashScopeDocumentRetrievalAdvisor.RETRIEVED_DOCUMENTS);
Assertions.assertNotNull(documents);for (Document document : documents) {logger.info("referenced doc name: {}, title: {}, score: {}", document.getMetadata().get("doc_name"),document.getMetadata().get("title"), document.getMetadata().get("_score"));}