如何使用Java實(shí)現(xiàn)請求deepseek
1.deepseek的api創(chuàng)建
點(diǎn)擊右上API開放平臺后找到API keys 創(chuàng)建APIkey:
注意:創(chuàng)建好的apikey只能在創(chuàng)建時(shí)可以復(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(); // 添加第一個(gè)message JSONObject systemMessage = new JSONObject(); systemMessage.put("content", "You are a helpful assistant"); systemMessage.put("role", "system"); messages.put(systemMessage); // 添加第二個(gè)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個(gè)空格進(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)文章
Resilience4J通過yml設(shè)置circuitBreaker的方法
Resilience4j是一個(gè)輕量級、易于使用的容錯(cuò)庫,其靈感來自Netflix Hystrix,但專為Java 8和函數(shù)式編程設(shè)計(jì),這篇文章主要介紹了Resilience4J通過yml設(shè)置circuitBreaker的方法,需要的朋友可以參考下2022-10-10Java中的線程池如何實(shí)現(xiàn)線程復(fù)用
這篇文章主要介紹了Java中的線程池如何實(shí)現(xiàn)線程復(fù)用問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03SpringBoot項(xiàng)目使用mybatis-plus代碼生成的實(shí)例詳解
mybatis-plus是mybatis的增強(qiáng),不對mybatis做任何改變,涵蓋了代碼生成,自定義ID生成器,快速實(shí)現(xiàn)CRUD,自動(dòng)分頁,邏輯刪除等功能。本文就來講講SpringBoot項(xiàng)目如何使用mybatis-plus實(shí)現(xiàn)代碼生成,需要的可以了解一下2022-10-10Java設(shè)置PDF有序和無序列表的知識點(diǎn)總結(jié)
在本篇文章中小編給大家整理了關(guān)于Java設(shè)置PDF有序和無序列表的知識點(diǎn),需要的朋友們參考下。2019-03-03關(guān)于Maven parent.relativePath說明
Maven中的relativePath用于指定父項(xiàng)目pom.xml的相對路徑,默認(rèn)值為../pom.xml,這個(gè)配置幫助Maven在構(gòu)建時(shí)定位父模塊的位置,確保模塊間的依賴關(guān)系正確,relativePath可以指向本地或遠(yuǎn)程倉庫中的父項(xiàng)目,如果不需要尋找父項(xiàng)目,可以將其設(shè)置為空2024-09-09Java基本數(shù)據(jù)類型族譜與易錯(cuò)點(diǎn)梳理解析
Java有八大基本類型,很多同學(xué)只對經(jīng)常使用的int類型比較了解。有的同學(xué)是剛從C語言轉(zhuǎn)入Java學(xué)習(xí),誤以為兩者的基本數(shù)據(jù)類型完全相同,這也是大錯(cuò)特錯(cuò)的。今天這本Java基本數(shù)據(jù)類型全解析大字典,可以幫助你直接通過目錄找到你想要了解某一種基本數(shù)據(jù)類型2022-01-01Java操作xls替換文本或圖片的功能實(shí)現(xiàn)
這篇文章主要給大家介紹了關(guān)于Java操作xls替換文本或圖片功能實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼講解了文件上傳、文件處理和Excel文件生成,需要的朋友可以參考下2024-12-12