Skills MCP Model 博客 提交 Skills

DeepSeek API Complete Documentation

Comprehensive guide to the DeepSeek API: from basic calls to advanced features, covering Chat Completions, Streaming, Function Calling, R1 reasoning model, Token calculation, error handling, and multi-language SDK examples. Compatible with OpenAI SDK, zero-cost migration.

Start Learning

API Overview

The DeepSeek API provides an interface format fully compatible with OpenAI. You can use any OpenAI SDK to call it directly, just modify the base_url and api_key.

Base URL and Authentication

# Base URL https://api.deepseek.com/v1 # Authentication: Include Bearer Token in HTTP Header Authorization: Bearer sk-your-api-key-here # Get API Key: https://platform.deepseek.com/api_keys

Rate Limits

Request Rate (RPM) Default 500 requests/minute (contact official to increase)
Concurrent Connections Default 100 concurrent requests
Token Rate (TPM) Default 500,000 TPM

Supported Models

Model Name API Parameter Value Description
DeepSeek V3 deepseek-chat Flagship conversational model, best choice for general scenarios
DeepSeek R1 deepseek-reasoner Reasoning-enhanced model for math/logic/programming scenarios

Pricing

Model Input (per million tokens) Output (per million tokens) Context Window
deepseek-chat (V3) $0.27 (cache hit $0.07) $1.10 160K
deepseek-reasoner (R1) $0.55 (cache hit $0.14) $2.19 128K

Chat Completions API

Chat Completions is the core API of DeepSeek, supporting all conversation scenarios such as text chat, code generation, and content creation. It is compatible with the OpenAI Chat Completions API format.

API Endpoint

# POST request POST https://api.deepseek.com/v1/chat/completions # Content-Type Content-Type: application/json

Request Parameters

Parameter Type Required Default Description
model string Yes - Model ID: deepseek-chat or deepseek-reasoner
messages array Yes - List of conversation messages, each containing role and content
temperature float No 1.0 Sampling temperature, range 0~2. Higher is more random, lower is more deterministic
top_p float No 1.0 Nucleus sampling parameter, range 0~1. It is recommended to adjust only one of temperature and top_p
max_tokens integer No 4096 Maximum number of output tokens. V3 max 8K, R1 max 32K
stream boolean No false Whether to enable streaming output (SSE)
frequency_penalty float No 0 Frequency penalty, range -2~2. Positive values reduce the probability of repeated content.
presence_penalty float No 0 Presence penalty, range -2~2. Positive values encourage talking about new topics.
stop string/array No null Stop words, up to 16. Output terminates immediately when a stop word is encountered.
tools array No null Function Calling tool definition list.

Response Format

{ "id": "chatcmpl-xxx", "object": "chat.completion", "created": 1710000000, "model": "deepseek-chat", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Hello! How can I help you?" }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 10, "completion_tokens": 8, "total_tokens": 18 } }

Common values for finish_reason: stop (normal completion), length (reached max_tokens limit), content_filter (content filtered), tool_calls (function call triggered).

Multi-turn Conversation

The DeepSeek API implements multi-turn conversation through the messages array. Each request sends the complete conversation history to the model, which understands the conversational intent based on context and provides coherent responses.

Message Roles

role Description
system System prompt, used to set the style, role, boundaries, and rules of the conversation. Placed as the first message in the messages array.
user User message, i.e., the user's input question or instruction.
assistant Assistant message, i.e., the model's previously generated reply. Historical assistant messages must be included to maintain conversational context.

Multi-turn Conversation Example

{ "model": "deepseek-chat", "messages": [ {"role": "system", "content": "You are a professional Python programming assistant, and all answers are in Chinese."}, {"role": "user", "content": "How to read a CSV file in Python?"}, {"role": "assistant", "content": "You can use the csv module or pandas library. Recommended: import pandas as pd; df = pd.read_csv('file.csv')"}, {"role": "user", "content": "What if the file is very large?"} ] }

Context Window Management

DeepSeek V3 supports a 160K token context window, and R1 supports 128K. When the conversation history becomes too long, context management is needed:

  • Sliding window: Keep only the most recent N turns, discarding the earliest messages.
  • Summary compression: Use the model to generate a summary of early conversations, replacing the original messages.
  • Key message retention: Always keep the system prompt and the user's core questions, trimming only the intermediate conversation.
  • Token counting: Estimate the total number of tokens before each request to ensure it does not exceed the context window.

Streaming Output

Streaming output allows the model to return results token by token, so users don't have to wait for the complete response and can see the generated content in real time. For long text generation and chat applications, streaming significantly improves user experience.

SSE Format Explanation

DeepSeek streaming output is based on the Server-Sent Events (SSE) protocol. Each chunk starts with data: and ends with \n\n. Each chunk contains a JSON object, where the choices[0].delta.content field contains the incremental text.

# SSE data stream example data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"你好"}}]} data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"!"}}]} data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]} data: [DONE]

Python Streaming Example

from openai import OpenAI client = OpenAI( api_key="sk-your-api-key", base_url="https://api.deepseek.com/v1", ) response = client.chat.completions.create( model="deepseek-chat", messages=[ {"role": "user", "content": "写一首关于春天的五言绝句"} ], stream=True, ) for chunk in response: if chunk.choices[0].delta.content: print(chunk.choices[0].delta.content, end="", flush=True)

JavaScript (Node.js) Streaming Example

import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'sk-your-api-key', baseURL: 'https://api.deepseek.com/v1', }); const stream = await client.chat.completions.create({ model: 'deepseek-chat', messages: [{ role: 'user', content: '写一首关于春天的五言绝句' }], stream: true, }); for await (const chunk of stream) { const content = chunk.choices[0]?.delta?.content || ''; process.stdout.write(content); }

How to Parse SSE Stream

If you don't use an SDK and directly fetch streaming data via HTTP requests, you need to manually parse the SSE format:

  • Read the response body line by line, each line starting with data:
  • Encountering data: [DONE] indicates the end of the stream
  • Parse the JSON string after data, extract choices[0].delta.content
  • Empty lines are used to separate different events (chunks)

Function Calling

Function Calling enables the model to intelligently decide when to call external functions and convert user natural language into structured function parameters. This is the core capability for building AI Agent and tool-calling scenarios.

Tool Definition Format

Define available functions via the tools parameter in the request. Each function requires name, description, and parameters (JSON Schema format).

{ "model": "deepseek-chat", "messages": [ {"role": "user", "content": "北京今天天气怎么样?"} ], "tools": [ { "type": "function", "function": { "name": "get_weather", "description": "获取指定城市的实时天气信息", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "城市名称,如 北京、上海、深圳" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "温度单位,默认摄氏度" } }, "required": ["city"] } } } ] }

Function Calling Workflow

  1. Send Request: Send user message and tools definition together to DeepSeek API
  2. Model Decision: Model decides whether to call a function. If needed, returns finish_reason="tool_calls" and function call information
  3. Execute Function: Developer executes the corresponding function in their code based on the function name and parameters returned by the model
  4. Return Result: Append the function execution result as a tool role message to messages and send again to the model
  5. Model Reply: Model generates the final natural language reply based on the function result

Python Complete Example

from openai import OpenAI import json client = OpenAI( api_key="sk-your-api-key", base_url="https://api.deepseek.com/v1", ) def get_weather(city: str, unit: str = "celsius"): """模拟天气查询函数""" return {"city": city, "temperature": 25, "condition": "晴", "unit": unit} tools = [{ "type": "function", "function": { "name": "get_weather", "description": "获取指定城市的实时天气信息", "parameters": { "type": "object", "properties": { "city": {"type": "string", "description": "城市名称"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["city"] } } }] messages = [{"role": "user", "content": "北京今天天气怎么样?"}] # 第一步:发送请求,模型决定是否调用函数 response = client.chat.completions.create( model="deepseek-chat", messages=messages, tools=tools, ) msg = response.choices[0].message # 第二步:如果模型要求调用函数 if msg.tool_calls: for tool_call in msg.tool_calls: func_name = tool_call.function.name func_args = json.loads(tool_call.function.arguments) func_result = get_weather(**func_args) # 第三步:将函数结果追加到消息中 messages.append(msg) messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(func_result, ensure_ascii=False) }) # 第四步:再次发送请求,获取最终回复 final_response = client.chat.completions.create( model="deepseek-chat", messages=messages, ) print(final_response.choices[0].message.content)

DeepSeek R1 (Reasoner) API

DeepSeek R1 is a reasoning-enhanced model that excels in scenarios such as mathematics, programming, and logical reasoning. The API calling method is basically the same as deepseek-chat, but it has a unique thinking process output.

R1 API Endpoint

# Uses the same endpoint as Chat Completions, only the model parameter differs POST https://api.deepseek.com/v1/chat/completions # Set the model parameter to "deepseek-reasoner"

Thinking Process (reasoning_content)

Before generating the final answer, the R1 model performs internal reasoning. In streaming output, the reasoning process is returned via the reasoning_content field, and only after reasoning is complete does it return the content field.

from openai import OpenAI client = OpenAI( api_key="sk-your-api-key", base_url="https://api.deepseek.com/v1", ) response = client.chat.completions.create( model="deepseek-reasoner", messages=[ {"role": "user", "content": "A pool has an inlet pipe and an outlet pipe. The inlet pipe can fill it in 3 hours, and the outlet pipe can empty it in 5 hours. If both pipes are opened simultaneously, how many hours will it take to fill the pool?"} ], stream=True, ) for chunk in response: delta = chunk.choices[0].delta # Reasoning process if hasattr(delta, 'reasoning_content') and delta.reasoning_content: print(f"[Thinking] {delta.reasoning_content}", end="") # Final answer if delta.content: print(delta.content, end="", flush=True)

Differences between R1 and Chat API

Feature deepseek-chat (V3) deepseek-reasoner (R1)
Context Window 160K tokens 128K tokens
Max Output 8K tokens 32K tokens (including reasoning)
Reasoning Process Not exposed Exposed via reasoning_content
temperature Supported (0~2) Not supported (fixed reasoning strategy)
Function Calling Supported Recommended to use V3 for tool calls
Use Cases General conversation, content creation, translation Mathematical proofs, algorithm design, logical reasoning

R1 Best Practices

  • R1 does not require complex system prompts; simple instructions yield the best results
  • The reasoning process consumes tokens, so ensure max_tokens is set sufficiently (recommended 8000+)
  • In non-streaming calls, reasoning_content is included in the full response
  • For simple conversations, it is recommended to use V3 to save cost and latency; use R1 only for complex reasoning tasks

Token Calculation

Understanding token calculation is key to controlling API costs and managing context windows. DeepSeek uses an OpenAI-compatible tokenizer, and you can use the tiktoken library for precise calculation.

Token Estimation Rules

Content Type Token Estimation
English Text 1 token ~ 4 English characters, or ~ 0.75 English words
Chinese Text 1 Chinese character ~ 1.5-2 tokens
Code 1 token ~ 3-4 code characters (varies with indentation and symbols)

Precise Calculation with tiktoken

# Install tiktoken pip install tiktoken # Python example import tiktoken # DeepSeek uses cl100k_base encoding (same as GPT-4) encoding = tiktoken.get_encoding("cl100k_base") def count_tokens(text: str) -> int: return len(encoding.encode(text)) # Example text = "Hello, DeepSeek! The weather is really nice today." print(f"Token count: {count_tokens(text)}")

Context Window and max_tokens Limits

Model Context Window Max Output Tokens
deepseek-chat (V3) 160,000 tokens 8,192 tokens (default 4,096)
deepseek-reasoner (R1) 128,000 tokens 32,768 tokens (including reasoning)

Tip

The total_tokens for each request is prompt_tokens + completion_tokens. Ensure that prompt_tokens + max_tokens does not exceed the model's context window limit. You can check the actual consumption via the usage field returned by the API.

Error Codes and Exception Handling

Learn about DeepSeek API error codes and exception handling strategies to ensure your application is stable and reliable in production.

HTTP Status Codes

Status Code Meaning Description and Handling
200 Success Request processed normally
400 Bad Request Incorrect parameter format, missing required fields, JSON parsing failure, etc. Check the request body format.
401 Authentication Failed API Key is invalid, expired, or not provided. Check the Authorization header.
402 Insufficient Balance Account balance is insufficient to complete the request. Go to platform.deepseek.com to recharge.
429 Rate Limit Request frequency exceeds the limit. Reduce request frequency or contact us to increase quota.
500 Internal Server Error Temporary failure on DeepSeek server. It is recommended to retry using exponential backoff.
503 Service Unavailable Server is busy or under maintenance. Wait and retry, with a maximum wait of 60 seconds recommended.

Error Response Format

{ "error": { "message": "Insufficient Balance", "type": "insufficient_balance", "param": null, "code": "invalid_request_error" } }

Retry Strategy: Exponential Backoff

import time import random from openai import OpenAI, APIError, RateLimitError client = OpenAI( api_key="sk-your-api-key", base_url="https://api.deepseek.com/v1", ) def chat_with_retry(messages, max_retries=5, base_delay=1): """API call with exponential backoff retry""" for attempt in range(max_retries): try: return client.chat.completions.create( model="deepseek-chat", messages=messages, ) except RateLimitError: if attempt == max_retries - 1: raise delay = base_delay * (2 ** attempt) + random.uniform(0, 1) print(f"Rate limit reached, retrying in {delay:.1f}s...") time.sleep(delay) except APIError as e: if e.status_code < 500 or attempt == max_retries - 1: raise delay = base_delay * (2 ** attempt) + random.uniform(0, 1) print(f"Server error {e.status_code}, retrying in {delay:.1f}s...") time.sleep(delay)

Multi-language SDK Examples

The DeepSeek API is compatible with the OpenAI SDK, so you can use any OpenAI client library in any language. Below are complete example codes in major languages.

Python (openai package)

# Install: pip install openai from openai import OpenAI client = OpenAI( api_key="sk-your-api-key", base_url="https://api.deepseek.com/v1", ) response = client.chat.completions.create( model="deepseek-chat", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Introduce DeepSeek"}, ], temperature=0.7, max_tokens=1024, ) print(response.choices[0].message.content)

Node.js (openai package)

// Install: npm install openai import OpenAI from 'openai'; const client = new OpenAI({ apiKey: 'sk-your-api-key', baseURL: 'https://api.deepseek.com/v1', }); const response = await client.chat.completions.create({ model: 'deepseek-chat', messages: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'Introduce DeepSeek' }, ], temperature: 0.7, max_tokens: 1024, }); console.log(response.choices[0].message.content);

curl

curl https://api.deepseek.com/v1/chat/completions \ -H "Content-Type: application/json" \ -H "Authorization: Bearer sk-your-api-key" \ -d '{ "model": "deepseek-chat", "messages": [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Introduce DeepSeek"} ], "temperature": 0.7, "max_tokens": 1024 }'

Go

// Install: go get github.com/sashabaranov/go-openai package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { config := openai.DefaultConfig("sk-your-api-key") config.BaseURL = "https://api.deepseek.com/v1" client := openai.NewClientWithConfig(config) resp, err := client.CreateChatCompletion( context.Background(), openai.ChatCompletionRequest{ Model: "deepseek-chat", Messages: []openai.ChatCompletionMessage{ {Role: "system", Content: "You are a helpful assistant."}, {Role: "user", Content: "Introduce DeepSeek"}, }, Temperature: 0.7, MaxTokens: 1024, }, ) if err != nil { panic(err) } fmt.Println(resp.Choices[0].Message.Content) }

Java

// Maven dependency: com.theokanning.openai-gpt3-java:service:0.18.2 import com.theokanning.openai.OpenAiService; import com.theokanning.openai.completion.chat.*; import java.time.Duration; import java.util.List; public class DeepSeekExample { public static void main(String[] args) { OpenAiService service = new OpenAiService( "sk-your-api-key", Duration.ofSeconds(60) ); // Note: This library requires configuring a custom base URL // It is recommended to use an OkHttp interceptor to modify the base URL // Or use the OpenAiApi class from the openai-java library ChatCompletionRequest request = ChatCompletionRequest.builder() .model("deepseek-chat") .messages(List.of( new ChatMessage("system", "You are a helpful assistant."), new ChatMessage("user", "Introduce DeepSeek") )) .temperature(0.7) .maxTokens(1024) .build(); ChatCompletionResult result = service.createChatCompletion(request); System.out.println(result.getChoices().get(0).getMessage().getContent()); } }

Best Practices

Summarize the key best practices for using the DeepSeek API to help you use DeepSeek models efficiently, stably, and cost-effectively in production environments.

1. System Prompt Design

  • Define the role clearly: tell the model "who you are" (e.g., "You are a professional Python programming assistant")
  • Set the output format: require the model to output in a specific format (JSON, Markdown tables, code blocks, etc.)
  • Constrain behavior boundaries: explicitly tell the model what it cannot do (e.g., "Do not guess uncertain information")
  • Keep it concise: an overly long system prompt occupies context window; it is recommended to keep it between 200 and 500 characters

2. Temperature Tuning

Temperature Use Cases
0.0 ~ 0.3 Code generation, mathematical calculations, data extraction, translation — scenarios requiring precision and consistency
0.5 ~ 0.8 Content creation, brainstorming, general conversation — balancing creativity and consistency
0.9 ~ 1.5 Creative writing, story generation, poetry — requiring high diversity and creativity

3. Context Window Optimization

  • Only pass necessary conversation history; avoid ineffective back-and-forth messages
  • Use RAG for long documents instead of directly concatenating the full text
  • Use the system prompt to convey persistent instructions, avoiding repetition in each user message
  • Monitor usage.total_tokens to get early warnings when approaching the context window limit

4. Cost Control

  • Set max_tokens reasonably to avoid unnecessary long output waste
  • Leverage cache hits to reduce input costs: repeated system prompts and history messages can enjoy cache discounts
  • Use smaller max_tokens and low temperature for simple tasks
  • Use token counting tools to estimate costs during development and set budget alerts
  • Set monthly spending limits for API keys to avoid unexpected overruns

5. Concurrent Request Management

  • Use connection pooling to reuse HTTP connections and reduce handshake overhead
  • Implement request queues to control concurrency within limits (default 100)
  • Use asynchronous calls for batch tasks (Python asyncio / Node.js Promise.all)
  • Monitor 429 error frequency and adjust concurrency dynamically
  • Set different priority queues for different types of requests

More DeepSeek Tutorials

Continue exploring DeepSeek usage, deployment, and model knowledge.

DeepSeek API FAQ

Is DeepSeek API compatible with OpenAI API? +
Fully compatible. DeepSeek API follows the OpenAI Chat Completions API format. You can directly use the official OpenAI SDK (Python, Node.js, etc.) by simply changing the base_url to https://api.deepseek.com/v1, the api_key to your DeepSeek API Key, and the model to deepseek-chat or deepseek-reasoner. No other code changes are needed.
How to choose between DeepSeek V3 and R1? +
V3 (deepseek-chat) is suitable for general conversation, content creation, translation, code generation, and other daily scenarios. It is cheaper and faster. R1 (deepseek-reasoner) is suitable for scenarios requiring deep thinking, such as mathematical proofs, complex logical reasoning, and algorithm design. It outputs the reasoning process. For most applications, prioritize V3, and switch to R1 only when deep reasoning is needed.
How to get a DeepSeek API Key? +
Visit platform.deepseek.com, register and log in, then click "API Keys" in the left navigation, and click "Create API Key". Save the key immediately after creation; after closing the page, you will not be able to view the full key again. New users usually have free credits, so you can try it out before recharging.
Does DeepSeek API support Function Calling? +
Yes. DeepSeek V3 (deepseek-chat) fully supports Function Calling and is compatible with OpenAI's tools parameter format. You can define multiple functions in a single request, and the model will intelligently decide whether to call a function and which one to call. The R1 model can also use Function Calling, but it is recommended to use V3 for better tool-calling stability and determinism.
What to do when encountering 429 errors (rate limit)? +
A 429 error indicates that the request frequency exceeds the limit. Solutions: 1) Reduce request frequency and use exponential backoff retry strategy; 2) Combine multiple requests to reduce the number of requests; 3) Implement request queue and concurrency control in your code; 4) If your business truly requires higher frequency, contact DeepSeek official to request a quota increase. It is recommended to handle 429 errors automatically in your code rather than letting users notice them.
Is DeepSeek API data secure? Will data be used for training? +
DeepSeek officially states that data sent via the API will not be used for model training. API calls are encrypted with TLS. It is recommended to manage your API Key securely on the client side: store the key in environment variables, do not hardcode it in code, and do not commit it to version control systems. Enterprise users can also contact the official team for dedicated deployment solutions.

每日精选 Skill 推荐,免费送到你邮箱

输入邮箱,每天接收一个精选 AI Agent 技能推荐。完全免费,持续更新。

完全免费,取消任意时间。我们不会发送垃圾邮件。