Java调用大模型API实战指南
文章目录
前言
随着大语言模型(如 OpenAI、DeepSeek、通义千问等)的发展,我们可以很方便地用 API 接口调用这些强大的智能助手。在 Java 项目中调用这些模型,可以实现智能问答、代码生成、摘要提取等功能。
参考 DeepSeek 官网文档:https://api-docs.deepseek.com/zh-cn/
调用大模型的流程概述和基本原理
流程概述:
- 步骤 1:选择合适的大模型 API
- 步骤 2:获取 API 访问密钥(API Key)
- 步骤 3:配置 Java 项目依赖
- 步骤 4:编写 Java 调用代码
- 步骤 5:处理 API 响应并展示结果
基本原理:
绝大多数大模型服务商(如 OpenAI、DeepSeek、阿里、百度、讯飞等)都提供标准的 HTTP RESTful API。我们通过 POST 请求向这些接口发送问题(以 JSON 格式表示),然后接收并解析模型的回答。
获取 DeepSeek 的 API key
Java 实现调用大模型 API 的Demo
一、在 Maven 项目中添加以下依赖:
<dependencies> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.12.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.32</version> </dependency></dependencies>
二、Java 完整代码:
public class DeepSeekChatExample { private static final String API_KEY = \"sk-cvvd6dc3ce5f4aeb97c015106e8996d5\"; // 写自己的! private static final String BASE_URL = \"https://api.deepseek.com/v1/chat/completions\"; public static void main(String[] args) throws IOException { OkHttpClient client = new OkHttpClient.Builder() .readTimeout(Duration.ofSeconds(60)) // 不设置容易超时 .build(); // 构建 messages 数组 JSONArray messages = new JSONArray(); JSONObject userMsg = new JSONObject(); userMsg.put(\"role\", \"user\"); userMsg.put(\"content\", \"给我用java快速排序算法的代码\"); messages.add(userMsg); // 构建请求体 JSONObject requestBody = new JSONObject(); requestBody.put(\"model\", \"deepseek-chat\"); requestBody.put(\"messages\", messages); requestBody.put(\"stream\", false); // 构建 HTTP 请求 Request request = new Request.Builder() .url(BASE_URL) .addHeader(\"Authorization\", \"Bearer \" + API_KEY) .addHeader(\"Content-Type\", \"application/json\") .post(RequestBody.create( requestBody.toJSONString(), MediaType.parse(\"application/json\"))) .build(); // 发送请求 try (Response response = client.newCall(request).execute()) { if (response.isSuccessful() && response.body() != null) { String responseBody = response.body().string(); JSONObject jsonResponse = JSONObject.parseObject(responseBody); String content = jsonResponse .getJSONArray(\"choices\") .getJSONObject(0) .getJSONObject(\"message\") .getString(\"content\"); System.out.println(content); } else { System.err.println(\"Request failed: \" + response.code() + \" \" + response.message()); } } }}
效果展示:
进阶扩展建议
- 支持上下文对话:将前几轮消息一并传给
messages
数组,构造多轮对话。 - 接入到 SpringBoot 服务:将调用封装为 Service,作为 REST 接口提供。
- 流式响应支持:将
stream
设为 true,实现分段读取效果(如聊天窗口)。