使用java、C#、Python、NodeJs实现DeepSeek API

要使用DeepSeek API文档,可以按照以下操作步骤进行:

一、注册与登录

  1. 访问DeepSeek平台:在浏览器中输入DeepSeek的官方网址,如https://www.deepseek.com/,并访问该网站。
  2. 注册与登录:如果尚未注册,点击注册按钮进行注册,填写相关信息并完成验证。注册成功后,使用用户名和密码登录DeepSeek平台。

二、获取API Key

  1. 进入API Keys页面:登录后,在DeepSeek平台的左侧边栏中找到“API Keys”选项,点击进入。
  2. 创建API Key:在API Keys页面中,点击“创建API Key”按钮,并输入API Key的名称。创建成功后,将显示API Key的值。
  3. 保存API Key:将API Key复制并保存在一个安全且易于访问的地方。请注意,出于安全考虑,将无法通过平台界面再次查看该密钥。如果密钥丢失,需要重新生成一个新的。

三、配置API环境

  1. 选择工具:可以选择使用Apifox或其他API调试工具来配置和调用DeepSeek API。
  2. 设置环境变量:在Apifox中,新建一个HTTP项目,并在项目右上角的“环境管理”中设置服务前置URL为https://api.deepseek.com。然后,添加一个环境变量,命名为API_KEY,其值为上面创建的DeepSeek API的API Key。

四、调用API

  1. 导入cURL:在Apifox中,新建一个接口,并将DeepSeek API文档中的对话API的cURL复制下来,粘贴到接口路径中。Apifox会自动解析cURL并生成相应的接口信息。
  2. 设置Authorization:在解析出来的接口中,点击Headers,然后更改Authorization的参数值,将其更改为Bearer {{API_KEY}}。这样在发送请求时才会携带存储在环境变量中的API_KEY。
  3. 发送请求:将页面右上角的环境管理中的环境切换到“正式环境”,然后点击“发送”按钮发送请求。将收到接口返回的消息,并可以在Body中修改messages里的信息来实现不同的对话。

五、具体调用API(可选)

调用DeepSeek API(或其他任何AI模型的API)通常涉及发送HTTP请求并处理响应。由于DeepSeek的具体API端点和认证机制可能有所不同,以下代码示例将基于通用的REST API调用方式,并假设DeepSeek提供了一个用于生成文本或执行其他任务的端点。

Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class DeepSeekClient {

    private static final String API_URL = "https://api.deepseek.com"; // 假设的API端点
    private static final String API_KEY = "your_api_key_here"; // 替换为你的API密钥

    public static void main(String[] args) {
        try {
            String prompt = "Write a story about a magical forest."; // 示例输入
            String response = callDeepSeekAPI(prompt);
            System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String callDeepSeekAPI(String prompt) throws Exception {
        URL url = new URL(API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置请求方法、头信息等
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", "Bearer " + API_KEY); // 假设使用Bearer Token认证

        // 发送请求体(JSON格式)
        String jsonInputString = "{\"model\":\"deepseek-chat\",\"messages\":[{\"role\":\"system\",\"content\":\"You are a helpful assistant.\"},{\"role\":\"user\",\"content\":\"Hello!\"}],\"stream\":false}";
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        }

        // 读取响应
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine.trim());
            }
            return response.toString();
        }
    }
}
C#
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // 需要安装Newtonsoft.Json NuGet包

class Program
{
    private static readonly string ApiUrl = "https://api.deepseek.com"; // 假设的API端点
    private static readonly string ApiKey = "your_api_key_here"; // 替换为你的API密钥

    static async Task Main(string[] args)
    {
        string prompt = "Write a story about a magical forest."; // 示例输入
        string response = await CallDeepSeekApiAsync(prompt);
        Console.WriteLine(response);
    }

    private static async Task<string> CallDeepSeekApiAsync(string prompt)
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + ApiKey); // 假设使用Bearer Token认证
 
            var json = "{\"model\":\"deepseek-chat\",\"messages\":[{\"role\":\"system\",\"content\":\"You are a helpful assistant.\"},{\"role\":\"user\",\"content\":\"Hello!\"}],\"stream\":false}";
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            var response = await client.PostAsync(ApiUrl, content);
            response.EnsureSuccessStatusCode();

            using (var responseStream = await response.Content.ReadAsStreamAsync())
            using (var reader = new StreamReader(responseStream))
            {
                return await reader.ReadToEndAsync();
            }
        }
    }
}
Python
# Please install OpenAI SDK first: `pip3 install openai`

from openai import OpenAI

client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {"role": "system", "content": "You are a helpful assistant"},
        {"role": "user", "content": "Hello"},
    ],
    stream=False
)

print(response.choices[0].message.content)
Node.js
// Please install OpenAI SDK first: `npm install openai`

import OpenAI from "openai";

const openai = new OpenAI({
        baseURL: 'https://api.deepseek.com',
        apiKey: '<DeepSeek API Key>'
});

async function main() {
  const completion = await openai.chat.completions.create({
    messages: [{ role: "system", content: "You are a helpful assistant." }],
    model: "deepseek-chat",
  });

  console.log(completion.choices[0].message.content);
}

main();

请确保替换示例代码中的API_URLAPI_KEY为DeepSeek提供的实际值,并根据API文档调整请求体格式和认证方式。如果DeepSeek API需要其他类型的认证(如API密钥作为查询参数、基本认证等),请相应地修改代码。

六、参考官方文档

在使用过程中,如果遇到任何问题或需要更详细的参数说明,可以参考DeepSeek的官方API文档。文档中包含了对API的详细介绍、参数说明、示例代码等信息,有助于更好地理解和使用DeepSeek API。

作者:夏子曦

物联沃分享整理
物联沃-IOTWORD物联网 » 使用java、C#、Python、NodeJs实现DeepSeek API

发表回复