This version is still in development and is not considered stable yet. For the latest stable version, please use Spring AI 2.0.2!

DeepSeek Chat

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

You will need to create an API key with DeepSeek to access DeepSeek language models.

Create an account at DeepSeek registration page and generate a token on the API Keys page.

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.

You can set this configuration property in your application.properties file:

spring.ai.deepseek.api-key=<your-deepseek-api-key>

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 artifacts are published in the Spring Milestone and Snapshot repositories. Refer to the Artifact Repositories section to add these repositories to your build system.

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 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>

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

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 4xx client error codes

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

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

https://api.deepseek.com

spring.ai.deepseek.api-key

The API Key

-

Configuration Properties

Enabling and disabling of the chat auto-configurations are now configured via top level properties with the prefix spring.ai.model.chat.

To enable, spring.ai.model.chat=deepseek (It is enabled by default)

To disable, spring.ai.model.chat=none (or any value which doesn’t match deepseek)

This change is done to allow configuration of multiple models.

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 (Removed and no longer valid)

Enables the DeepSeek chat model.

true

spring.ai.model.chat

Enable DeepSeek chat model.

deepseek

spring.ai.deepseek.chat.base-url

Optionally overrides the spring.ai.deepseek.base-url to provide a chat-specific URL

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

spring.ai.deepseek.chat.model

ID of the model to use. You can use deepseek-v4-flash, deepseek-v4-pro, deepseek-chat or deepseek-reasoner.

deepseek-v4-flash

spring.ai.deepseek.chat.frequency-penalty

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.max-tokens

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.presence-penalty

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.stop

Up to 4 sequences where the API will stop generating further tokens.

-

spring.ai.deepseek.chat.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.top-p

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.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.top-logprobs

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.

-

spring.ai.deepseek.chat.thinking.type

Controls the switch between thinking mode and non-thinking mode. When set to enabled, the thinking mode is used; when set to disabled, the non-thinking mode is used.

-

spring.ai.deepseek.chat.reasoning-effort

Controls the reasoning effort level for the DeepSeek model. For normal requests, high is the default; for complex Agent-style requests (such as Claude Code, OpenCode), max is used automatically.

-

spring.ai.deepseek.chat.tool-callbacks

Tool Callbacks to register with the ChatModel.

-

You can override the common spring.ai.deepseek.base-url and spring.ai.deepseek.api-key for the ChatModel implementations. The spring.ai.deepseek.chat.base-url and spring.ai.deepseek.chat.api-key properties, if set, take precedence over the common properties. This is useful if you want to use different DeepSeek accounts for different models and different model endpoints.
All properties prefixed with spring.ai.deepseek.chat can be overridden at runtime by adding a request-specific Runtime Options to the Prompt call.

Runtime Options

The DeepSeekChatOptions.java provides model configurations, such as the model to use, the temperature, the frequency penalty, etc.

On startup, the default options can be configured with the DeepSeekChatModel(api, options) constructor or the spring.ai.deepseek.chat.* properties.

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_V4_PRO.getValue())
            .withTemperature(0.8f)
        .build()
    ));
In addition to the model-specific DeepSeekChatOptions, you can use a portable ChatOptions instance, created with the ChatOptions#builder().

Sample Controller (Auto-configuration)

Create a new Spring Boot project and add the spring-ai-starter-model-deepseek to your pom (or gradle) dependencies.

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.model=deepseek-v4-pro
spring.ai.deepseek.chat.temperature=0.8
Replace the api-key with your DeepSeek credentials.

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);
    }
}

Tool Calling

DeepSeekChatModel supports tool calling. The model can request tool execution but does not run tools itself — Spring AI handles execution.

For most applications, use ChatClient with the auto-registered ToolCallingAdvisor — see Tool Calling. For low-level control where you drive the loop yourself, see ChatModel Tool Calling.

Chat Prefix Completion

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.

When using prefix completion, the user must ensure that the last message in the messages list is an AssistantMessage flagged as a prefix, by setting the DeepSeekChatModel.PREFIX_METADATA_KEY (deepseek.prefix) metadata entry to true.

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 = AssistantMessage.builder()
			.content("```python\\n")
			.properties(Map.of(DeepSeekChatModel.PREFIX_METADATA_KEY, true))
			.build();
		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 support

Models supporting that feature return their CoT content as a ReasoningPart of the AssistantMessage, available through getReasoning() (see Message Parts).

public void deepSeekReasoningExample() {
    DeepSeekChatOptions promptOptions = DeepSeekChatOptions.builder()
            .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 the model
    AssistantMessage assistantMessage = response.getResult().getOutput();
    List<ReasoningPart> reasoning = assistantMessage.getReasoning();
    String text = assistantMessage.getText();
}

Thinking Mode

DeepSeek models support a switch between thinking mode and non-thinking mode. The thinking mode can be controlled through the Thinking option, which accepts Thinking.ENABLED (thinking mode) or Thinking.DISABLED (non-thinking mode). When thinking is disabled, the model does not produce any reasoning content.

public void deepSeekThinkingExample() {
    DeepSeekChatOptions promptOptions = DeepSeekChatOptions.builder()
            .thinking(Thinking.DISABLED)
            .build();
    Prompt prompt = new Prompt("9.11 and 9.8, which is greater?", promptOptions);
    ChatResponse response = chatModel.call(prompt);

    AssistantMessage assistantMessage = response.getResult().getOutput();
    // No reasoning part is produced when thinking is disabled
    List<ReasoningPart> reasoning = assistantMessage.getReasoning();
    String text = assistantMessage.getText();
}

The thinking mode can also be toggled with the enableThinking() and disableThinking() builder convenience methods, or configured globally through the spring.ai.deepseek.chat.thinking.type property.

Reasoning Effort

DeepSeek models let you control the reasoning effort level through the ReasoningEffort option. ReasoningEffort.HIGH is the default for normal requests, while ReasoningEffort.MAX is used automatically for complex Agent-style requests (such as Claude Code, OpenCode).

public void deepSeekReasoningEffortExample() {
    DeepSeekChatOptions promptOptions = DeepSeekChatOptions.builder()
            .reasoningEffort(ReasoningEffort.MAX)
            .build();
    Prompt prompt = new Prompt("9.11 and 9.8, which is greater?", promptOptions);
    ChatResponse response = chatModel.call(prompt);

    AssistantMessage assistantMessage = response.getResult().getOutput();
    List<ReasoningPart> reasoning = assistantMessage.getReasoning();
    String text = assistantMessage.getText();
}

The reasoning effort can also be set with the reasoningEffortHigh() and reasoningEffortMax() builder convenience methods, or configured globally through the spring.ai.deepseek.chat.reasoning-effort property.

Reasoning Model Multi-round Conversation

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:

Multimodal Test Image

Spring AI sends the reasoning of earlier assistant messages back as reasoning_content, which the API ignores when the request carries no tools.

A request that carries tools is different in thinking mode: according to the DeepSeek documentation, every assistant message of the conversation must carry its reasoning_content, and the API may reject the request otherwise. Spring AI replays the reasoning parts of each assistant message as its reasoning_content (see Message Parts), so a tool calling loop driven by ChatClient or by the ToolCallingManager keeps working, streamed or not. A conversation that holds reasoning signed by another provider, for example Anthropic thinking, cannot be continued that way, because such reasoning is not replayed. NOTE: Only the in-memory chat memory repository keeps the message parts. A conversation restored from any other repository has lost its reasoning, so a follow-up request that carries tools in thinking mode does not meet that requirement.

Message Parts

Each choice of a response is a Generation whose AssistantMessage holds the choice as ordered message parts:

DeepSeek field Message part

reasoning_content

ReasoningPart with the reasoning text and no payload

content

TextPart

a tool call

ToolCallPart

The parts follow that order: reasoning, text, tool calls, which is the only order DeepSeek produces them in. A DeepSeek message has one field per kind of content rather than a list of content blocks, and the reasoning that is interleaved with tool calls in thinking mode spans several assistant messages, one per tool call round. A choice whose content is empty has no TextPart, unless it has no other part either, and getText() returns an empty string in both cases.

The returned message is a DeepSeekAssistantMessage, which is deprecated for removal. Its getReasoningContent() and getPrefix() accessors are views over the reasoning parts and the DeepSeekChatModel.PREFIX_METADATA_KEY metadata entry; read those instead.

When an assistant message is sent back, its parts are folded into a single DeepSeek message:

  • the text parts are joined into content;

  • the reasoning parts are joined into reasoning_content, unless another provider signed some of them (for example Anthropic thinking), in which case no reasoning is sent;

  • the ToolCallPart`s become `tool_calls;

  • any other part is not sent.

When streaming, the reasoning and text deltas of each chunk are partial parts stamped with a synthesized index, so that MessageAggregator rebuilds one ReasoningPart and one TextPart. While a tool call streams, each of its argument deltas arrives right away as a partial ToolCallPart, which is only fit for display purposes and is not a tool call (see Streaming Tool Call Arguments). Once the model has finished its tool calls, one more chunk carries them as complete ToolCallPart`s, at the same index as their deltas, and only those are returned by `getToolCalls().

Manual Configuration

The DeepSeekChatModel implements the ChatModel and StreamingChatModel and uses the Low-level DeepSeekApi Client to connect to the DeepSeek service.

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>

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.

Next, create a DeepSeekChatModel and use it for text generation:

DeepSeekApi deepSeekApi = DeepSeekApi.builder()
        .apiKey(System.getenv("DEEPSEEK_API_KEY"))
        .build();
DeepSeekChatOptions options = DeepSeekChatOptions.builder()
        .model(DeepSeekApi.ChatModel.DEEPSEEK_V4_PRO.getValue())
        .temperature(0.4)
        .maxTokens(200)
        .build();
DeepSeekChatModel chatModel = DeepSeekChatModel.builder()
        .deepSeekApi(deepSeekApi)
        .options(options)
        .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."));

The DeepSeekChatOptions provides the configuration information for the chat requests. The DeepSeekChatOptions.Builder is a fluent options builder.

Low-level DeepSeekApi Client

The DeepSeekApi is a lightweight Java client for DeepSeek 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_V4_FLASH.getValue(), 0.7, false));

// Streaming request
Flux<ChatCompletionChunk> streamResponse = deepSeekApi.chatCompletionStream(
    new ChatCompletionRequest(List.of(chatCompletionMessage), DeepSeekApi.ChatModel.DEEPSEEK_V4_FLASH.getValue(), 0.7, true));

chatCompletionStream merges the chunks of a streamed tool call into one chunk. chatCompletionStreamRaw returns the chunks as the server sends them, including every tool call argument delta.

Follow the DeepSeekApi.java's JavaDoc for further information.

DeepSeekApi Samples

  • The DeepSeekApiIT.java test provides some general examples of how to use the lightweight library.