简易java调用DeepSeek Api教程

一、请求格式

首先观察官方文档给出的访问api的样例脚本

curl https://api.deepseek.com/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer " \
  -d '{
        "model": "deepseek-chat",
        "messages": [
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Hello!"}
        ],
        "stream": false
      }'

 在这里我们可以看出,我们向https://api.deepseek.com/chat/completions发送了一条请求

请求头包含两个部分:
第一个是Content-Type,也就是请求格式,是application/json
第二个是Authorization,是身份验证信息,由Bearer + DeepSeek给你的Api Key 组成

请求体包含三个部分:
第一个是model,指定调用哪个版本的模型
第二个是message,是你要发送的信息,它是一个对象list,每个对象包含两个属性:
role,表示说话的对象,有system(系统设置)、user(你)、assistant(Deepseek)
content,表示说话的内容
第三个是stream,为true会逐步生成回答,为false就会等回答生成之后一次性响应
对于请求体,我们可以创建一个实体类来表示

package com.example.entity;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@Builder
@NoArgsConstructor  // 无参构造函数
@AllArgsConstructor // 全参构造函数
public class DeepSeekRequest {
    private String model;
    private List messages;

    @Data
    @Builder
    @NoArgsConstructor  // 无参构造函数
    @AllArgsConstructor // 全参构造函数
    public static class Message {
        private String role;
        private String content;
    }
}

同时,我们在java中也学着构建一个这样的请求即可

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        headers.set("Authorization", "Bearer " + apiKey);

        // 构建请求体
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel("deepseek-chat");
        request.setMessages(List.of(new DeepSeekRequest.Message("user", userMessage)));

        // 构建请求
        HttpEntity entity = new HttpEntity<>(request, headers);
        // 参数依次为:请求路径、请求方法、请求、返参格式
        ResponseEntity response = restTemplate.exchange(
                apiUrl, HttpMethod.POST, entity, DeepSeekResponse.class);

二、 返回格式

这是返回的JSON格式

{
  "id": "1dc2ee32-1e2c-4ad3-bfeb-b17b19ad4f78",   //主键
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "这是生成的对话内容。",
        "role": "assistant"
      },
      "logprobs": null
    }
  ],
  "created": 1735541715,
  "model": "deepseek-chat",
  "service_tier": null,
  "system_fingerprint": "fp_f1afce2943",
  "object": "chat.completion",
  "usage": {
    "completion_tokens": 10,
    "prompt_tokens": 5,
    "total_tokens": 15,
    "completion_tokens_details": null,
    "prompt_tokens_details": null
  }
}

 观察一下可以发现我们需要的是content内容,我们想获取就要

获取response的返回体body,
再获取里面的choice,choice里面有一个对象和一个logprobs
再获取choice的第一个属性,也就是那个对象
再获取里面的message
再获取message里面的content

总结就是 

response.getBody().getChoices().get(0).getMessage().getContent();
到了get(0)之后最好设置一个返参的实体类,如下

package com.example.entity;

import lombok.Data;

import java.util.List;

@Data
public class DeepSeekResponse {
    private List choices;

    @Data
    public static class Choice {
        private Message message;

        @Data
        public static class Message {
            private String role;
            private String content;
        }
    }
}

 因此总的代码如下:
controller

package com.example.controller;

import com.example.common.Result;
import com.example.service.DeepSeekService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/deepSeek")
public class DeepSeekController {

    @Resource
    private DeepSeekService deepSeekService;

    @PostMapping("/chat")
    public Result chat(@RequestBody String message) {
        String reply =  deepSeekService.callDeepSeek(message);
        return Result.success(reply);
    }
}

service

package com.example.service;

import com.example.entity.DeepSeekRequest;
import com.example.entity.DeepSeekResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;

import java.util.List;

@Service
public class DeepSeekService {


    private final String apiKey =""; //这里填你自己的api key

    private final String apiUrl="";  //这里填你要调用的api url

    private final RestTemplate restTemplate = new RestTemplate(); //用resttemplate构建请求

    public String chatDeepSeek(String userMessage) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");
        headers.set("Authorization", "Bearer " + apiKey);

        // 构建请求体
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel("deepseek-chat");
        request.setMessages(List.of(new DeepSeekRequest.Message("user", userMessage)));

        // 构建请求
        HttpEntity entity = new HttpEntity<>(request, headers);
        // 参数依次为:请求路径、请求方法、请求、返参格式
        ResponseEntity response = restTemplate.exchange(
                apiUrl, HttpMethod.POST, entity, DeepSeekResponse.class);

        // 解析响应
        if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
            return response.getBody().getChoices().get(0).getMessage().getContent();
        } else {
            return "Failed to call DeepSeek API: " + response.getStatusCode();
        }
    }
}

实体类就是上面那两个,这样只要发送请求,参数是message,就可以获得一条返回的信息

你可能感兴趣的:(学习小本本,java,数据库,开发语言)