Java 实现调用 DeepSeek API

实现效果

在这里插入图片描述

引言

在人工智能技术飞速发展的今天,自然语言处理 (NLP) 作为其重要分支,正逐渐渗透到我们生活的方方面面。DeepSeek 作为一款强大的 NLP 平台,提供了丰富的 API 接口,为开发者构建智能对话系统、实现文本分析与理解等提供了便捷的工具。
本文将带领您深入浅出地了解如何使用 Java 语言调用 DeepSeek API,实现与 DeepSeek 模型的交互。我们将从环境配置、API 调用流程、代码示例等方面进行详细讲解,并结合实际应用场景,帮助您快速掌握 DeepSeek API 的使用技巧,开启智能对话的新篇章。

开发环境

  • JDK (Java Development Kit):推荐 JDK 11 或更高版本
  • IntelliJ IDEA
  • Maven:用于管理项目依赖和构建
  • OkHttp:流行的第三方 HTTP 客户端库
  • hutool工具包

获取Api key

访问DeepSeek官网Api:

在这里插入图片描述

在这里插入图片描述

代码示例

 // DeepSeek API 地址
    private static final String DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions"; // 替换为实际 API 地址

    // 你的 API Key
    private static final String API_KEY = "your_api_key_here"; // 替换为你的 DeepSeek API Key

    public static void main(String[] args) {
        // 构造请求参数
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "deepseek-chat"); // 模型名称

        // 构造 messages 数组
        JSONArray messages = new JSONArray();
        JSONObject message = new JSONObject();
        message.put("role", "user");
        message.put("content", "你好,介绍一下你自己");
        messages.add(message);

        requestBody.put("messages", messages); // 设置 messages
        requestBody.put("temperature", 0.7); // 温度参数
        requestBody.put("max_tokens", 100); // 最大 token 数

        // 发送 POST 请求
        String response = HttpUtil.createPost(DEEPSEEK_API_URL)
                .header("Authorization", "Bearer " + API_KEY) // 添加认证头
                .header("Content-Type", "application/json") // 设置请求头
                .body(requestBody.toString()) // 设置请求体
                .execute().body();

        // 处理响应
        System.out.println("API 响应: " + response);

        // 解析响应 JSON
        JSONObject jsonResponse = JSONObject.parseObject(response);
        String generatedText = jsonResponse.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content");
        System.out.println("生成的文本: " + generatedText);
    }

代码说明:

  1. API 地址:DEEPSEEK_API_URL 是 DeepSeek API 的地址,需要替换为实际的 API 地址。

  2. API Key:API_KEY 是 DeepSeek 提供的认证密钥,替换为你的实际 API Key。

请求参数:

  1. model:指定使用的模型。

  2. messages:对话消息列表,包含角色(role)和内容(content)。

  3. temperature:控制生成文本的随机性。

  4. max_tokens:限制生成文本的最大长度。

请求头:

Authorization:用于身份验证的 Bearer Token。

Content-Type:设置为 application/json。

响应处理:

解析响应 JSON,提取生成的文本内容。

运行结果为:

API 响应: {"choices":[{"message":{"content":"你好!我是 DeepSeek 的智能助手,很高兴为您服务。"}}]}
生成的文本: 你好!我是 DeepSeek 的智能助手,很高兴为您服务。

文章总结

  • 掌握 Java 调用 DeepSeek API 的完整流程

  • 了解 DeepSeek API 的核心功能和应用场景

  • 获得可复用的 Java 代码示例,快速上手开发

  • 激发灵感,探索 DeepSeek API 的更多可能性

让我们一起开启 Java 与 DeepSeek API 的奇妙之旅,共同探索人工智能技术的无限可能!

### 调用本地 DeepSeek API 的代码示例 #### C# 实现方式一:通过 HTTP 请求发送数据 为了在本地环境中调用 DeepSeek API,可以使用 `HttpClient` 类来构建 POST 请求并传递必要的参数。 ```csharp using System; using System.Net.Http; using System.Text; using System.Threading.Tasks; public class DeepSeekClient { private static readonly HttpClient client = new HttpClient(); public async Task<string> CallDeepSeekApiAsync(string apiUrl, string apiKey) { var requestUri = $"{apiUrl}/endpoint"; using (var content = new StringContent( "{\"query\":\"your query\"}", Encoding.UTF8, "application/json")) { client.DefaultRequestHeaders.Add("Authorization", $"Bearer {apiKey}"); HttpResponseMessage response = await client.PostAsync(requestUri, content); response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); return responseBody; } } } ``` 此段代码展示了如何利用 C# 发送带有授权头的 JSON 数据给指定端点[^1]。 #### Python 实现方式二:基于 Requests 库发起请求 对于 Python 用户来说,可以通过安装第三方库 requests 来简化网络通信过程。下面是一个简单的例子: ```python import os import json import requests def call_deepseek_api(api_url, api_key): url = f"{api_url}/endpoint" headers = {"Authorization": f"Bearer {api_key}", 'content-type': 'application/json'} payload = {'query': 'your query'} response = requests.post(url=url, data=json.dumps(payload), headers=headers) if response.status_code == 200: result = response.json() return result raise Exception(f"Error calling API: {response.text}") ``` 这段脚本说明了怎样安全地读取环境变量中的 API key 并将其用于认证目的[^4]。 #### Java 实现最佳实践 当采用 Java 进行开发时,建议遵循某些特定的最佳做法以确保应用程序的安全性和效率。例如,应该避免直接把 API keys 编写入源码文件内;相反,应当借助于外部配置机制如环境变量来进行管理。 ```java import java.io.IOException; import okhttp3.*; public class Main { private final OkHttpClient httpClient = new OkHttpClient().newBuilder().build(); public void callDeepSeek() throws IOException { RequestBody body = RequestBody.create( "{ \"query\": \"your query\" }", MediaType.parse("application/json; charset=utf-8")); Request request = new Request.Builder() .url(System.getenv("DEEPSEEK_API_URL") + "/endpoint") .method("POST", body) .addHeader("Authorization", "Bearer " + System.getenv("DEEPSEEK_API_KEY")) .build(); try (Response response = httpClient.newCall(request).execute()) { if (!response.isSuccessful()) throw new RuntimeException(response.message()); System.out.println(response.body().string()); } } } ``` 上述实例强调了安全性的重要性以及推荐的做法——即不将敏感信息嵌入程序本身而是作为运行期参数提供[^3]。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无语小咪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值