调用本地部署deepseek



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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值