DeepSeek Chat
Spring AI支持来自DeepSeek的各种AI语言模型。你可以与DeepSeek语言模型交互,并基于DeepSeek模型创建一个多语言对话助手。
Spring AI supports the various AI language models from DeepSeek. You can interact with DeepSeek language models and create a multilingual conversational assistant based on DeepSeek models.
Prerequisites
你需要为DeepSeek创建一个API密钥才能访问DeepSeek语言模型。
You will need to create an API key with DeepSeek to access DeepSeek language models.
在 DeepSeek registration page 创建账户,并在 API Keys page 生成令牌。
Create an account at DeepSeek registration page and generate a token on the API Keys page.
Spring AI项目定义了一个名为 spring.ai.deepseek.api-key
的配置属性,你应该将其设置为从API密钥页面获得的 API Key
的值。
The Spring AI project defines a configuration property named spring.ai.deepseek.api-key
that you should set to the value of the API Key
obtained from the API Keys page.
你可以在` application.properties
`文件中设置此配置属性:
You can set this configuration property in your application.properties
file:
spring.ai.deepseek.api-key=<your-deepseek-api-key>
为了在处理 API 密钥等敏感信息时增强安全性,您可以使用 Spring 表达式语言 (SpEL) 引用自定义环境变量:
For enhanced security when handling sensitive information like API keys, you can use Spring Expression Language (SpEL) to reference a custom environment variable:
# In application.yml
spring:
ai:
deepseek:
api-key: ${DEEPSEEK_API_KEY}
# In your environment or .env file
export DEEPSEEK_API_KEY=<your-deepseek-api-key>
你也可以在应用程序代码中以编程方式设置此配置:
You can also set this configuration programmatically in your application code:
// Retrieve API key from a secure source or environment variable
String apiKey = System.getenv("DEEPSEEK_API_KEY");
Add Repositories and BOM
Spring AI制品发布在Spring里程碑和快照仓库中。请参阅 Artifact Repositories 部分将这些仓库添加到你的构建系统。
Spring AI artifacts are published in the Spring Milestone and Snapshot repositories. Refer to the Artifact Repositories section to add these repositories to your build system.
为了帮助依赖管理,Spring AI提供了一个BOM(物料清单)以确保在整个项目中使用的Spring AI版本一致。请参阅 Dependency Management 部分将Spring AI BOM添加到你的构建系统。
To help with dependency management, Spring AI provides a BOM (bill of materials) to ensure that a consistent version of Spring AI is used throughout your entire project. Refer to the Dependency Management section to add the Spring AI BOM to your build system.
Auto-configuration
Spring AI为DeepSeek聊天模型提供了Spring Boot自动配置。要启用它,请将以下依赖项添加到项目的Maven pom.xml
文件:
Spring AI provides Spring Boot auto-configuration for the DeepSeek Chat Model.
To enable it, add the following dependency to your project’s Maven pom.xml
file:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-deepseek</artifactId>
</dependency>
或添加到你的Gradle build.gradle
文件。
or to your Gradle build.gradle
file.
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-model-deepseek'
}
|
Refer to the Dependency Management section to add the Spring AI BOM to your build file. |
Chat Properties
Retry Properties
前缀 spring.ai.retry
用作属性前缀,让你配置DeepSeek聊天模型的重试机制。
The prefix spring.ai.retry
is used as the property prefix that lets you configure the retry mechanism for the DeepSeek Chat model.
Property | Description | Default |
---|---|---|
spring.ai.retry.max-attempts |
Maximum number of retry attempts. |
10 |
spring.ai.retry.backoff.initial-interval |
Initial sleep duration for the exponential backoff policy. |
2 sec. |
spring.ai.retry.backoff.multiplier |
Backoff interval multiplier. |
5 |
spring.ai.retry.backoff.max-interval |
Maximum backoff duration. |
3 min. |
spring.ai.retry.on-client-errors |
If false, throws a NonTransientAiException, and does not attempt a retry for |
false |
spring.ai.retry.exclude-on-http-codes |
List of HTTP status codes that should not trigger a retry (e.g. to throw NonTransientAiException). |
empty |
spring.ai.retry.on-http-codes |
List of HTTP status codes that should trigger a retry (e.g. to throw TransientAiException). |
empty |
Connection Properties
前缀 spring.ai.deepseek
用作属性前缀,让你连接到DeepSeek。
The prefix spring.ai.deepseek
is used as the property prefix that lets you connect to DeepSeek.
Property | Description | Default |
---|---|---|
spring.ai.deepseek.base-url |
The URL to connect to |
[role="bare"]https://api.deepseek.com |
spring.ai.deepseek.api-key |
The API Key |
- |
Configuration Properties
前缀 spring.ai.deepseek.chat
是属性前缀,让你配置DeepSeek的聊天模型实现。
The prefix spring.ai.deepseek.chat
is the property prefix that lets you configure the chat model implementation for DeepSeek.
Property | Description | Default |
---|---|---|
spring.ai.deepseek.chat.enabled |
Enables the DeepSeek chat model. |
true |
spring.ai.deepseek.chat.base-url |
Optionally overrides the spring.ai.deepseek.base-url to provide a chat-specific URL |
[role="bare"]https://api.deepseek.com/ |
spring.ai.deepseek.chat.api-key |
Optionally overrides the spring.ai.deepseek.api-key to provide a chat-specific API key |
- |
spring.ai.deepseek.chat.completions-path |
The path to the chat completions endpoint |
/chat/completions |
spring.ai.deepseek.chat.beta-prefix-path |
The prefix path to the beta feature endpoint |
/beta/chat/completions |
spring.ai.deepseek.chat.options.model |
ID of the model to use. You can use either deepseek-coder or deepseek-chat. |
deepseek-chat |
spring.ai.deepseek.chat.options.frequencyPenalty |
Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model’s likelihood to repeat the same line verbatim. |
0.0f |
spring.ai.deepseek.chat.options.maxTokens |
The maximum number of tokens to generate in the chat completion. The total length of input tokens and generated tokens is limited by the model’s context length. |
- |
spring.ai.deepseek.chat.options.presencePenalty |
Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model’s likelihood to talk about new topics. |
0.0f |
spring.ai.deepseek.chat.options.stop |
Up to 4 sequences where the API will stop generating further tokens. |
- |
spring.ai.deepseek.chat.options.temperature |
Which sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or top_p, but not both. |
1.0F |
spring.ai.deepseek.chat.options.topP |
An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature, but not both. |
1.0F |
spring.ai.deepseek.chat.options.logprobs |
Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of the message. |
- |
spring.ai.deepseek.chat.options.topLogprobs |
An integer between 0 and 20 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used. |
- |
你可以为 |
You can override the common |
所有以 |
All properties prefixed with |
Runtime Options
DeepSeekChatOptions.java 提供模型配置,例如要使用的模型、温度、频率惩罚等。
The DeepSeekChatOptions.java provides model configurations, such as the model to use, the temperature, the frequency penalty, etc.
在启动时,可以使用 DeepSeekChatModel(api, options)
构造函数或 spring.ai.deepseek.chat.options.*
属性配置默认选项。
On startup, the default options can be configured with the DeepSeekChatModel(api, options)
constructor or the spring.ai.deepseek.chat.options.*
properties.
在运行时,你可以通过向 Prompt
调用添加新的、请求特定的选项来覆盖默认选项。例如,要覆盖特定请求的默认模型和温度:
At runtime, you can override the default options by adding new, request-specific options to the Prompt
call.
For example, to override the default model and temperature for a specific request:
ChatResponse response = chatModel.call(
new Prompt(
"Generate the names of 5 famous pirates. Please provide the JSON response without any code block markers such as ```json```.",
DeepSeekChatOptions.builder()
.withModel(DeepSeekApi.ChatModel.DEEPSEEK_CHAT.getValue())
.withTemperature(0.8f)
.build()
));
除了模型特定的 DeepSeekChatOptions ,您还可以使用通过 ChatOptionsBuilder#builder() 创建的便携式 ChatOptions 实例。 |
In addition to the model-specific DeepSeekChatOptions, you can use a portable ChatOptions instance, created with the ChatOptionsBuilder#builder(). |
Sample Controller (Auto-configuration)
创建一个新的 Spring Boot 项目,并将 spring-ai-starter-model-deepseek
添加到您的 pom(或 gradle)依赖中。
Create a new Spring Boot project and add the spring-ai-starter-model-deepseek
to your pom (or gradle) dependencies.
在 src/main/resources
目录下添加一个 application.properties
文件,以启用和配置 DeepSeek Chat 模型:
Add an application.properties
file under the src/main/resources
directory to enable and configure the DeepSeek Chat model:
spring.ai.deepseek.api-key=YOUR_API_KEY
spring.ai.deepseek.chat.options.model=deepseek-chat
spring.ai.deepseek.chat.options.temperature=0.8
将 |
Replace the |
这将创建一个 DeepSeekChatModel
实现,您可以将其注入到您的类中。以下是一个简单的 @Controller
类示例,它使用聊天模型进行文本生成。
This will create a DeepSeekChatModel
implementation that you can inject into your class.
Here is an example of a simple @Controller
class that uses the chat model for text generation.
@RestController
public class ChatController {
private final DeepSeekChatModel chatModel;
@Autowired
public ChatController(DeepSeekChatModel chatModel) {
this.chatModel = chatModel;
}
@GetMapping("/ai/generate")
public Map generate(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
return Map.of("generation", chatModel.call(message));
}
@GetMapping("/ai/generateStream")
public Flux<ChatResponse> generateStream(@RequestParam(value = "message", defaultValue = "Tell me a joke") String message) {
var prompt = new Prompt(new UserMessage(message));
return chatModel.stream(prompt);
}
}
Chat Prefix Completion
聊天前缀补全遵循 Chat Completion API,用户提供助手的消息前缀,模型补全消息的其余部分。
The chat prefix completion follows the Chat Completion API, where users provide an assistant’s prefix message for the model to complete the rest of the message.
使用前缀补全时,用户必须确保消息列表中的最后一条消息是 DeepSeekAssistantMessage。
When using prefix completion, the user must ensure that the last message in the messages list is a DeepSeekAssistantMessage.
以下是聊天前缀补全的完整 Java 代码示例。在此示例中,我们将助手的消息前缀设置为 "```python\n",以强制模型输出 Python 代码,并将停止参数设置为 ['’] 以防止模型进行额外的解释。
Below is a complete Java code example for chat prefix completion. In this example, we set the prefix message of the assistant to "``python\n" to force the model to output Python code, and set the stop parameter to ['`’] to prevent additional explanations from the model.
@RestController
public class CodeGenerateController {
private final DeepSeekChatModel chatModel;
@Autowired
public ChatController(DeepSeekChatModel chatModel) {
this.chatModel = chatModel;
}
@GetMapping("/ai/generatePythonCode")
public String generate(@RequestParam(value = "message", defaultValue = "Please write quick sort code") String message) {
UserMessage userMessage = new UserMessage(message);
Message assistantMessage = DeepSeekAssistantMessage.prefixAssistantMessage("```python\\n");
Prompt prompt = new Prompt(List.of(userMessage, assistantMessage), ChatOptions.builder().stopSequences(List.of("```")).build());
ChatResponse response = chatModel.call(prompt);
return response.getResult().getOutput().getText();
}
}
Reasoning Model (deepseek-reasoner)
deepseek-reasoner
是 DeepSeek 开发的一种推理模型。在提供最终答案之前,模型首先生成一个思维链 (CoT) 以提高其响应的准确性。我们的 API 允许用户访问 deepseek-reasoner
生成的 CoT 内容,使他们能够查看、显示和提取它。
The deepseek-reasoner
is a reasoning model developed by DeepSeek. Before delivering the final answer, the model first generates a Chain of Thought (CoT) to enhance the accuracy of its responses. Our API provides users with access to the CoT content generated by deepseek-reasoner
, enabling them to view, display, and distill it.
您可以使用 DeepSeekAssistantMessage
获取 deepseek-reasoner
生成的 CoT 内容。
You can use the DeepSeekAssistantMessage
to get the CoT content generated by deepseek-reasoner
.
public void deepSeekReasonerExample() {
DeepSeekChatOptions promptOptions = DeepSeekChatOptions.builder()
.model(DeepSeekApi.ChatModel.DEEPSEEK_REASONER.getValue())
.build();
Prompt prompt = new Prompt("9.11 and 9.8, which is greater?", promptOptions);
ChatResponse response = chatModel.call(prompt);
// Get the CoT content generated by deepseek-reasoner, only available when using deepseek-reasoner model
DeepSeekAssistantMessage deepSeekAssistantMessage = (DeepSeekAssistantMessage) response.getResult().getOutput();
String reasoningContent = deepSeekAssistantMessage.getReasoningContent();
String text = deepSeekAssistantMessage.getText();
}
Reasoning Model Multi-round Conversation
在对话的每一轮中,模型输出 CoT (reasoning_content) 和最终答案 (content)。在下一轮对话中,前几轮的 CoT 不会连接到上下文中,如下图所示:
In each round of the conversation, the model outputs the CoT (reasoning_content) and the final answer (content). In the next round of the conversation, the CoT from previous rounds is not concatenated into the context, as illustrated in the following diagram:

请注意,如果输入消息序列中包含 reasoning_content 字段,API 将返回 400 错误。因此,您应该在发出 API 请求之前从 API 响应中删除 reasoning_content 字段,如 API 示例所示。
Please note that if the reasoning_content field is included in the sequence of input messages, the API will return a 400 error. Therefore, you should remove the reasoning_content field from the API response before making the API request, as demonstrated in the API example.
public String deepSeekReasonerMultiRoundExample() {
List<Message> messages = new ArrayList<>();
messages.add(new UserMessage("9.11 and 9.8, which is greater?"));
DeepSeekChatOptions promptOptions = DeepSeekChatOptions.builder()
.model(DeepSeekApi.ChatModel.DEEPSEEK_REASONER.getValue())
.build();
Prompt prompt = new Prompt(messages, promptOptions);
ChatResponse response = chatModel.call(prompt);
DeepSeekAssistantMessage deepSeekAssistantMessage = (DeepSeekAssistantMessage) response.getResult().getOutput();
String reasoningContent = deepSeekAssistantMessage.getReasoningContent();
String text = deepSeekAssistantMessage.getText();
messages.add(new AssistantMessage(Objects.requireNonNull(text)));
messages.add(new UserMessage("How many Rs are there in the word 'strawberry'?"));
Prompt prompt2 = new Prompt(messages, promptOptions);
ChatResponse response2 = chatModel.call(prompt2);
DeepSeekAssistantMessage deepSeekAssistantMessage2 = (DeepSeekAssistantMessage) response2.getResult().getOutput();
String reasoningContent2 = deepSeekAssistantMessage2.getReasoningContent();
return deepSeekAssistantMessage2.getText();
}
Manual Configuration
DeepSeekChatModel 实现了 ChatModel
和 StreamingChatModel
,并使用 Low-level DeepSeekApi Client 连接到 DeepSeek 服务。
The DeepSeekChatModel implements the ChatModel
and StreamingChatModel
and uses the Low-level DeepSeekApi Client to connect to the DeepSeek service.
将 spring-ai-deepseek
依赖项添加到您的项目 Maven pom.xml
文件中:
Add the spring-ai-deepseek
dependency to your project’s Maven pom.xml
file:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-deepseek</artifactId>
</dependency>
或添加到你的Gradle build.gradle
文件。
or to your Gradle build.gradle
file.
dependencies {
implementation 'org.springframework.ai:spring-ai-deepseek'
}
|
Refer to the Dependency Management section to add the Spring AI BOM to your build file. |
接下来,创建一个 DeepSeekChatModel
并将其用于文本生成:
Next, create a DeepSeekChatModel
and use it for text generation:
var deepSeekApi = new DeepSeekApi(System.getenv("DEEPSEEK_API_KEY"));
var chatModel = new DeepSeekChatModel(deepSeekApi, DeepSeekChatOptions.builder()
.withModel(DeepSeekApi.ChatModel.DEEPSEEK_CHAT.getValue())
.withTemperature(0.4f)
.withMaxTokens(200)
.build());
ChatResponse response = chatModel.call(
new Prompt("Generate the names of 5 famous pirates."));
// Or with streaming responses
Flux<ChatResponse> streamResponse = chatModel.stream(
new Prompt("Generate the names of 5 famous pirates."));
DeepSeekChatOptions
提供聊天请求的配置信息。 DeepSeekChatOptions.Builder
是一个流式选项构建器。
The DeepSeekChatOptions
provides the configuration information for the chat requests.
The DeepSeekChatOptions.Builder
is a fluent options builder.
Low-level DeepSeekApi Client
DeepSeekApi 是一个用于 DeepSeek API 的轻量级 Java 客户端。
The DeepSeekApi is a lightweight Java client for DeepSeek API.
这是一个简单的代码片段,展示了如何以编程方式使用 API:
Here is a simple snippet showing how to use the API programmatically:
DeepSeekApi deepSeekApi =
new DeepSeekApi(System.getenv("DEEPSEEK_API_KEY"));
ChatCompletionMessage chatCompletionMessage =
new ChatCompletionMessage("Hello world", Role.USER);
// Sync request
ResponseEntity<ChatCompletion> response = deepSeekApi.chatCompletionEntity(
new ChatCompletionRequest(List.of(chatCompletionMessage), DeepSeekApi.ChatModel.DEEPSEEK_CHAT.getValue(), 0.7f, false));
// Streaming request
Flux<ChatCompletionChunk> streamResponse = deepSeekApi.chatCompletionStream(
new ChatCompletionRequest(List.of(chatCompletionMessage), DeepSeekApi.ChatModel.DEEPSEEK_CHAT.getValue(), 0.7f, true));
有关更多信息,请遵循 DeepSeekApi.java 的 JavaDoc。
Follow the DeepSeekApi.java's JavaDoc for further information.
DeepSeekApi Samples
-
DeepSeekApiIT.java 测试提供了一些关于如何使用轻量级库的通用示例。
-
The DeepSeekApiIT.java test provides some general examples of how to use the lightweight library.