java简单实现请求deepseek

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 文档

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如下:

{
  "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 实现类:

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

输入结果如下:

状态码: 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()

### Java 实现 DeepSeek 数据生成集成 为了实现Java应用程序与DeepSeek的数据生成集成,可以采用RESTful API的方式进行交互。这涉及到构建HTTP请求来发送指令给DeepSeek服务端,并接收返回的结果。 #### 准备工作 确保已经具备了必要的前置条件: - 完整安装并配置好Java开发环境。 - 获取到用于访问DeepSeek API的有效密钥和API地址[^4]。 #### 构建 HTTP 请求 下面是一个简单的例子展示怎样利用`HttpURLConnection`类发起POST请求DeepSeek服务器获取数据生成的服务支持。此过程通常包括设置URL路径、方法类型以及必要参数等步骤。 ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class DeepSeekIntegration { private static final String DEEPSEEK_API_URL = "https://api.deepseek.example.com/generate"; private static final String AUTH_TOKEN = "your_auth_token_here"; public static void main(String[] args) { try { URL url = new URL(DEEPSEEK_API_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求属性 conn.setRequestMethod("POST"); conn.setRequestProperty("Authorization", "Bearer " + AUTH_TOKEN); conn.setRequestProperty("Content-Type", "application/json; utf-8"); conn.setDoOutput(true); // 发送请求体 String jsonInputString = "{\"prompt\":\"Generate a JSON response\",\"max_tokens\":50}"; try(OutputStream os = conn.getOutputStream()) { byte[] input = jsonInputString.getBytes("utf-8"); os.write(input, 0, input.length); } int code = conn.getResponseCode(); System.out.println("Response Code : " + code); // 处理响应... } catch (Exception e) { e.printStackTrace(); } } } ``` 这段代码展示了如何向指定的DeepSeek API endpoint发出带有认证信息和其他所需参数的POST请求。注意替换示例中的`DEEPSEEK_API_URL`和`AUTH_TOKEN`为实际使用的值[^3]。 对于更复杂的场景,比如异步调用或者处理更大的负载量,则可能需要考虑引入第三方库如OkHttp或Apache HttpClient简化网络通信逻辑;同时也可以探索其他高级特性例如错误重试机制、超时控制等功能提升系统的健壮性和性能[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值