import okhttp3.*;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class DeepSeekClient {
private static final String BASE_URL = "http://localhost:11434/v1/chat/completions";
private static final OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.build();
public static String getDeepSeekResponse(String model, String question, int maxTokens) throws JSONException {
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);
}
assert response.body() != null;
String responseBody = response.body().string();
JSONObject responseJson = new JSONObject(responseBody);
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);
}
}