Skip to content

DeepSeek API 频繁出现 JSONDecodeError: Expecting value line 1 column 1

问题

调用 DeepSeek API 时随机出现以下错误,且 DeepSeek 状态页显示"一切正常":

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

表现特征:

  • 短上下文的请求正常,长上下文(需要生成大量 token)时频繁触发
  • 第一次请求成功,之后请求失败一段时间
  • HTTP 状态码仍返回 200,但 body 为空

根因

DeepSeek 后端网关存在约 60 秒的超时限制。当请求需要生成的 token 较多、耗时超过 60 秒时,网关强制断开并返回空响应体。OpenAI SDK 尝试解析空字符串时,抛出 JSONDecodeError

解决方案

方案一:加重试逻辑(推荐)

python
import json
import time
from openai import OpenAI

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

def call_with_retry(messages, max_retries=3, delay=5):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="deepseek-chat",
                messages=messages
            )
        except json.decoder.JSONDecodeError:
            if attempt < max_retries - 1:
                time.sleep(delay * (2 ** attempt))  # 指数退避
            else:
                raise
typescript
// TypeScript 版本
async function callWithRetry(messages: any[], maxRetries = 3) {
  for (let i = 0; i < maxRetries; i++) {
    try {
      return await client.chat.completions.create({ model: "deepseek-chat", messages });
    } catch (e: any) {
      if (i < maxRetries - 1 && e.message?.includes('JSON')) {
        await new Promise(r => setTimeout(r, 1000 * Math.pow(2, i)));
      } else throw e;
    }
  }
}

方案二:减少单次生成量

将长上下文任务拆分,或设置较小的 max_tokens 限制,避免单次请求耗时超过 60 秒。

方案三:启用流式输出(streaming)

流式输出可以规避网关超时:

python
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=messages,
    stream=True  # 启用流式,避免 60s 超时
)
for chunk in response:
    print(chunk.choices[0].delta.content or "", end="")

来源Issue #599 - deepseek-ai/DeepSeek-V3