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 LearningAPI 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
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
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
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
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.
Python Streaming Example
JavaScript (Node.js) Streaming Example
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).
Function Calling Workflow
- Send Request: Send user message and tools definition together to DeepSeek API
- Model Decision: Model decides whether to call a function. If needed, returns finish_reason="tool_calls" and function call information
- Execute Function: Developer executes the corresponding function in their code based on the function name and parameters returned by the model
- Return Result: Append the function execution result as a tool role message to messages and send again to the model
- Model Reply: Model generates the final natural language reply based on the function result
Python Complete Example
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
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.
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
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
Retry Strategy: Exponential Backoff
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)
Node.js (openai package)
curl
Go
Java
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.
How to Use DeepSeek Models
Zero to hero, covering all four usage methods.
DeepSeek Model Deployment Guide
Ollama, Docker, vLLM, K8s deployment options.
Complete Guide to DeepSeek Models
Technical architecture, benchmark performance comparison, model selection.
DeepSeek Ecosystem Tools
30+ recommended tools and configuration guides.
DeepSeek + LangChain
Integrate with LangChain framework to build AI applications.