DeepSeek-V3 API接入java
时间: 2025-01-13 08:01:26 浏览: 320
### Java 中集成和使用 DeepSeek-V3 API
为了在 Java 项目中集成并调用 DeepSeek-V3 API,可以采用 HTTP 请求的方式发送 JSON 数据到指定 URL 来实现交互。由于官方提供了 Python SDK 并未直接提供针对 Java 的 SDK,因此推荐通过 RESTful 接口形式来完成操作。
#### 准备工作
首先确保已获取有效的 `API_KEY` ,该密钥用于身份验证过程[^1]。
#### 添加依赖库
引入必要的第三方类库支持 HTTP 请求处理以及 JSON 解析功能,在 Maven 项目的 pom.xml 文件内添加如下配置:
```xml
<dependencies>
<!-- Apache HttpClient -->
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<!-- Gson for JSON parsing -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
</dependencies>
```
#### 编写请求逻辑
创建一个新的 Java 类文件命名为 `DeepSeekClient.java` 实现基本的功能封装:
```java
import com.google.gson.JsonObject;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.io.entity.EntityUtils;
public class DeepSeekClient {
private static final String BASE_URL = "https://api.deepseek.com";
private static final String MODEL_NAME = "deepseek-chat";
public static void main(String[] args) throws Exception {
// 构建消息体
JsonObject jsonBody = new JsonObject();
jsonBody.addProperty("model", MODEL_NAME);
JsonArray messages = new JsonArray();
JsonObject systemMessage = new JsonObject();
systemMessage.addProperty("role", "system");
systemMessage.addProperty("content", "You are a helpful assistant.");
messages.add(systemMessage);
JsonObject userMessage = new JsonObject();
userMessage.addProperty("role", "user");
userMessage.addProperty("content", "你好,DeepSeek!");
messages.add(userMessage);
jsonBody.add("messages", messages);
jsonBody.addProperty("stream", false);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost postRequest = new HttpPost(BASE_URL + "/v1/chat/completions");
// 设置头部信息
postRequest.setHeader("Content-Type", "application/json");
postRequest.setHeader("Authorization", "Bearer YOUR_API_KEY_HERE"); // 替换成实际的 API 密钥
// 将构建好的 JSON 对象转换成字符串作为 POST 请求的内容
postRequest.setEntity(new StringEntity(jsonBody.toString()));
try (CloseableHttpResponse response = httpClient.execute(postRequest)) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
```
上述代码实现了向 DeepSeek 发送对话请求,并打印返回的结果。
阅读全文
相关推荐















