introduction
DeepSeek has been extremely popular recently. As a big model provided by DeepSeek, it provides powerful natural language processing and other AI functions. By calling its interface, it can realize intelligent dialogue, content generation and other functions in the Spring Boot project. This article will introduce in detail how to call the DeepSeek interface in Spring Boot, and give detailed intervention steps and code examples.
1. Apply for DeepSeek API Key
Before calling the DeepSeek interface, you need to apply for an API Key. This is a credential to access the DeepSeek API, used to verify the requester's identity and permissions.
1) Visit DeepSeek official website:
Open the browser, enter the official website address of DeepSeek (such as /usage), and enter the DeepSeek open platform page.
2) Create API Key:
In the open platform page, find the API keys related options and click to enter the API Key management page. Click the "Create API Key" button and fill in relevant information according to the prompts, such as application name, description, etc. After creation is completed, the system will generate a unique API key and be sure to save it properly, because the page will not be viewed again after closing it.
2. Create Spring Boot Project
Next, we need to create a Spring Boot project to call the DeepSeek interface. Spring Initializr(/) can be used to quickly generate project structures.
1) Visit Spring Initializr:
Open the browser, enter the address of Spring Initializr, and enter the project generation page.
2) Configure project parameters:
- Project: Select project construction tools (such as Maven or Gradle), set project language (Java), Spring Boot version, etc.
- Dependencies: Add necessary dependencies. Since we need to call the HTTP interface of DeepSeek, we need to add
spring-boot-starter-web
rely. In addition, other dependencies can be added as needed, such as log framework (spring-boot-starter-logging
), database connection pool (spring-boot-starter-data-jpa
)wait.
3) Generate project:
After the configuration is complete, click the "Generate" button to generate the project structure. Download the generated project files locally and import them into an IDE (such as IntelliJ IDEA or Eclipse) for development.
3. Configuration
In Spring Boot projects, the ```` file is usually used to configure the relevant parameters of the application. In order to call the DeepSeek interface, we need to add the DeepSeek API Key and request URL in the configuration file.
Add the following configuration:
deepseek: api: key: sk-63************5f # Replace with your DeepSeek API Key url: /chat/completions # DeepSeek API Request URL
4. Write configuration classes
In order to more conveniently manage the configuration information of the DeepSeek API, we can write a configuration class to read itconfiguration in.
import ; import ; import ; @Configuration @Getter public class DeepSeekConfig { @Value("${}") private String apiKey; @Value("${}") private String apiUrl; }
5. Write a request/response model
When calling the DeepSeek interface, we need to define the data structure of the request and response. According to the DeepSeek API documentation, the request body usually contains fields such as model name, message list, and other fields, while the response body contains fields such as generated reply options.
import ; import ; @Data public class DeepSeekRequest { private String model; private List<Message> messages; private boolean stream; @Data public static class Message { private String role; private String content; } } @Data public class DeepSeekResponse { private List<Choice> choices; @Data public static class Choice { private Delta delta; @Data public static class Delta { private String content; } } }
6. Write a service category
The service class is used to encapsulate the process of issuing queries to DeepSeek. We will useRestTemplate
to send HTTP requests and process response results.
import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; @Service public class DeepSeekService { @Autowired private RestTemplate restTemplate; @Autowired private DeepSeekConfig deepSeekConfig; private final ObjectMapper objectMapper = new ObjectMapper(); public String askDeepSeek(String question) throws JsonProcessingException { DeepSeekRequest request = new DeepSeekRequest(); ("deepseek-chat"); (false); List<> messages = ( new ("user", question) ); (messages); HttpHeaders headers = new HttpHeaders(); (MediaType.APPLICATION_JSON); ("Bearer " + ()); HttpEntity<String> entity = new HttpEntity<>((request), headers); UriComponentsBuilder builder = (()); ResponseEntity<String> response = ((), entity, ); if (().is2xxSuccessful()) { DeepSeekResponse deepSeekResponse = ((), ); if (deepSeekResponse != null && () != null && !().isEmpty()) { return ().get(0).getDelta().getContent(); } } return "No valid response from DeepSeek"; } }
7 Writing a controller class
The controller class is used to process HTTP requests and call the service class method to get the DeepSeek response result.
import ; import ; import ; import ; import ; @RestController public class DeepSeekController { @Autowired private DeepSeekService deepSeekService; @GetMapping("/ask") public ResponseEntity<String> askDeepSeek(@RequestParam String question) { try { String response = (question); return (response); } catch (Exception e) { return (500).body("Error occurred while communicating with DeepSeek: " + ()); } } }
8 Testing and Verification
After completing the above steps, we can start the Spring Boot application and test whether the DeepSeek interface is called successfully through tools such as browser or Postman.
1) Start Spring Boot application:
Run in IDE@SpringBootApplication
Main class, observe console output:
2024-02-20T14:30:00.000+08:00 INFO 8080 --- [ restartedMain] : Tomcat started on port(s): 8080 (http)
2) Construct the test request:
Send GET requests using Postman:
GET http://localhost:8080/ask?question=How to learn Spring Boot framework?
3) Verify the normal response:
An AI response should be received in JSON format:
{ "content": "You can start with the following steps when learning Spring Boot... (Special learning suggestions)" }
4) Exception scene test:
- For example: Invalid API Key Test:401 Unauthorized error should be received:
=sk-invalid_key
{ "code": "DEEPSEEK_API_ERROR", "message": "Invalid API Key" }
Summarize
This article introduces how to call the DeepSeek interface in Spring Boot project to implement intelligent dialogue functions. First, you need to apply for the DeepSeek API Key and create a Spring Boot project. Next, configure the API Key and request URL in it, and write a configuration class to manage these configurations. Then, define the request/response model, write the service class to send HTTP requests using RestTemplate and process the response. Finally, write a controller class to process HTTP requests and test to verify whether the interface call is successful. Through these steps, you can easily integrate the DeepSeek big model in Spring Boot project to achieve functions such as intelligent conversation and content generation.
This is the end of this article about the implementation of SpringBoot calling the DeepSeek interface. For more related contents of SpringBoot calling the DeepSeek interface, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!