AI-大模型接入
一、AI 大模型概念
什么是大模型?
大模型,即大规模预训练模型,是一种基于深度学习的人工智能模型,通过在海量数据上进行无监督或自监督学习,学习到数据中广泛的通用知识和模式 。
大模型之所以具备出众的实力,核心源于其独特的涌现能力:当模型的参数量持续扩容、训练数据的规模不断累积时,模型会突破训练阶段未被刻意设计或植入的能力边界,衍生出诸如逻辑推导、代码编写、多步骤拆解并解决复杂问题等全新的技能。
二、接入大模型
使用大模型的2种方式
在实际开发过程中,我们主要有 2 种途径来使用 AI 大模型,分别是云服务和自部署,各有优缺。
1、云服务
直接使用其他云服务商在云端已部署好的大模型服务,无需自己考虑基础设施(比如服务器、GPU 算力),特点如下:
- 提供纯净的大模型能力和构建应用(智能体)的工具
- 按需付费,无需前期大量基础设施投入
- 随时可用,维护成本低
- 自动更新到最新版本的模型
- 通常具有更完善的安全措施和合规保障
2、自部署
开发者自行在本地或私有云环境部署开源大模型,特点如下:
- 完全控制数据流,更高的数据隐私保障
- 可根据特定需求微调和定制模型
- 无网络延迟,适合对响应速度有严格要求的场景
- 一次性成本较高,需要专业的技术团队维护
- 适合企业级应用和对数据安全有严格要求的场景
接入大模型的 3 种方式
1、AI 应用平台接入
通过云服务商提供的 AI 应用平台来使用 AI 大模型。
2、AI 软件客户端接入
除了平台之外,还可以通过 AI 软件客户端来使用大模型能力
3、程序接入
可以通过编程的方式在自己的项目中调用 AI 大模型,又可以分为 2 种方式:
1. 直接调用 AI 大模型,比如调用 DeepSeek(更原生)
2. 调用 AI 大模型平台创建的应用或智能体(更方便)
三、后端项目初始化
环境准备
安装的 JDK 版本必须是 17 或 21(不能选择其他版本!因为项目使用最新版本的 Spring Boot 3 和 Spring AI 开发框架。)
推荐使用 21 版本,因为支持虚拟线程这个王炸功能。
新建项目
在 IDEA 中新建项目,选择 Spring boot模板,注意需要确保 Server URL (https://start.spring.io/)。
Java 版本选择 21选择 Spring Boot 版本,可以根据自己的需要添加一些依赖,比如 Spring Web 和 Lombok。当然,后续通过修改 Maven 配置添加依赖也是可以的。
点击创建,就得到了一个 Spring Boot 项目,需要等待 Maven 为我们安装依赖。
如果 Lombok 依赖报错的话,可以手动指定 Lombok 的版本,pom.xml 代码如下:
<dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.36</version><optional>true</optional>
</dependency>
整合依赖
可以根据自己的需要,整合一些开发项目常用的依赖。此处我们整合 Hutool 工具库和 Knife4j 接口文档即可。
1、Hutool 工具库
Hutool 是主流的 Java 工具类库,集合了丰富的工具类,涵盖字符串处理、日期操作、文件处理、加解密、反射、正则匹配等常见功能。它的轻量化和无侵入性让开发者能够专注于业务逻辑而不必编写重复的工具代码
在 Maven 的 pom.xml 中添加依赖:
<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.37</version>
</dependency>
2、Knife4j 接口文档
Knife4j 是基于 Swagger 接口文档的增强工具,提供了更加友好的 API 文档界面和功能扩展,例如动态参数调试、分组文档等。它适合用于 Spring Boot 项目中,能够通过简单的配置自动生成接口文档,让开发者和前端快速了解和调试接口,提高写作效率。
1)在 Maven 的 pom.xml 中添加依赖:
<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId><version>4.4.0</version>
</dependency>
2)新建 controller 包用于存放 API 接口,编写一个健康检查接口用于测试接口文档是否正常引入:
@RestController
@RequestMapping("/health")
public class HealthController {@GetMappingpublic String healthCheck() {return "ok";}
}
3)在 application.yml 中追加接口文档配置,扫描 controller 包。这段配置可以从官方文档中复制过来,然后微调即可:
spring:application:name: henxi-ai-agentprofiles:active: local
server:port: 8123servlet:context-path: /api
# springdoc-openapi
springdoc:swagger-ui:path: /swagger-ui.htmltags-sorter: alphaoperations-sorter: alphaapi-docs:path: /v3/api-docsgroup-configs:- group: 'default'paths-to-match: '/**'packages-to-scan: com.example.henxiaiagent.controller
# knife4j
knife4j:enable: truesetting:language: zh_cn
4)启动项目,访问 (http://localhost:8123/api/doc.html) 能够看到接口文档,可以测试调用接口:
四、程序调用 AI 大模型
在实际开发中,有多种方式可以在应用程序中调用 AI 大模型。下面有 4 种主流的接入方式,并通过实例代码展示如何在 Java 项目中实现与 AI 大模型的交互。
1. SDK 接入:使用官方提供的软件开发工具包,最直接的集成方式
2. HTTP 接入:通过 REST API 直接发送 HTTP 请求调用模型
3. Spring AI:基于 Spring 生态系统的 AI 框架,更方便地接入大模型
4. LangChain4j:专注于构建 LLM 应用的 Java 框架,提供丰富的 AI 调用组件
下面所有的示例代码均放置在项目的 `demo.invoke` 包下,方便统一管理和查阅。
1、SDK 接入
SDK(软件开发工具包)是官方提供的最直接的集成方式,通常提供了完善的类型支持和错误处理机制。
1)首先需要按照官方文档安装 SDK:安装 SDK 官方指南
在选择 SDK 版本时,建议在 Maven 仓库查看最新的版本号:Maven中央仓库版本信息
在 pom.xml 中引入依赖:
<dependency><groupId>com.alibaba</groupId><artifactId>dashscope-sdk-java</artifactId><version>2.19.1</version>
</dependency>
2)先在百炼平台申请一个 API Key,注意不要泄露:
3)项目中新建 `demo.invoke` 包,集中存放调用 AI 大模型的示例代码。
为了安全管理 API 密钥,我们创建一个接口类来存储密钥信息(在实际生产环境中,应使用配置文件或环境变量):
public interface TestApiKey {String API_KEY = "你的 API Key";
}
使用 SDK 调用模型的完整示例代码:
// 建议dashscope SDK的版本 >= 2.12.0import java.util.Arrays;
import java.lang.System;import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;public class SdkAiInvoke {public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {Generation gen = new Generation();Message systemMsg = Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();Message userMsg = Message.builder().role(Role.USER.getValue()).content("你是谁?").build();GenerationParam param = GenerationParam.builder()// 若没有配置环境变量,请用百炼API Key将下行替换为:.apiKey("sk-xxx").apiKey(TestApiKey.API_KEY)// 此处以qwen-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models.model("qwen-plus").messages(Arrays.asList(systemMsg, userMsg)).resultFormat(GenerationParam.ResultFormat.MESSAGE).build();return gen.call(param);}public static void main(String[] args) {try {GenerationResult result = callWithMessage();System.out.println(JsonUtils.toJson(result));} catch (ApiException | NoApiKeyException | InputRequiredException e) {// 使用日志框架记录异常信息System.err.println("An error occurred while calling the generation service: " + e.getMessage());}System.exit(0);}
}
4)运行项目,成功看到 AI 的回复:
2、HTTP 接入
对于 SDK 不支持的编程语言或需要更灵活控制的场景,可以直接使用 HTTP 请求调用 AI 大模型的 API。
HTTP 调用的详细说明可参考官方文档:通过 API 调用通义千问
可以利用 AI 将CURL 代码转换为 Java 的 Hutool 工具类网络请求代码。
AI 生成的代码如下,可以自己略作修改:
package com.example.henxiaiagent.demo.invoke;import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;import java.util.HashMap;
import java.util.Map;/*** http 调用AI*/
public class HttpAiInvoke {private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";private static final String API_KEY = TestApiKey.API_KEY;/*** 使用hutool发送HTTP请求调用阿里云DashScope服务* @param systemPrompt 系统提示词* @param userPrompt 用户提示词* @param model 模型名称,默认为qwen-plus* @return 响应结果字符串*/public static String callWithHutool(String systemPrompt, String userPrompt, String model) {// 构建请求体JSONMap<String, Object> requestBody = new HashMap<>();requestBody.put("model", model);// 构建input字段Map<String, Object> input = new HashMap<>();JSONArray messages = new JSONArray();// 添加系统消息JSONObject systemMessage = new JSONObject();systemMessage.put("role", "system");systemMessage.put("content", systemPrompt);messages.add(systemMessage);// 添加用户消息JSONObject userMessage = new JSONObject();userMessage.put("role", "user");userMessage.put("content", userPrompt);messages.add(userMessage);input.put("messages", messages);requestBody.put("input", input);// 构建parameters字段Map<String, Object> parameters = new HashMap<>();parameters.put("result_format", "message");requestBody.put("parameters", parameters);// 发送POST请求HttpResponse response = HttpRequest.post(API_URL).header("Authorization", "Bearer " + API_KEY).header("Content-Type", "application/json").body(JSONUtil.toJsonStr(requestBody)).execute();// 返回响应结果return response.body();}/*** 重载方法,使用默认模型qwen-plus*/public static String callWithHutool(String systemPrompt, String userPrompt) {return callWithHutool(systemPrompt, userPrompt, "qwen-plus");}/*** 主方法,用于测试*/public static void main(String[] args) {try {String result = callWithHutool("You are a helpful assistant.", "你是谁?");System.out.println("Response: " + result);} catch (Exception e) {System.err.println("Error occurred: " + e.getMessage());e.printStackTrace();}}
}
3、Spring AI
Spring AI是 Spring 生态系统的新成员,旨在简化 AI 功能与 Spring 应用的集成。Spring AI 通过提供统一接口、支持集成多种 AI 服务提供商和模型类型、各种 AI 开发常用的特性(比如 RAG 知识库、Tools 工具调用和 MCP 模型上下文协议),简化了 AI 应用开发代码,使开发者能够专注于业务逻辑,提高了开发效率。
- 跨 AI 供应商的可移植 API 支持:适用于聊天、文本转图像和嵌入模型,同时支持同步和流式 API 选项,并可访问特定于模型的功能。
- 支持所有主流 AI 模型供应商:如 Anthropic、OpenAI、微软、亚马逊、谷歌和 Ollama,支持的模型类型包括:聊天补全、嵌入、文本转图像、音频转录、文本转语音
- 结构化输出:将 AI 模型输出映射到 POJO(普通 Java 对象)。
- 支持所有主流向量数据库:如 Apache Cassandra、Azure Cosmos DB、Azure Vector Search、Chroma、Elasticsearch、GemFire、MariaDB、Milvus、MongoDB Atlas、Neo4j、OpenSearch、Oracle、PostgreSQL/PGVector、PineCone、Qdrant、Redis、SAP Hana、Typesense 和 Weaviate。
- 跨向量存储供应商的可移植 API:包括新颖的类 SQL 元数据过滤 API。
- 工具/函数调用:允许模型请求执行客户端工具和函数,从而根据需要访问必要的实时信息并采取行动。
- 可观测性:提供与 AI 相关操作的监控信息。
- 文档 ETL 框架:适用于数据工程场景。
- AI 模型评估工具:帮助评估生成内容并防范幻觉响应。
- Spring Boot 自动配置和启动器:适用于 AI 模型和向量存储。
- ChatClient API:与 AI 聊天模型通信的流式 API,用法类似于 WebClient 和 RestClient API。
- Advisors API:封装常见的生成式 AI 模式,转换发送至语言模型(LLM)和从语言模型返回的数据,并提供跨各种模型和用例的可移植性。
- 支持聊天对话记忆和检索增强生成(RAG)。
Spring AI 默认没有支持所有的大模型(尤其是国产的),更多的是支持兼容 OpenAI API 的大模型的集成。因此,我们如果想要调用阿里系大模型(比如通义千问),推荐直接使用阿里自主封装的 Spring AI Alibaba 框架,它不仅能直接继承阿里系大模型,用起来更方便,而且与标准的 Spring AI 保持兼容。
1)引入依赖:
<dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter</artifactId><version>1.0.0-M6.1</version>
</dependency>
2)编写配置:
spring:application:name: spring-ai-alibaba-qwq-chat-client-exampleai:dashscope:api-key: ${AI_DASHSCOPE_API_KEY}chat:options:model: qwen-plus
3)编写示例代码,注意要注入 `dashscopeChatModel`:
package com.example.henxiaiagent.demo.invoke;import com.alibaba.dashscope.utils.JsonUtils;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.AssistantMessage;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;/*** Spring AI框架 调用AI*/@Componentpublic class SpringAiInvoke implements CommandLineRunner {@Resourceprivate ChatModel dashscopeChatModel;@Overridepublic void run(String... args) throws Exception {AssistantMessage output = dashscopeChatModel.call(new Prompt("你好,我是痕夕")).getResult().getOutput();System.out.println(output.getText());}}
上述代码实现了 CommandLineRunner 接口,我们启动 Spring Boot 项目时,会自动注入大模型 ChatModel 依赖,并且单次执行该类的 run 方法,达到测试的效果。
4、LangChain4j
和 Spring AI 作用一样,LangChain4j 是一个专注于构建基于大语言模型(LLM)应用的 Java 框架,作为知名 AI 框架 LangChain 的 Java 版本,它提供了丰富的工具和抽象层,简化了与 LLM 的交互和应用开发。
1)首先引入依赖:
<dependency><groupId>dev.langchain4j</groupId><artifactId>langchain4j-community-dashscope</artifactId><version>1.0.0-beta2</version>
</dependency>
值得一提的是,LangChain4j 也提供了 Spring Boot Starter,方便在 Spring 项目中使用,最新版本号可以在 Maven中央仓库查询。我们这里由于只是编写 Demo,而且已经引入了 Spring AI 的 Starter,就不再引入 LangChain 的 Starter 了,担心会有冲突。
2)参考 官方文档 来编写示例对话代码,创建了一个 ChatModel 并调用
package com.example.henxiaiagent.demo.invoke;import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.model.chat.ChatLanguageModel;public class LangChainAiInvoke {public static void main(String[] args) {ChatLanguageModel qwenChatModel = QwenChatModel.builder().apiKey(TestApiKey.API_KEY).modelName("qwen-max").build();String answer = qwenChatModel.chat("我是程序员痕夕,这是 AI 超级智能体项目");System.out.println(answer);}
}
最后直接运行 Main 方法进行测试即可。
感觉 Spring AI更优,一方面是它属于 Spring 生态,更主流;另一方面是它简单易用、资源更多,更利于学习,也能满足我们绝大多数 AI 项目的开发需求。
我的源代码在:https://github.com/6zyy6/henxi-ai-agent.git/