java(spring boot)实现向deepseek/GPT等模型的api发送请求/多轮对话(附源码)

我们再启动应用并获取api密钥后就可以对它发送请求了,但是官方文档对于如何进行多轮对话以及怎么自定义参数并没有说的很清楚,给的模板也没有java的,因此我们需要自己实现。

java 复制代码
import org.json.JSONArray;
import org.json.JSONObject;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class DeepSeekUtil {
    private static final String API_URL = "https://ark.cn-beijing.volces.com/api/v3/chat/completions"; //  API 地址
    private static final String API_KEY = ""; // 请替换为你的 API 密钥

    // 与模型进行交互
    public static String chat(String userMessage, JSONArray messages) {
        // 如果没有传入消息历史,初始化一个空的 JSONArray
        if (messages == null) {
            messages = new JSONArray();
        }

        // 添加用户的消息到对话历史
        messages.put(new JSONObject().put("role", "user").put("content", userMessage));

        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-v3-241226"); // 使用正确的模型名称
        requestBody.put("messages", messages); // 将历史对话传递给 API
        requestBody.put("temperature", 0.7); // 控制生成文本的创意性
        //requestBody.put("max_tokens", 1024); // 最大生成 token 数量,避免生成过长的回答

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(API_URL))
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + API_KEY)
                .POST(HttpRequest.BodyPublishers.ofString(requestBody.toString()))
                .build();

        HttpClient client = HttpClient.newHttpClient();
        try {
            // 发送请求并获取响应
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // 检查响应状态
            if (response.statusCode() != 200) {
                System.out.println("API Response Error: " + response.body());
                return "Error: API responded with status code " + response.statusCode();
            }

            // 从响应中获取 API 返回的内容
            String responseBody = response.body();
            System.out.println("API Response: " + responseBody);

            // 解析 API 响应
            JSONObject jsonResponse = new JSONObject(responseBody);
            JSONArray choices = jsonResponse.getJSONArray("choices");

            // 获取第一个 choice 中的 message 内容
            JSONObject firstChoice = choices.getJSONObject(0);
            JSONObject message = firstChoice.getJSONObject("message");
            String apiReply = message.getString("content");

            // 添加模型回复到对话历史
            messages.put(new JSONObject().put("role", "assistant").put("content", apiReply));

            // 返回 API 的回复
            return apiReply;

        } catch (Exception e) {
            // 出现错误时返回错误消息
            e.printStackTrace(); // 打印详细的错误信息
            return "Error: " + e.getMessage();
        }
    }
}

我们再编写测试类

java 复制代码
 @Test
    void testChat(){
        JSONArray array=new JSONArray();

      String response=DeepSeekUtil.chat("你好",array);
        System.out.println(response);
        String response1=DeepSeekUtil.chat("帮我设计一个演示自由落体的网页",array);
        System.out.println(response1);
    }
相关推荐
咖啡八杯1 小时前
GoF设计模式——解释器模式
java·后端·spring·设计模式
优橙教育1 小时前
5G网优培训 vs Java开发:转行选哪个?
java·开发语言·5g
糖果店的幽灵2 小时前
【DeepAgents 从入门到精通】Context Management 上下文管理
java·人工智能·后端·spring·中间件·langgraph·deepagents
腻害兔3 小时前
【若依项目-产品经理视角】RuoYi-Vue-Pro 源码拆解:字典、短信、邮件、通知——后台系统的“基础设施四件套“!
java·前端·vue.js·产品经理·ai编程
碎光拾影4 小时前
ARM交叉工具链各工具作用及IMX6ULL平台LED+蜂鸣器裸机程序实现
java·开发语言·数据库
Miao121314 小时前
微服务 API 测试实践:海外某民宿平台如何构建模式驱动测试基础设施
java·开发语言
腻害兔5 小时前
【若依项目-产品经理视角】RuoYi-Vue-Pro 源码拆解:支付模块 yudao-module-pay,一个让产品经理都看懂的支付中台设计
java·前端·vue.js·产品经理·ai编程
CRMEB系统商城6 小时前
开源自建还是SaaS订阅?算一笔3年经济账
java·大数据·开发语言·开源
keyipatience7 小时前
线程栈与TLS和线程互斥
java·linux·服务器·开发语言·ubuntu
weixin_408099677 小时前
2026 图片去水印 API 接口完全指南:一键去除图片水印(附 Python/Java/PHP/C# 示例)
java·python·php·图片处理·api调用·图片去水印·石榴智能