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();
|
}
|
}
|
}
|