":{"type":"bad_response_status_code","message":"Model tpm limit exceeded. Please...

2026年01月06日 11:02 processing

错误信息

429 {"error":{"type":"bad_response_status_code","message":"Model tpm limit exceeded. Please try again later. (request id: 20260106110333853086578lKoWgQdJ)"},"type":"error"}

AI 解决方案

代码糕手 - 专业报错分析助理

1. 错误翻译


原文:Model tpm limit exceeded. Please try again later.
译文:模型TPM(每分钟令牌数)限制已超出。请稍后重试。

2. 原因分析


这个错误是API调用频率限制错误,不是代码本身的语法或逻辑错误。

根本原因

  • 您调用的AI模型服务(如GPT、Claude等)设定了TPM(Tokens Per Minute)限制

  • 您的请求在特定时间窗口内消耗的令牌数超过了服务商设定的配额
  • 发生位置

  • API调用接口层

  • 服务商的后端速率限制器
  • 3. 解决方案

    方案一:添加重试机制(推荐)


    import time
    import requests
    from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception
    
    def is_rate_limit_error(exception):
        """检查是否为速率限制错误"""
        if hasattr(exception, 'response') and exception.response is not None:
            return exception.response.status_code == 429
        return False
    
    @retry(
        retry=retry_if_exception(is_rate_limit_error),
        stop=stop_after_attempt(5),
        wait=wait_exponential(multiplier=1, min=4, max=60)
    )
    def call_api_with_retry():
        """带重试机制的API调用"""
        # 您的API调用代码
        response = requests.post(
            "https://api.your-service.com/v1/chat/completions",
            headers={"Authorization": "Bearer YOUR_API_KEY"},
            json={"model": "gpt-4", "messages": [...]}
        )
        response.raise_for_status()
        return response.json()
    

    方案二:手动添加延迟


    import time
    
    def call_api_with_backoff():
        try:
            # 您的API调用代码
            response = requests.post(
                "https://api.your-service.com/v1/chat/completions",
                headers={"Authorization": "Bearer YOUR_API_KEY"},
                json={"model": "gpt-4", "messages": [...]}
            )
            
            if response.status_code == 429:
                # 等待一段时间后重试
                wait_time = 60  # 建议等待60秒
                print(f"Rate limited. Waiting {wait_time} seconds...")
                time.sleep(wait_time)
                # 重试逻辑
                return call_api_with_backoff()
                
            response.raise_for_status()
            return response.json()
        except requests.exceptions.HTTPError as e:
            if e.response.status_code == 429:
                # 同上处理
                pass
    

    4. ️ 预防措施

    最佳实践建议:


  • 实现指数退避重试机制:使用像tenacity这样的库,在遇到429错误时自动重试,并逐渐增加重试间隔

  • 监控令牌使用量:跟踪您的TPM使用情况,避免接近限制阈值
  • 开发工具推荐:


  • Tenacity库:Python中最强大的重试库,支持复杂的重试策略

  • API监控仪表板:如果服务商提供,使用其仪表板监控您的使用量

  • 本地限流器:在客户端实现令牌桶或漏桶算法来限制请求频率
  • 配置建议:


    # 在您的API客户端配置中
    API_CONFIG = {
        "max_retries": 3,
        "retry_delay": [10, 30, 60],  # 秒数
        "batch_size": 5,  # 分批处理请求
        "requests_per_minute": 50  # 自行限制频率,低于服务商限制
    }
    

    请求ID: 20260106110333853086578lKoWgQdJ