当前位置: 首页 > news >正文

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

我们再启动应用并获取api密钥后就可以对它发送请求了,但是官方文档对于如何进行多轮对话以及怎么自定义参数并没有说的很清楚,给的模板也没有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();
        }
    }
}

我们再编写测试类

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

相关文章:

  • 进程的介绍--进程状态/切换
  • 【代码审计】-Tenda AC 18 v15.03.05.05 /goform接口文档漏洞挖掘
  • 网站快速收录:如何设置robots.txt文件?
  • tiptap md 编辑器实用场景开发
  • 笔试算法题思路
  • 让浏览器AI起来:基于大模型Agent的浏览器自动化工具
  • 06、ElasticStack系列,第六章:elasticsearch设置密码
  • MinkowskiEngine安装(CUDA11.8+torch2.0.1+RTX4070TI)
  • 挖矿病毒实战分析
  • 题海拾贝:【枚举】P2010 [NOIP 2016 普及组] 回文日期
  • stm32单片机个人学习笔记16(SPI通信协议)
  • Unity游戏制作中的C#基础(1)界面操作基础
  • 25旅游管理研究生复试面试问题汇总 旅游管理专业知识问题很全! 旅游管理复试全流程攻略 旅游管理考研复试真题汇总
  • 谈谈对线程的认识
  • 23.2 HtmlDocument类
  • 算法1-4 数楼梯
  • 007 HBuilderX提示IDE service port disabled. To use CLI Call, open IDE
  • 程序代码篇---Python参数管理
  • Spring统一功能处理:拦截器、响应与异常的统一管理
  • PT8023W 单触控双输出 LED 调光 IC
  • 兴业证券:下半年A股指数稳、结构牛,中国资产重估刚刚开始
  • 上海将完善隔代照料支持措施:建设老幼共享设施、提高科学育儿指导力度
  • 国家话剧院上海演出季7月重启,《大宅门》等5部大戏来沪
  • 讲述“外国货币上的中国故事”,《世界钱币上的中国印记》主题书刊出版发布
  • 确诊前列腺癌后,拜登首次发声
  • “打铁”热邂逅江南水乡,长三角首个国际级铁三赛事有何不同