import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* @ClassName: DeepSeekClient
* @Description:
* @Author: 张小辉
* @Date: 2025-02-06
* @Version: 1.0
**/
public class DeepSeekClient {
private static final String BASE_URL = "http://localhost:11434/v1/chat/completions";
// OkHttpClient 配置
private static final OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS) // 连接超时 60s
.readTimeout(120, TimeUnit.SECONDS) // 读取超时 120s
.writeTimeout(60, TimeUnit.SECONDS) // 写入超时 60s
.build();
// 发送请求并返回 DeepSeek 回复的 content
public static String getDeepSeekResponse(String model, String question, int maxTokens) throws JSONException {
// 创建 JSON 请求体
JSONObject message = new JSONObject();
message.put("role", "user");
message.put("content", question);
JSONArray messages = new JSONArray();
messages.put(message);
JSONObject json = new JSONObject();
json.put("model", model);
json.put("messages", messages);
json.put("max_tokens", maxTokens);
RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString());
Request request = new Request.Builder().url(BASE_URL).post(body).build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("请求失败: " + response);
}
// 解析返回的 JSON
assert response.body() != null;
String responseBody = response.body().string();
JSONObject responseJson = new JSONObject(responseBody);
// 检查 'choices' 数组是否为空或格式有误
if (responseJson.has("choices") && responseJson.getJSONArray("choices").length() > 0) {
return responseJson.getJSONArray("choices")
.getJSONObject(0)
.getJSONObject("message")
.getString("content");
} else {
return "没有得到有效的回答。";
}
} catch (IOException e) {
e.printStackTrace();
return "请求失败:" + e.getMessage();
}
}
// 测试
public static void main(String[] args) throws JSONException {
String model = "deepseek-r1:8b";
String question = "你好,能介绍一下自己吗?";
int maxTokens = 100;
String answer = getDeepSeekResponse(model, question, maxTokens);
System.out.println("DeepSeek 回复: " + answer);
}
}
调用本地部署deepseek
最新推荐文章于 2025-04-02 17:33:50 发布