?近日,國產AI DeepSeek在中國、美國的科技圈受到廣泛關注,甚至被認為是大模型行業的最大“黑馬”。在外網,DeepSeek被不少人稱為“神秘的東方力量”。1月27日,DeepSeek應用登頂蘋果美國地區應用商店免費APP下載排行榜,在美區下載榜上超越了ChatGPT。同日,蘋果中國區應用商店免費榜顯示,DeepSeek成為中國區第一。總之就是deepseek目前比較火,同時也提供了開放平臺,嘗試接入一下,也比較方便,官網每個接口都提供了各種語言的示例代碼,java采用的okhttp,我用httpurlconnection嘗試下
一、獲取 API key
開放平臺地址:DeepSeek
登錄deepseek開放平臺,創建API keys,注意創建的時候復制key,要不然找不到了
新賬號有10元的體驗額度,不足可以充值,10元體驗額度的有效期為1個月
v3和R1的收費標準
1. deepseek-chat 模型優惠期至北京時間 2025 年 2 月 8 日 24:00,期間 API 調用享歷史價格,優惠結束后將按每百萬輸入 tokens 2 元,每百萬輸出 tokens 8 元計費。
2. deepseek-reasoner 模型上線即按每百萬輸入 tokens 4 元,每百萬輸出 tokens 16 元計費。
二、獲取開放API文檔
接口地址:首次調用 API | DeepSeek API Docs
進入接口文檔,提供了對話、補全、模型等接口,我們找一個【對話補全】接口,給了一個上下文,讓他補充說話
三、JAVA調用API文檔
使用java調用API,跟其他接口沒什么區別,方便上手,注意下入參和返回參數就可以,采用json格式。
-----對話上下文
?{ "content": "歡迎加入虛擬電廠", "role": "system" , "name": "muyunfei" },
?{ "content": "你好,虛擬電廠與deepseek結合的方向說一下吧", "role": "user" , "name": "路人甲"}
組裝請求參數:
{"messages": [{"content": "歡迎加入虛擬電廠","role": "system","name": "muyunfei"}, {"content": "你好,虛擬電廠與deepseek結合的方向說一下吧","role": "user","name": "路人甲"}],"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
}
返回數據參數格式:
{"id": "2fe86f3b-6e3b-4e65-b35a-1127c14c8739","object": "chat.completion","created": 1738810567,"model": "deepseek-chat","choices": [{"index": 0,"message": {"role": "assistant","content": "Hello! How can I assist you today? 😊"},"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"}
------------------------------------------------------------------------
--------------------------? ? ? 完整代碼? ? ? ------------------------
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;import net.sf.json.JSONArray;
import net.sf.json.JSONObject;/*** 實現了。。。。。。** @author 牟云飛**<p>Modification History:</p>*<p>Date Author Description</p>*<p>------------------------------------------------------------------</p>*<p>2025年2月4日 牟云飛 新建</p>*/
public class DeepseekTestMain {private static final String DEEPSEEK_API_URL_COMPLETIONS = "https://api.deepseek.com/chat/completions"; // API地址 ——// 對話補全private static final String DEEPSEEK_API_KEY = "換成自己的key"; // 官網申請的api keypublic static void main(String[] args) {DeepseekTestMain test = new DeepseekTestMain();try {test.sendDeepseekChat(DEEPSEEK_API_URL_COMPLETIONS, "虛擬電廠與deepseek結合的方向說一下");} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}/*** 對話補全* * @param mess* @return* @throws IOException*/public String sendDeepseekChat(String deepseekUrl, String context) throws IOException {String result = null;URL url_req = new URL(deepseekUrl);HttpsURLConnection connection = (HttpsURLConnection) url_req.openConnection();// 設置參數connection.setDoOutput(true); // 需要輸出connection.setDoInput(true); // 需要輸入connection.setUseCaches(false); // 不允許緩存connection.setConnectTimeout(60000); // 設置連接超時connection.setReadTimeout(60000); // 設置讀取超時connection.setRequestMethod("POST"); // 設置POST方式連接// 設置請求屬性connection.setRequestProperty("Content-Type", "application/json");connection.setRequestProperty("Accept", "application/json");connection.setRequestProperty("Charset", "UTF-8");// 設置請求頭參數connection.addRequestProperty("Authorization", "Bearer " + DEEPSEEK_API_KEY); // 設置appIdHttpsURLConnection https = (HttpsURLConnection) connection;SSLSocketFactory oldSocketFactory = trustAllHosts(https);HostnameVerifier oldHostnameVerifier = https.getHostnameVerifier();https.setHostnameVerifier(DO_NOT_VERIFY);// 輸入數據String requestData = "{ \"messages\": "+ "[ "+ " { \"content\": \"歡迎加入虛擬電廠\", \"role\": \"system\" , \"name\": \"muyunfei\" }, "+ " { \"content\": \"你好,虛擬電廠與deepseek結合的方向說一下吧\", \"role\": \"user\" , \"name\": \"路人甲\"} "+ "],"+ " \"model\": \"deepseek-chat\","+ " \"frequency_penalty\": 0,"+ " \"max_tokens\": 2048,"+ " \"presence_penalty\": 0,"+ " \"response_format\": {\n \"type\": \"text\"\n },"+ " \"stop\": null,"+ " \"stream\": false,"+ " \"stream_options\": null,"+ " \"temperature\": 1,"+ " \"top_p\": 1,"+ " \"tools\": null,"+ " \"tool_choice\": \"none\","+ " \"logprobs\": false,"+ " \"top_logprobs\": null}";try (OutputStream os = connection.getOutputStream()) {byte[] input = requestData.getBytes("utf-8");os.write(input,0,input.length);}// 輸出數據InputStream in = connection.getInputStream(); // 獲取返回數據BufferedInputStream bis = new BufferedInputStream(in);ByteArrayOutputStream baos = new ByteArrayOutputStream();int c;while (-1 != (c = bis.read())) {baos.write(c);}bis.close();in.close();baos.flush();byte[] data = baos.toByteArray();String responseMsg = new String(data);System.out.println(responseMsg);
// {
// "id": "2fe86f3b-6e3b-4e65-b35a-1127c14c8739",
// "object": "chat.completion",
// "created": 1738810567,
// "model": "deepseek-chat",
// "choices": [{
// "index": 0,
// "message": {
// "role": "assistant",
// "content": "Hello! How can I assist you today? 😊"
// },
// "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"
// }JSONObject jsonObject = JSONObject.fromObject(responseMsg);JSONArray choices = JSONArray.fromObject(jsonObject.get("choices"));// 獲取補全內容,是個數組,多個補全回復多個System.out.println(choices.toString());JSONObject item = JSONObject.fromObject(JSONObject.fromObject(choices.get(0)).get("message"));System.out.println(item.get("content"));// 對JSON作解析return result;}private SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {SSLSocketFactory oldFactory = connection.getSSLSocketFactory();try {SSLContext sc = SSLContext.getInstance("TLS");sc.init(null, trustAllCerts, new java.security.SecureRandom());SSLSocketFactory newFactory = sc.getSocketFactory();connection.setSSLSocketFactory(newFactory);} catch (Exception e) {e.printStackTrace();}return oldFactory;}private TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {public java.security.cert.X509Certificate[] getAcceptedIssuers() {return new java.security.cert.X509Certificate[] {};}public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}} };private HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {public boolean verify(String hostname, SSLSession session) {return true;}};}