如何使用Java實(shí)現(xiàn)請求deepseek
1.deepseek的api創(chuàng)建
點(diǎn)擊右上API開放平臺后找到API keys 創(chuàng)建APIkey:



注意:創(chuàng)建好的apikey只能在創(chuàng)建時可以復(fù)制,要保存好
2.java實(shí)現(xiàn)請求deepseek
使用springboot+maven
2.1 pom文件
<?xml version="1.0" encoding="UTF-8"?>
<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.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.demo</groupId>
<artifactId>deepseek-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>deepseek-java</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>maven-ali</id>
<url>http://maven.aliyun.com/nexus/content/groups/public//</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>public</id>
<name>aliyun nexus</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
2.2 json轉(zhuǎn)化文件
參數(shù)可以參考DeepSeek API 文檔
import org.json.JSONArray;
import org.json.JSONObject;
/**
* @Description:自定義json轉(zhuǎn)化
* @Author:
* @Date: 2025/2/20
* @Version: v1.0
*/
public class JsonExample {
/**
* toJson
* @param msg 你要輸入的內(nèi)容
* @param model 模型類型 例如 deepseek-chat、deepseek-reasoner
* @return 組裝好的json數(shù)據(jù)
*/
public static String toJson(String msg,String model){
// 創(chuàng)建JSON對象
JSONObject json = new JSONObject();
// 創(chuàng)建messages數(shù)組
JSONArray messages = new JSONArray();
// 添加第一個message
JSONObject systemMessage = new JSONObject();
systemMessage.put("content", "You are a helpful assistant");
systemMessage.put("role", "system");
messages.put(systemMessage);
// 添加第二個message
JSONObject userMessage = new JSONObject();
userMessage.put("content", msg);
userMessage.put("role", "user");
messages.put(userMessage);
// 將messages數(shù)組添加到JSON對象
json.put("messages", messages);
// 添加其他字段
json.put("model", model);
json.put("frequency_penalty", 0);
json.put("max_tokens", 2048);
json.put("presence_penalty", 0);
// 添加response_format對象
JSONObject responseFormat = new JSONObject();
responseFormat.put("type", "text");
json.put("response_format", responseFormat);
// 添加其他字段
json.put("stop", JSONObject.NULL);
json.put("stream", false);
json.put("stream_options", JSONObject.NULL);
json.put("temperature", 1);
json.put("top_p", 1);
json.put("tools", JSONObject.NULL);
json.put("tool_choice", "none");
json.put("logprobs", false);
json.put("top_logprobs", JSONObject.NULL);
// 控制臺打印輸出JSON字符串并且使用2個空格進(jìn)行縮進(jìn)
//System.out.println(json.toString(2));
return json.toString();
}
}
轉(zhuǎn)化后JSON如下:
{
"messages": [
{
"content": "You are a helpful assistant",
"role": "system"
},
{
"content": "Hi",
"role": "user"
}
],
"model": "deepseek-chat",
"frequency_penalty": 0,
"max_tokens": 2048,
"presence_penalty": 0,
"response_format": {
"type": "text"
},
"stop": null,
"stream": false,
"stream_options": null,
"temperature": 1,
"top_p": 1,
"tools": null,
"tool_choice": "none",
"logprobs": false,
"top_logprobs": null
}2.2 實(shí)現(xiàn)類
import okhttp3.*;
import java.io.IOException;
/**
* @Description:
* @Author:
* @Date: 2025/2/20
* @Version: v1.0
*/
public class MyDeepSeekClient {
private static final String API_URL = "https://api.deepseek.com/chat/completions"; // 替換為實(shí)際的API URL
private static final String API_KEY = "你的APIkey"; // 替換為實(shí)際的API密鑰
public static void main(String[] args) {
try {
String json = JsonExample.toJson("你好", "deepseek-chat");
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, json);
Request request = new Request.Builder()
.url(API_URL)//deepseek的API
.method("POST", body)
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Bearer "+API_KEY)//deepseek的API_KEY
.build();
// 異步發(fā)送 POST 請求
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
if (response.isSuccessful()) {//判斷響應(yīng)是否成功
// 成功
System.out.println("狀態(tài)碼: " + response.code());
System.out.println("響應(yīng)體: " + response.body().string());
} else {
// 失敗
System.out.println("狀態(tài)碼: " + response.code());
System.out.println("響應(yīng)體: " + response.body().string());
}
} finally {
// 關(guān)閉響應(yīng)體,防止資源泄漏
response.close();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
輸入結(jié)果如下:
狀態(tài)碼: 200
響應(yīng)體: {"id":"6d83333a-ac8e-4ebf-9030-dc4e5ec620a3","object":"chat.completion","created":1740040067,"model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"你好!很高興見到你。有什么我可以幫忙的嗎?"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":11,"total_tokens":20,"prompt_tokens_details":{"cached_tokens":0},"prompt_cache_hit_tokens":0,"prompt_cache_miss_tokens":9},"system_fingerprint":"fp_3a5770e1b4"}
注意事項(xiàng):
響應(yīng)體大?。喝绻憫?yīng)體較大,直接調(diào)用responseBody.string()可能會占用大量內(nèi)存。對于大文件或流式數(shù)據(jù),可以使用responseBody.byteStream()或responseBody.charStream()。
到此這篇關(guān)于如何使用Java實(shí)現(xiàn)請求deepseek的文章就介紹到這了,更多相關(guān)Java請求deepseek內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot使用Cache集成Redis做緩存的保姆級教程
Spring Cache是Spring框架提供的一個緩存抽象層,它簡化了緩存的使用和管理,Spring Cache默認(rèn)使用服務(wù)器內(nèi)存,并無法控制緩存時長,查找緩存中的數(shù)據(jù)比較麻煩,本文已常用的Redis作為緩存中間件作為示例,詳細(xì)講解項(xiàng)目中如何使用Cache提高系統(tǒng)性能,需要的朋友可以參考下2025-01-01
SpringBoot如何統(tǒng)一清理數(shù)據(jù)
這篇文章主要介紹了SpringBoot如何統(tǒng)一清理數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
詳解Kotlin:forEach也能break和continue
這篇文章主要介紹了詳解Kotlin:forEach也能break和continue的相關(guān)資料,需要的朋友可以參考下2017-06-06
Java使用Request獲取請求參數(shù)的通用方式詳解
這篇文章主要給大家介紹了關(guān)于Java使用Request獲取請求參數(shù)的通用方式,在Java后端開發(fā)中第一步就是獲取前端傳過來的請求參數(shù),文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01
淺談SpringBoot在使用測試的時候是否需要@RunWith
本文主要介紹了淺談SpringBoot在使用測試的時候是否需要@RunWith,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01
java正則表達(dá)式判斷強(qiáng)密碼和隨機(jī)生成強(qiáng)密碼代碼示例
這篇文章主要給大家介紹了關(guān)于java正則表達(dá)式判斷強(qiáng)密碼和隨機(jī)生成強(qiáng)密碼的相關(guān)資料,最近需要一個密碼強(qiáng)度正則表達(dá)式在用戶注冊時校驗(yàn)用戶密碼強(qiáng)度,需要的朋友可以參考下2023-08-08

