网站留言板制作,可以定制衣服的软件,手工制作大全简单,商业网站建设费用Spring AI Alibaba 实现了与阿里云通义模型的完整适配#xff0c;接下来#xff0c;我们将学习如何使用 spring ai alibaba 开发一个基于通义模型服务的智能聊天应用。
一、快速体验示例 注意#xff1a;因为 Spring AI Alibaba 基于 Spring Boot 3.x 开发#xff0c;因此…Spring AI Alibaba 实现了与阿里云通义模型的完整适配接下来我们将学习如何使用 spring ai alibaba 开发一个基于通义模型服务的智能聊天应用。
一、快速体验示例 注意因为 Spring AI Alibaba 基于 Spring Boot 3.x 开发因此本地 JDK 版本要求为 17 及以上。 下载项目 运行以下命令下载源码进入 helloworld 示例目录 git clone --depth1 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.mainClasscom.alibaba.cloud.ai.example.helloworld.HelloWorldExampleApplication 访问 http://localhost:8080/ai/chat?input给我讲一个笑话吧向通义模型提问并得到回答。
二、示例开发指南
以上示例本质上就是一个普通的 Spring Boot 应用我们来通过源码解析看一下具体的开发流程。 添加依赖 首先需要在项目中添加 spring-ai-alibaba-starter 依赖它将通过 Spring Boot 自动装配机制初始化与阿里云通义大模型通信的 ChatClient、ChatModel 相关实例。 dependencygroupIdcom.alibaba.cloud.ai/groupIdartifactIdspring-ai-alibaba-starter/artifactIdversion1.0.0-M2.1/version/dependency 注意由于 spring-ai 相关依赖包还没有发布到中央仓库如出现 spring-ai-core 等相关依赖解析问题请在您项目的 pom.xml 依赖中加入如下仓库配置。 repositories repository idspring-milestones/id nameSpring Milestones/name urlhttps://repo.spring.io/milestone/url snapshots enabledfalse/enabled /snapshots /repository /repositories 注入 ChatClient 接下来在普通 Controller Bean 中注入 ChatClient 实例这样你的 Bean 就具备与 AI 大模型智能对话的能力了。 RestControllerRequestMapping(/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 version1.0 encodingUTF-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 xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersionparentgroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-parent/artifactIdversion3.3.3/versionrelativePath/ !-- lookup parent from repository --/parentgroupIdcom.alibaba.cloud.ai/groupIdartifactIdrag-example/artifactIdversion0.0.1-SNAPSHOT/versionnamerag-example/namedescriptionDemo project for Spring AI Alibaba/descriptionpropertiesproject.build.sourceEncodingUTF-8/project.build.sourceEncodingproject.reporting.outputEncodingUTF-8/project.reporting.outputEncodingmaven.compiler.source17/maven.compiler.sourcemaven.compiler.target17/maven.compiler.targetmaven-deploy-plugin.version3.1.1/maven-deploy-plugin.version!-- Spring AI --spring-ai-alibaba.version1.0.0-M3.2/spring-ai-alibaba.versionspring-ai.version1.0.0-M3/spring-ai.version!-- utils --commons-lang3.version3.14.0/commons-lang3.version/propertiesdependenciesdependencygroupIdcom.alibaba.cloud.ai/groupIdartifactIdspring-ai-alibaba-starter/artifactIdversion${spring-ai-alibaba.version}/version/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.apache.commons/groupIdartifactIdcommons-lang3/artifactId/dependencydependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-pdf-document-reader/artifactIdversion${spring-ai.version}/version/dependencydependencygroupIdorg.springframework.ai/groupIdartifactIdspring-ai-elasticsearch-store-spring-boot-starter/artifactIdversion${spring-ai.version}/version/dependency/dependenciesbuildpluginsplugingroupIdorg.springframework.boot/groupIdartifactIdspring-boot-maven-plugin/artifactId/pluginplugingroupIdorg.apache.maven.plugins/groupIdartifactIdmaven-deploy-plugin/artifactIdversion${maven-deploy-plugin.version}/versionconfigurationskiptrue/skip/configuration/plugin/plugins/buildrepositoriesrepositoryidspring-milestones/idnameSpring Milestones/nameurlhttps://repo.spring.io/milestone/urlsnapshotsenabledfalse/enabled/snapshots/repository/repositories/project
知识库内容导入
下边是将pdf文档导入到知识库的代码
DashScopeApi dashscopeApi ...;// 1. 解析文档和chunk切分
String filePath 新能源产业有哪些-36氪.pdf;
DashScopeDocumentCloudReader reader new DashScopeDocumentCloudReader(filePath, dashscopeApi, null);
ListDocument documentList reader.get();
DashScopeDocumentTransformer transformer new DashScopeDocumentTransformer(dashscopeApi);
ListDocument 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);//获取引用的内容
ListDocument documents (ListDocument) 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));}