You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring AI中insufficient_quota错误的优化处理方案咨询

针对Spring AI OpenAI客户端insufficient_quota错误快速失败的解决方案

问题背景

按照Spring AI的OpenAI Chat教程实现服务后,因账户配额不足触发insufficient_quota错误(对应HTTP 429状态码),但请求出现“挂起”现象——默认重试策略会不断重试该非瞬时错误。期望实现:仅对insufficient_quota错误快速失败,其他错误保留默认重试逻辑;已尝试配置spring.ai.retry.exclude-on-http-codes=429但未生效。

解决方案

1. 修正配置属性(优先尝试)

部分Spring AI版本中,全局重试配置spring.ai.retry.*不会覆盖OpenAI客户端的专属重试配置,需使用客户端级别的配置:

# OpenAI客户端专属重试排除配置
spring.ai.openai.retry.exclude-on-http-codes=429
# 直接排除指定错误码类型(部分新版本支持)
spring.ai.openai.retry.exclude-on-error-codes=insufficient_quota

2. 自定义RetryTemplate(配置不生效时使用)

若配置方式无效,可通过自定义RetryTemplate实现精准的重试规则:

步骤1:创建自定义RetryPolicy

import org.springframework.ai.retry.NonTransientAiException;
import org.springframework.retry.RetryPolicy;
import org.springframework.retry.context.RetryContext;
import org.springframework.retry.policy.SimpleRetryPolicy;

import java.util.Collections;
import java.util.Map;

public class OpenAiQuotaAwareRetryPolicy extends SimpleRetryPolicy {

    public OpenAiQuotaAwareRetryPolicy() {
        super(3, getRetryableExceptions(), true); // 保留默认重试次数,自定义可重试异常范围
    }

    private static Map<Class<? extends Throwable>, Boolean> getRetryableExceptions() {
        return Collections.singletonMap(NonTransientAiException.class, false);
    }

    @Override
    public boolean canRetry(RetryContext context) {
        Throwable throwable = context.getLastThrowable();
        if (throwable instanceof NonTransientAiException exception) {
            // 识别insufficient_quota错误,直接终止重试
            return !exception.getMessage().contains("insufficient_quota");
        }
        // 其他异常遵循默认重试规则
        return super.canRetry(context);
    }
}

步骤2:注册自定义RetryTemplate到OpenAI客户端配置

import org.springframework.ai.openai.OpenAiChatClient;
import org.springframework.ai.openai.OpenAiChatClientConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.support.RetryTemplate;

@Configuration
public class OpenAiClientConfig {

    @Bean
    public OpenAiChatClient openAiChatClient(OpenAiChatClientConfiguration clientConfiguration) {
        RetryTemplate retryTemplate = RetryTemplate.builder()
                .customPolicy(new OpenAiQuotaAwareRetryPolicy())
                .build();
        return new OpenAiChatClient(clientConfiguration, retryTemplate);
    }
}

3. 验证效果

启动服务后再次触发配额不足错误,日志应直接返回NonTransientAiException,无重试记录;其他如网络波动等瞬时错误仍会按照默认策略重试。

内容的提问来源于stack exchange,提问作者mnlaptev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:02:49