java简单实现请求deepseek

news/2025/2/22 22:54:51

1.deepseek的api创建

deepseek官网链接

点击右上API开放平台后找到API keys 创建APIkey:

注意:创建好的apikey只能在创建时可以复制,要保存好

2.java实现请求deepseek

使用springboot+maven

2.1 pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.4.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.demo</groupId>
	<artifactId>deepseek-java</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>deepseek-java</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>21</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<version>RELEASE</version>
			<scope>compile</scope>
		</dependency>

		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20231013</version>
		</dependency>

		<dependency>
			<groupId>com.squareup.okhttp3</groupId>
			<artifactId>okhttp</artifactId>
			<version>4.12.0</version>
		</dependency>


	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>maven-ali</id>
			<url>http://maven.aliyun.com/nexus/content/groups/public//</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
				<updatePolicy>always</updatePolicy>
				<checksumPolicy>fail</checksumPolicy>
			</snapshots>
		</repository>
	</repositories>

	<pluginRepositories>
		<pluginRepository>
			<id>public</id>
			<name>aliyun nexus</name>
			<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
			<releases>
				<enabled>true</enabled>
			</releases>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</pluginRepository>
	</pluginRepositories>

</project>

2.2 json转化文件:

参数可以参考DeepSeek API 文档

java">import org.json.JSONArray;
import org.json.JSONObject;

/**
 * @Description:自定义json转化
 * @Author:
 * @Date: 2025/2/20
 * @Version: v1.0
 */
public class JsonExample {
    /**
     * toJson
     * @param msg 你要输入的内容
     * @param model 模型类型 例如 deepseek-chat、deepseek-reasoner
     * @return 组装好的json数据
     */
    public static String toJson(String msg,String model){
        // 创建JSON对象
        JSONObject json = new JSONObject();

        // 创建messages数组
        JSONArray messages = new JSONArray();

        // 添加第一个message
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("content", "You are a helpful assistant");
        systemMessage.put("role", "system");
        messages.put(systemMessage);

        // 添加第二个message
        JSONObject userMessage = new JSONObject();
        userMessage.put("content", msg);
        userMessage.put("role", "user");
        messages.put(userMessage);

        // 将messages数组添加到JSON对象
        json.put("messages", messages);

        // 添加其他字段
        json.put("model", model);
        json.put("frequency_penalty", 0);
        json.put("max_tokens", 2048);
        json.put("presence_penalty", 0);

        // 添加response_format对象
        JSONObject responseFormat = new JSONObject();
        responseFormat.put("type", "text");
        json.put("response_format", responseFormat);

        // 添加其他字段
        json.put("stop", JSONObject.NULL);
        json.put("stream", false);
        json.put("stream_options", JSONObject.NULL);
        json.put("temperature", 1);
        json.put("top_p", 1);
        json.put("tools", JSONObject.NULL);
        json.put("tool_choice", "none");
        json.put("logprobs", false);
        json.put("top_logprobs", JSONObject.NULL);

        // 控制台打印输出JSON字符串并且使用2个空格进行缩进
       //System.out.println(json.toString(2));
        return json.toString();
    }
}

转化后JSON如下:

java">{
  "messages": [
    {
      "content": "You are a helpful assistant",
      "role": "system"
    },
    {
      "content": "Hi",
      "role": "user"
    }
  ],
  "model": "deepseek-chat",
  "frequency_penalty": 0,
  "max_tokens": 2048,
  "presence_penalty": 0,
  "response_format": {
    "type": "text"
  },
  "stop": null,
  "stream": false,
  "stream_options": null,
  "temperature": 1,
  "top_p": 1,
  "tools": null,
  "tool_choice": "none",
  "logprobs": false,
  "top_logprobs": null
}

2.2 实现类:

java">import okhttp3.*;

import java.io.IOException;

/**
 * @Description:
 * @Author:
 * @Date: 2025/2/20
 * @Version: v1.0
 */
public class MyDeepSeekClient {

    private static final String API_URL = "https://api.deepseek.com/chat/completions"; // 替换为实际的API URL
    private static final String API_KEY = "你的APIkey"; // 替换为实际的API密钥


    public static void main(String[] args) {
        try {
            String json = JsonExample.toJson("你好", "deepseek-chat");
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, json);
            Request request = new Request.Builder()
                    .url(API_URL)//deepseek的API
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .addHeader("Authorization", "Bearer "+API_KEY)//deepseek的API_KEY
                    .build();
            // 异步发送 POST 请求
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        if (response.isSuccessful()) {//判断响应是否成功
                            // 成功
                            System.out.println("状态码: " + response.code());
                            System.out.println("响应体: " + response.body().string());
                        } else {
                            // 失败
                            System.out.println("状态码: " + response.code());
                            System.out.println("响应体: " + response.body().string());
                        }
                    } finally {
                        // 关闭响应体,防止资源泄漏
                        response.close();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输入结果如下:

java">状态码: 200
响应体: {"id":"6d83333a-ac8e-4ebf-9030-dc4e5ec620a3","object":"chat.completion","created":1740040067,"model":"deepseek-chat","choices":[{"index":0,"message":{"role":"assistant","content":"你好!很高兴见到你。有什么我可以帮忙的吗?"},"logprobs":null,"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":11,"total_tokens":20,"prompt_tokens_details":{"cached_tokens":0},"prompt_cache_hit_tokens":0,"prompt_cache_miss_tokens":9},"system_fingerprint":"fp_3a5770e1b4"}

注意事项:

  1. 响应体大小:如果响应体较大,直接调用responseBody.string()可能会占用大量内存。对于大文件或流式数据,可以使用responseBody.byteStream()responseBody.charStream()


http://www.niftyadmin.cn/n/5862822.html

相关文章

科技助力汽车保险迎接行业大变革

随着科技的飞速发展&#xff0c;汽车行业正经历一场前所未有的变革。智能网联、新能源汽车的兴起&#xff0c;以及自动驾驶技术的日益成熟&#xff0c;都为汽车保险行业带来了新的挑战和机遇。本文将探讨汽车保险行业如何利用科技力量&#xff0c;应对行业变革&#xff0c;实现…

Linux6-进程消亡、

一、进程补充 函数指针取别名 typedef void (*tmp) vdoid;//将所有的void &#xff08;*&#xff09;void数据类型取别名为tmp 1.进程消亡&#xff1a; 进程退出&#xff1a; 1.1主函数调 return 0&#xff1b; 1.2调 exit(库函数)\_exit\Exit&#xff08;系统调用&#xff0…

CentOS 7配置YOLOv8环境指南:无显卡版教程 - 幽络源

看本篇教程前请确保Centos7系统已安装配置Python3环境&#xff0c;参考幽络源上一篇文章>CentOS 7安装Python3环境详细指南&#xff1a;从源码编译到PIP配置 步骤1&#xff1a;建立python虚拟环境项目 在home目录下执行如下命令新建虚拟环境python项目 python3 -m venv y…

Java数据结构第十二期:走进二叉树的奇妙世界(一)

专栏&#xff1a;数据结构(Java版) 个人主页&#xff1a;手握风云 目录 一、树型结构 1.1. 树的定义 1.2. 树的基本概念 1.3. 树的表示形式 二、二叉树 2.1. 概念 2.2. 两种特殊的二叉树 2.3. 二叉树的性质 2.4. 二叉树的存储 三、二叉树的基本操作 一、树型结构 1.…

Golang中如何正确close channel

在 Go 语言中&#xff0c;close 操作用于关闭一个 channel&#xff0c;通常是由发送数据的方&#xff08;即发送者&#xff09;来完成。关闭 channel 表明不会再有更多的数据会被发送到该 channel&#xff0c;但是已发送的数据仍然可以被接收。关闭 channel 是 Go 中一种同步机…

开源免费文档翻译工具 可支持pdf、word、excel、ppt

项目介绍 今天给大家推荐一个开源的、超实用的免费文档翻译工具&#xff08;DeeplxFile&#xff09;&#xff0c;相信很多人都有需要翻译文档的时刻&#xff0c;这款工具就能轻松解决你的需求。 它支持多种文档格式翻译&#xff0c;包括 Word、PDF、PPT、Excel &#xff0c;使…

STL介绍1:vector、pair、string、queue、map

一、vector&#xff1a;变长数组、倍增思想 1.常用函数 size()&#xff1a;返回元素个数 empty()&#xff1a;返回是否为空 clear()&#xff1a;清空 front() / bcak() push_back() / pop_back()&#xff1a;尾部插入和删除 2.存储方式 #include<iostream> #incl…

内容中台架构下智能推荐系统的算法优化与分发策略

内容概要 在数字化内容生态中&#xff0c;智能推荐系统作为内容中台的核心引擎&#xff0c;承担着用户需求与内容资源精准匹配的关键任务。其算法架构的优化路径围绕动态特征建模与多模态数据融合展开&#xff0c;通过深度强化学习技术实现用户行为特征的实时捕捉与动态更新&a…