| ¶Ô±ÈÐÂÎļþ |
| | |
| | | package com.smartor; |
| | | |
| | | ; |
| | | import com.alibaba.fastjson.JSON; |
| | | import com.alibaba.fastjson.JSONObject; |
| | | import okhttp3.*; |
| | | |
| | | import java.io.IOException; |
| | | import java.util.ArrayList; |
| | | import java.util.HashMap; |
| | | import java.util.List; |
| | | import java.util.Map; |
| | | |
| | | public class DeepSeekApi { |
| | | // æ¿æ¢ä¸ºä½ èªå·±çkey |
| | | private static final String API_KEY = "sk-"; |
| | | private static final String API_URL = "https://api.deepseek.com/v1/chat/completions"; |
| | | |
| | | public static void main(String[] args) { |
| | | String resp = chatCompletion("ç¨Javaåä¸ä¸ªå泡æåº"); |
| | | System.out.println("DeepSeekè¿åç»æï¼\n" + resp); |
| | | } |
| | | |
| | | public static String chatCompletion(String userPrompt) { |
| | | OkHttpClient client = new OkHttpClient(); |
| | | |
| | | // 1. ç»è£
æ¶æ¯ä½ |
| | | List<Map<String, String>> messages = new ArrayList<>(); |
| | | // ç³»ç»è§è²ï¼å¯éï¼ç¨äºè®¾å®AIèº«ä»½ï¼ |
| | | Map<String, String> sysMsg = new HashMap<>(); |
| | | sysMsg.put("role", "system"); |
| | | sysMsg.put("content", "ä½ æ¯ä¸ä¸Javaå¼åå·¥ç¨å¸ï¼åçç®æ´è§è"); |
| | | messages.add(sysMsg); |
| | | // ç¨æ·æé® |
| | | Map<String, String> userMsg = new HashMap<>(); |
| | | userMsg.put("role", "user"); |
| | | userMsg.put("content", userPrompt); |
| | | messages.add(userMsg); |
| | | |
| | | // 2. 请æ±åæ° |
| | | Map<String, Object> requestBody = new HashMap<>(); |
| | | requestBody.put("model", "deepseek-chat"); |
| | | requestBody.put("messages", messages); |
| | | requestBody.put("temperature", 0.7); // éæºæ§0~1ï¼è¶ä½è¶ä¸¥è°¨ |
| | | requestBody.put("max_tokens", 1024); |
| | | |
| | | // 3. æå»ºè¯·æ± |
| | | String jsonBody = JSON.toJSONString(requestBody); |
| | | RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonBody); |
| | | |
| | | Request request = new Request.Builder() |
| | | .url(API_URL) |
| | | .header("Authorization", "Bearer " + API_KEY) |
| | | .header("Content-Type", "application/json") |
| | | .post(body) |
| | | .build(); |
| | | |
| | | // 4. åéè¯·æ± |
| | | try (Response response = client.newCall(request).execute()) { |
| | | if (!response.isSuccessful()) { |
| | | return "请æ±å¤±è´¥ï¼ç¶æç ï¼" + response.code() + "ï¼é误信æ¯ï¼" + response.body().string(); |
| | | } |
| | | String resJson = response.body().string(); |
| | | JSONObject jsonObj = JSON.parseObject(resJson); |
| | | // æåAIåçå
容 |
| | | return jsonObj.getJSONArray("choices") |
| | | .getJSONObject(0) |
| | | .getJSONObject("message") |
| | | .getString("content"); |
| | | } catch (IOException e) { |
| | | e.printStackTrace(); |
| | | return "æ¥å£è°ç¨å¼å¸¸ï¼" + e.getMessage(); |
| | | } |
| | | } |
| | | } |