You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

237 lines
9.7 KiB

1 month ago
package com.dsideal.base.Util;
1 month ago
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import java.io.File;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Stream;
public class CallDeepSeek {
private static final String API_KEY = "sk-44ae895eeb614aa1a9c6460579e322f1"; // 请替换为您的API KEY
private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
/**
* DeepSeek API
*
* @param prompt
* @param listener
*/
public static void callDeepSeekStream(String prompt, SSEListener listener) {
callDeepSeekStream(prompt, listener, null, false);
}
/**
* DeepSeek API
*
* @param prompt
* @param listener
* @param outputPath
* @param saveToFile
*/
public static void callDeepSeekStream(String prompt, SSEListener listener, String outputPath, boolean saveToFile) {
new Thread(() -> {
StringBuilder fullResponse = new StringBuilder();
try {
1 month ago
System.out.println("开始调用DeepSeek API...");
1 month ago
JSONObject jsonPayload = createRequestPayload(prompt);
1 month ago
System.out.println("请求载荷: " + jsonPayload.toString());
1 month ago
HttpClient client = createHttpClient();
java.net.http.HttpRequest request = createHttpRequest(jsonPayload);
1 month ago
System.out.println("发送HTTP请求到: " + API_URL);
1 month ago
CompletableFuture<Void> future = client.sendAsync(request, HttpResponse.BodyHandlers.ofLines())
.thenAccept(response -> {
1 month ago
System.out.println("收到响应,状态码: " + response.statusCode());
1 month ago
handleStreamResponse(response, fullResponse, listener, outputPath, saveToFile);
}).exceptionally(e -> {
1 month ago
System.err.println("请求异常: " + e.getMessage());
1 month ago
listener.onError("请求或处理异常: " + e.getMessage());
e.printStackTrace();
return null;
});
future.join();
} catch (Exception e) {
1 month ago
System.err.println("发生意外错误: " + e.getMessage());
1 month ago
listener.onError("发生意外错误: " + e.getMessage());
e.printStackTrace();
}
}).start();
}
/**
* HTTP
*/
private static JSONObject createRequestPayload(String prompt) {
JSONObject jsonPayload = new JSONObject();
jsonPayload.set("model", "deepseek-chat");
JSONObject message = new JSONObject();
message.set("role", "user");
message.set("content", prompt);
JSONArray messages = new JSONArray();
messages.add(message);
jsonPayload.set("messages", messages);
jsonPayload.set("stream", true);
return jsonPayload;
}
/**
* HTTP
*/
private static HttpClient createHttpClient() {
return HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.build();
}
/**
* HTTP
*/
private static java.net.http.HttpRequest createHttpRequest(JSONObject jsonPayload) {
return java.net.http.HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + API_KEY)
.header("Accept", "text/event-stream")
.POST(java.net.http.HttpRequest.BodyPublishers.ofString(jsonPayload.toString(), StandardCharsets.UTF_8))
.build();
}
/**
*
*/
private static void handleStreamResponse(HttpResponse<Stream<String>> response,
StringBuilder fullResponse,
SSEListener listener,
String outputPath,
boolean saveToFile) {
1 month ago
System.out.println("处理流式响应,状态码: " + response.statusCode());
1 month ago
if (response.statusCode() == 200) {
1 month ago
System.out.println("开始处理SSE数据流...");
1 month ago
response.body().forEach(line -> {
1 month ago
System.out.println("收到SSE行: " + line);
1 month ago
if (line.startsWith("data:")) {
String data = line.substring(5).trim();
1 month ago
System.out.println("解析SSE数据: " + data);
1 month ago
if (!data.equals("[DONE]")) {
try {
JSONObject jsonData = JSONUtil.parseObj(data);
if (jsonData.containsKey("choices")) {
String content = jsonData.getJSONArray("choices")
.getJSONObject(0)
.getJSONObject("delta")
.getStr("content", "");
if (content != null && !content.isEmpty()) {
1 month ago
System.out.println("提取到内容: " + content);
1 month ago
fullResponse.append(content);
listener.onData(content);
}
}
} catch (Exception e) {
System.err.println("解析SSE JSON数据错误: " + data + " \nError: " + e.getMessage());
1 month ago
e.printStackTrace();
1 month ago
}
1 month ago
} else {
System.out.println("收到结束标记 [DONE]");
1 month ago
// 收到[DONE]标记,流处理完成
String responseContent = fullResponse.toString();
System.out.println("流处理完成,总内容长度: " + responseContent.length());
if (saveToFile && outputPath != null) {
FileUtil.writeString(responseContent, new File(outputPath), "UTF-8");
listener.onComplete("内容已成功保存到" + outputPath);
1 month ago
System.out.println("内容已成功保存到" + outputPath);
1 month ago
} else {
listener.onComplete(responseContent);
}
return; // 提前结束处理
1 month ago
}
}
});
1 month ago
System.out.println("SSE数据流处理结束");
1 month ago
} else {
1 month ago
System.err.println("API请求失败状态码: " + response.statusCode());
1 month ago
listener.onError("API请求失败: " + response.statusCode() + " Body: " + response.body().toString());
}
}
public static void main(String[] args) {
String prompt = "你好,你是谁?";
// 使用通用方法
callDeepSeekStream(prompt, new SSEListener() {
@Override
public void onData(String data) {
System.out.print(data);
System.out.flush();
}
@Override
public void onComplete(String fullResponse) {
System.out.println("\n\n完整回复: " + fullResponse);
}
@Override
public void onError(String error) {
System.err.println("错误: " + error);
}
});
}
public interface SSEListener {
void onData(String data);
void onComplete(String fullResponse);
void onError(String error);
}
1 month ago
/**
* DeepSeek API
*
* @param prompt
* @return DeepSeek
*/
public static String callDeepSeek(String prompt) {
try {
JSONObject jsonPayload = createRequestPayload(prompt);
// 设置为非流式响应
jsonPayload.set("stream", false);
HttpClient client = createHttpClient();
java.net.http.HttpRequest request = createHttpRequest(jsonPayload);
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
JSONObject responseJson = JSONUtil.parseObj(response.body());
if (responseJson.containsKey("choices")) {
return responseJson.getJSONArray("choices")
.getJSONObject(0)
.getJSONObject("message")
.getStr("content", "");
}
} else {
System.err.println("DeepSeek API调用失败: " + response.statusCode() + " Body: " + response.body());
return null;
}
} catch (Exception e) {
System.err.println("调用DeepSeek API时出错: " + e.getMessage());
e.printStackTrace();
return null;
}
return null;
}
1 month ago
}