Skip to content

party model integration tutorial-DeepSeek

This topic describes how to call DeepSeek models on Alibaba Cloud Model Studio through the OpenAI-compatible API or the DashScope SDK.

Getting started

deepseek-v4-pro is the latest model in the DeepSeek series and delivers top-tier performance across coding, math, and general tasks. You can use the enable_thinking parameter to switch between thinking and non-thinking modes. The following example calls deepseek-v4-pro in thinking mode.

Before you begin, get an API key and export it as an environment variable. If you call the model through an SDK, install the OpenAI or DashScope SDK.

OpenAI compatible

Note

The enable_thinking parameter is not part of the standard OpenAI API. In the OpenAI Python SDK, pass it through extra_body. In the Node.js SDK, pass it as a top-level parameter. The reasoning_effort parameter is a standard OpenAI parameter that you can pass directly as a top-level parameter.

Python

Sample code

HELPCODEESCAPE-python
from openai import OpenAI
import os


client = OpenAI(
    # If the environment variable is not set, replace it with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "Who are you"}]
completion = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=messages,
    # Set enable_thinking in extra_body to enable thinking mode
    extra_body={"enable_thinking": True},
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # Full thinking process
answer_content = ""  # Full response
is_answering = False  # Indicates whether the response phase has started
print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")

for chunk in completion:
    if not chunk.choices:
        print("\n" + "=" * 20 + "Token usage" + "=" * 20 + "\n")
        print(chunk.usage)
        continue

    delta = chunk.choices[0].delta

    # Collect only the thinking content
    if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
        if not is_answering:
            print(delta.reasoning_content, end="", flush=True)
        reasoning_content += delta.reasoning_content

    # Start replying when content is received
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "Full response" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

Response

HELPCODEESCAPE-plaintext
====================Thinking process====================

We are asked: "Who are you". I need to respond as a helpful assistant. I should introduce myself as an AI assistant. Keep it simple and friendly.
====================Full response====================

I'm an AI assistant! I'm here to help you with questions, tasks, or just to chat. How can I assist you today?
====================Token usage====================

CompletionUsage(completion_tokens=238, prompt_tokens=5, total_tokens=243, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=93, rejected_prediction_tokens=None), prompt_tokens_details=None)

Node.js

Sample code

HELPCODEESCAPE-nodejs
import OpenAI from "openai";
import process from 'process';

// Initialize the OpenAI client
const openai = new OpenAI({
    // If the environment variable is not set, replace it with your Model Studio API key: apiKey: "sk-xxx"
    apiKey: process.env.DASHSCOPE_API_KEY,
    baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1'
});

let reasoningContent = ''; // Full thinking process
let answerContent = ''; // Full response
let isAnswering = false; // Indicates whether the response phase has started

async function main() {
    try {
        const messages = [{ role: 'user', content: 'Who are you' }];

        const stream = await openai.chat.completions.create({
            model: 'deepseek-v4-pro',
            messages,
            // Note: In the Node.js SDK, non-standard parameters such as enable_thinking are passed as top-level properties and do not need to be placed in extra_body.
            enable_thinking: true,
            stream: true,
            stream_options: {
                include_usage: true
            },
        });

        console.log('\n' + '='.repeat(20) + 'Thinking process' + '='.repeat(20) + '\n');

        for await (const chunk of stream) {
            if (!chunk.choices?.length) {
                console.log('\n' + '='.repeat(20) + 'Token usage' + '='.repeat(20) + '\n');
                console.log(chunk.usage);
                continue;
            }

            const delta = chunk.choices[0].delta;

            // Collect only the thinking content
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // Start replying when content is received
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + 'Full response' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

Response

HELPCODEESCAPE-plaintext
====================Thinking process====================

We are asked: "Who are you". I need to respond as a helpful assistant. I should introduce myself as an AI assistant. Keep it simple and friendly.
====================Full response====================

I'm an AI assistant! I'm here to help you with questions, tasks, or just to chat. How can I assist you today?
====================Token usage====================

{
  prompt_tokens: 5,
  completion_tokens: 243,
  total_tokens: 248,
  completion_tokens_details: { reasoning_tokens: 83 }
}

HTTP

Sample code

curl

HELPCODEESCAPE-curl
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "deepseek-v4-pro",
    "messages": [
        {
            "role": "user",
            "content": "Who are you"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true
}'

DashScope

Python

Sample code

HELPCODEESCAPE-python
import os
import dashscope
from dashscope import Generation

dashscope.base_http_api_url = "https://dashscope.aliyuncs.com/api/v1"

# Initialize the request parameters
messages = [{"role": "user", "content": "Who are you?"}]

completion = Generation.call(
    # If the environment variable is not set, replace it with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="deepseek-v4-pro",
    messages=messages,
    result_format="message",  # Set the result format to message
    enable_thinking=True,
    stream=True,              # Enable streaming output
    incremental_output=True,  # Enable incremental output
)

reasoning_content = ""  # Full thinking process
answer_content = ""     # Full response
is_answering = False    # Indicates whether the response phase has started

print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")

for chunk in completion:
    message = chunk.output.choices[0].message
    # Collect only the thinking content
    if "reasoning_content" in message:
        if not is_answering:
            print(message.reasoning_content, end="", flush=True)
        reasoning_content += message.reasoning_content

    # Start replying when content is received
    if message.content:
        if not is_answering:
            print("\n" + "=" * 20 + "Full response" + "=" * 20 + "\n")
            is_answering = True
        print(message.content, end="", flush=True)
        answer_content += message.content

print("\n" + "=" * 20 + "Token usage" + "=" * 20 + "\n")
print(chunk.usage)

Response

HELPCODEESCAPE-plaintext
====================Thinking process====================

We are asked: "Who are you". I need to respond as a helpful assistant. I should introduce myself as an AI assistant. Keep it simple and friendly.
====================Full response====================

I'm an AI assistant! I'm here to help you with questions, tasks, or just to chat. How can I assist you today?
====================Token usage====================

{"input_tokens": 6, "output_tokens": 240, "total_tokens": 246, "output_tokens_details": {"reasoning_tokens": 92}​}

Java

Sample code

Important

Use DashScope Java SDK version 2.19.4 or later.

HELPCODEESCAPE-java
// The DashScope SDK version must be 2.19.4 or later.
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import java.lang.System;
import java.util.Arrays;

public class Main {
    private static StringBuilder reasoningContent = new StringBuilder();
    private static StringBuilder finalContent = new StringBuilder();
    private static boolean isFirstPrint = true;
    private static void handleGenerationResult(GenerationResult message) {
        String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
        String content = message.getOutput().getChoices().get(0).getMessage().getContent();
        if (reasoning != null && !reasoning.isEmpty()) {
            reasoningContent.append(reasoning);
            if (isFirstPrint) {
                System.out.println("====================Thinking process====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }
        if (content != null && !content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================Full response====================");
                isFirstPrint = true;
            }
            System.out.print(content);
        }
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                // If the environment variable is not set, replace it with your Model Studio API key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("deepseek-v4-pro")
                .enableThinking(true)
                .incrementalOutput(true)
                .resultFormat("message")
                .messages(Arrays.asList(userMsg))
                .build();
    }
    public static void streamCallWithMessage(Generation gen, Message userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException {
        GenerationParam param = buildGenerationParam(userMsg);
        Flowable<GenerationResult> result = gen.streamCall(param);
        result.blockingForEach(message -> handleGenerationResult(message));
    }
    public static void main(String[] args) {
        try {
            Generation gen = new Generation("http", "https://dashscope.aliyuncs.com/api/v1");
            Message userMsg = Message.builder().role(Role.USER.getValue()).content("Who are you?").build();
            streamCallWithMessage(gen, userMsg);
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("An exception occurred: " + e.getMessage());
        }
    }
}

Response

HELPCODEESCAPE-plaintext
====================Thinking process====================

We are asked: "Who are you". I need to respond as a helpful assistant. I should introduce myself as an AI assistant. Keep it simple and friendly.
====================Full response====================

I'm an AI assistant! I'm here to help you with questions, tasks, or just to chat. How can I assist you today?

HTTP

Sample code

curl

HELPCODEESCAPE-curl
curl -X POST "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "deepseek-v4-pro",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": "Who are you?"
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "incremental_output": true,
        "result_format": "message"
    }
}'

Reasoning effort

deepseek-v4-pro and deepseek-v4-flash have thinking mode enabled by default. You can use the reasoning_effort parameter to control reasoning intensity. Valid values: high and max. The default value is high. Note

If you set this parameter to low or medium, it is mapped to high. If you set it to xhigh, it is mapped to max.

OpenAI compatible

Python

HELPCODEESCAPE-python
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "Which is greater, 9.9 or 9.11?"}],
    reasoning_effort="high",
)
print(completion.choices[0].message.content)

Node.js

HELPCODEESCAPE-nodejs
import OpenAI from "openai";

const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
});

const completion = await openai.chat.completions.create({
    model: "deepseek-v4-pro",
    messages: [{ role: "user", content: "Which is greater, 9.9 or 9.11?" }],
    reasoning_effort: "high",
});
console.log(completion.choices[0].message.content);

curl

HELPCODEESCAPE-curl
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "deepseek-v4-pro",
    "messages": [{"role": "user", "content": "Which is greater, 9.9 or 9.11?"}],
    "reasoning_effort": "high"
}'

DashScope

HELPCODEESCAPE-python
import os
from dashscope import Generation

response = Generation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "Which is greater, 9.9 or 9.11?"}],
    reasoning_effort="high",
    result_format="message",
)
print(response.output.choices[0].message.content)

Other features

ModelMulti-turn conversationFunction callingContext cacheStructured outputPrefix Completion
deepseek-v4-proSupportedSupportedSupportedUnsupportedUnsupported
deepseek-v4-flashSupportedSupportedSupportedUnsupportedUnsupported
deepseek-v3.2SupportedSupportedSupportedUnsupportedUnsupported
deepseek-v3.2-expSupportedSupported ** Only in non-thinking modeUnsupportedUnsupportedUnsupported
deepseek-v3.1SupportedSupported Only in non-thinking modeSupportedUnsupportedUnsupported
deepseek-r1SupportedSupportedSupportedUnsupportedUnsupported
deepseek-r1-0528SupportedSupportedUnsupportedUnsupportedUnsupported
deepseek-v3SupportedSupportedSupportedUnsupportedUnsupported
Distilled modelsSupportedUnsupportedUnsupportedUnsupportedUnsupported

Default parameter values

Model**temperaturetop_prepetition_penaltypresence_penaltymax_tokensthinking_budget
deepseek-v4-pro1.01.0--Total: 393,216
deepseek-v4-flash1.01.0--Total: 393,216
deepseek-v3.21.00.95--65,53632,768
deepseek-v3.2-exp0.60.951.0-65,53632,768
deepseek-v3.10.60.951.0-65,53632,768
deepseek-r10.60.95-116,38432,768
deepseek-r1-05280.60.95-116,38432,768
Distilled models0.60.95-116,38416,384
deepseek-v30.70.6--16,384-
  • A hyphen (-) indicates that the parameter has no default value and cannot be configured.

  • The deepseek-r1, deepseek-r1-0528, and distilled models do not support these parameters.

  • For more information about parameter definitions, see OpenAI-compatible Chat.

Models and billing

  • Hybrid thinking models (thinking is controlled by the enable_thinking parameter): deepseek-v4-pro, deepseek-v4-flash, deepseek-v3.2, deepseek-v3.2-exp, deepseek-v3.1

  • Thinking-only models (always think before responding): deepseek-r1, deepseek-r1-0528

  • Non-thinking model: deepseek-v3

deepseek-v4-pro delivers top-tier performance across coding, math, and general tasks. deepseek-v4-flash is optimized for speed and cost-efficiency. Both models offer higher rate limits. We recommend starting with deepseek-v4-pro.

Check the context window size and pricing information in the console.

You are billed based on the number of input and output tokens.

In thinking mode, the chain of thought is billed as output tokens.

FAQ

Can I upload images or documents to ask questions?

DeepSeek models accept text input only and do not support image or document input. For image input, use Qwen-VL. For document input, use Qwen-Long.

How do I view token usage and the number of calls?

One hour after calling a model, go to Monitoring, set your filters (time range and workspace), find your model in Models , and click Monitor in Actions to view usage statistics. For more information, see Usage and performance monitoring.

Data is updated hourly. During peak hours, updates may be delayed by up to one hour.

Error codes

If an error occurs, see Error messages for troubleshooting.

Mirror of Alibaba Cloud Model Studio docs for reference and RAG. Not affiliated with Alibaba Cloud.