陈昶聿
6 小时以前 061977eba85adcb2a9f81cf81c7c3315c5570945
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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();
        }
    }
}