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);
    }
相关推荐
朱一头zcy11 小时前
Java基础复习10:Java网络编程入门、Junit单元测试、反射基本介绍、注解基本介绍、XML基本介绍
java·笔记
AI 编程助手GPT11 小时前
【实战】多模型编程时代已至:Codex+Claude+Gemini 组合拳实战,让 AI 替你写代码
人工智能·gpt·ai·chatgpt·ai编程
user_admin_god11 小时前
Opencode常见问题与优化排查
java·人工智能·自然语言处理·nlp·idea
工作log11 小时前
从 Ubuntu 22.04 到 ROS 2 Humble 完整环境搭建与 Java 控制指南
java·linux·ubuntu
Wenzar_11 小时前
**元宇宙经济中的智能合约与数字资产:基于Solidity的NFT交易平台开发实践**随着元宇宙概念持续升
java·python·区块链·智能合约
Giggle121811 小时前
从零解构一套校园外卖系统:架构设计、技术选型与核心难点剖析
java·运维·微服务
一叶飘零_sweeeet11 小时前
Spring Boot 4.0:云原生 Java 开发的范式革命
java·spring boot·云原生
Devin~Y11 小时前
大厂 Java 面试实战:Spring Boot 微服务 + Redis 缓存 + Kafka 消息 + Kubernetes + RAG(小Y水货翻车记)
java·spring boot·redis·kafka·spring security·jwt·oauth2
朱一头zcy11 小时前
设计模式入门:简单认识单例模式、模板方法、工厂模式、装饰模式、动态代理
java·设计模式
日拱一卒的小田11 小时前
ZYNQ学习笔记1-裸机-PS端中断配置、IO配置及PS/PL AXI交互(2-2)
笔记·学习·microsoft