如何使用Java實現(xiàn)請求deepseek
1.deepseek的api創(chuàng)建
點擊右上API開放平臺后找到API keys 創(chuàng)建APIkey:
注意:創(chuàng)建好的apikey只能在創(chuàng)建時可以復制,要保存好
2.java實現(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轉化文件
參數(shù)可以參考DeepSeek API 文檔
import org.json.JSONArray; import org.json.JSONObject; /** * @Description:自定義json轉化 * @Author: * @Date: 2025/2/20 * @Version: v1.0 */ public class JsonExample { /** * toJson * @param msg 你要輸入的內容 * @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個空格進行縮進 //System.out.println(json.toString(2)); return json.toString(); } }
轉化后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 實現(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"; // 替換為實際的API URL private static final String API_KEY = "你的APIkey"; // 替換為實際的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()) {//判斷響應是否成功 // 成功 System.out.println("狀態(tài)碼: " + response.code()); System.out.println("響應體: " + response.body().string()); } else { // 失敗 System.out.println("狀態(tài)碼: " + response.code()); System.out.println("響應體: " + response.body().string()); } } finally { // 關閉響應體,防止資源泄漏 response.close(); } } }); } catch (Exception e) { e.printStackTrace(); } } }
輸入結果如下:
狀態(tài)碼: 200
響應體: {"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"}
注意事項:
響應體大小:如果響應體較大,直接調用responseBody.string()可能會占用大量內存。對于大文件或流式數(shù)據(jù),可以使用responseBody.byteStream()或responseBody.charStream()。
到此這篇關于如何使用Java實現(xiàn)請求deepseek的文章就介紹到這了,更多相關Java請求deepseek內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Resilience4J通過yml設置circuitBreaker的方法
Resilience4j是一個輕量級、易于使用的容錯庫,其靈感來自Netflix Hystrix,但專為Java 8和函數(shù)式編程設計,這篇文章主要介紹了Resilience4J通過yml設置circuitBreaker的方法,需要的朋友可以參考下2022-10-10SpringBoot項目使用mybatis-plus代碼生成的實例詳解
mybatis-plus是mybatis的增強,不對mybatis做任何改變,涵蓋了代碼生成,自定義ID生成器,快速實現(xiàn)CRUD,自動分頁,邏輯刪除等功能。本文就來講講SpringBoot項目如何使用mybatis-plus實現(xiàn)代碼生成,需要的可以了解一下2022-10-10