DeepSeek API Overview and Pricing

The DeepSeek API is currently one of the most cost-effective large model APIs. It is fully compatible with the OpenAI SDK, and developers can seamlessly switch by simply modifying the base_url. The API offers two core models: deepseek-chat (corresponding to the V3 series) and deepseek-reasoner (corresponding to the R1 series). As of July 2026, DeepSeek's API pricing is only about one-tenth of similar products: approximately ¥1 per million tokens for input and ¥2 per million tokens for output. For small and medium-sized applications, a few dozen yuan per month can cover a large number of requests.

Basic Call Example

The DeepSeek API is compatible with the OpenAI SDK, making installation and invocation very simple:

pip install openai
from openai import OpenAI

client = OpenAI(
    api_key="sk-your-deepseek-api-key",
    base_url="https://api.deepseek.com"
)

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[
        {"role": "system", "content": "You are a helpful AI assistant."},
        {"role": "user", "content": "Please introduce artificial intelligence in one sentence."}
    ],
    temperature=0.7,
    max_tokens=200
)

print(response.choices[0].message.content)

The DeepSeek API also supports configuration in the OpenAI Playground using the Custom Endpoint mode. Set the Base URL to https://api.deepseek.com/v1 to test various prompts in a familiar interface.

Streaming Output Explained

Streaming output is a key technology for achieving typewriter effects. It allows users to see AI responses in real time, significantly reducing perceived latency:

stream = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "Write a five-character quatrain about programming"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

Streaming output is crucial in scenarios like chat applications and code generation. It is recommended that all user-facing AI applications enable streaming output, using SSE (Server-Sent Events) to push to the frontend. In production environments, pay attention to handling network disconnections and streaming timeouts.

Function Calling in Practice

Function Calling enables AI to call external tools and APIs. This is a core capability for building Agent applications:

tools = [{
    "type": "function",
    "function": {
        "name": "get_stock_price",
        "description": "Get the real-time price of a specified stock",
        "parameters": {
            "type": "object",
            "properties": {
                "symbol": {
                    "type": "string",
                    "description": "Stock symbol, e.g., AAPL, GOOGL"
                }
            },
            "required": ["symbol"]
        }
    }
}]

response = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "How much is Apple stock now?"}],
    tools=tools
)

tool_call = response.choices[0].message.tool_calls[0]
print(f"Function called: {tool_call.function.name}")
print(f"Arguments: {tool_call.function.arguments}")

When using Function Calling in production, note the following: tool descriptions should be clear and accurate, parameter validation is essential, tool call results should be properly fed back to the model, and avoid infinite recursion due to loop calls.

Rate Limits and Error Handling

The DeepSeek API has rate limits, and exceeding them returns a 429 error. In production, robust error handling and retry mechanisms are essential:

import time
from openai import RateLimitError, APIError

def call_with_retry(messages, max_retries=5):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="deepseek-chat",
                messages=messages
            )
        except RateLimitError as e:
            wait = 2 ** attempt  # exponential backoff
            print(f"Rate limit hit, waiting {wait} seconds before retry...")
            time.sleep(wait)
        except APIError as e:
            if e.status_code >= 500:
                wait = 2 ** attempt
                print(f"Server error, waiting {wait} seconds before retry...")
                time.sleep(wait)
            else:
                raise
    raise Exception("Max retries reached")

Key strategies: exponential backoff, random jitter to avoid thundering herd effect, setting a maximum number of retries, and distinguishing between retryable errors (429/5xx) and non-retryable errors (4xx).

Multi-Model Selection Strategy

DeepSeek offers two core models: deepseek-chat (V3) and deepseek-reasoner (R1). The V3 model is suitable for most general tasks—conversation, translation, summarization, code generation, etc. It has fast response times and high cost-effectiveness. The R1 model excels at deep reasoning, performing exceptionally well on tasks requiring rigorous thinking such as mathematics, programming, and logical reasoning, but it has longer response times and slightly higher costs. A practical strategy is to use V3 by default and switch to R1 when the task requires deep reasoning. You can also set up a simple router:

def select_model(user_message):
    reasoning_keywords = ["reasoning", "proof", "mathematics", "logic", "analysis"]
    if any(kw in user_message for kw in reasoning_keywords):
        return "deepseek-reasoner"
    return "deepseek-chat"

model = select_model("Help me prove the Pythagorean theorem")
print(f"Selected model: {model}")

Production Best Practices

Retry and Degradation: In addition to exponential backoff retries, implement degradation strategies. When the DeepSeek API is unavailable, automatically switch to a backup model or return cached results. Request Caching: For repeated queries, use Redis or in-memory caching to store results, reducing API calls and costs. Semantic caching (hitting cache for similar questions) is more practical than exact-match caching. Connection Pool Management: Reuse HTTP connections to avoid establishing new connections for each request. httpx and the OpenAI SDK support connection pooling by default. Request Queue: For high-concurrency scenarios, use a message queue (e.g., Redis Queue) to process requests asynchronously, smoothing traffic spikes. Logging and Monitoring: Record latency, token consumption, and status codes for each API call, and set up alerting rules. This not only tracks costs but also helps detect anomalies promptly.

Cost Optimization Strategies

Controlling token consumption is key to reducing API costs: use shorter system prompts (the system prompt is counted in tokens for every request), limit max_tokens output length, summarize and compress historical conversations instead of retaining full context, and cache responses to frequently asked questions. Another cost-saving method is to use DeepSeek's open-source models for local deployment—for large-scale offline tasks, local inference is more economical than calling the API. For small applications requiring high-frequency calls, it is recommended to set daily budget alerts to avoid unexpected overspending.

Want to orchestrate Agent tool chains?

Explore Skill Chain Orchestration →