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

解决Spring AI ImagePrompt Socket超时问题及图像搜索内存组件咨询

问题解答

1. 正确配置方式(含超时处理)

SocketTimeoutException是请求OpenAI接口超时导致的,DALL-E生成图像本身耗时较长,默认超时时间不足以覆盖这个过程,可通过自定义OkHttp客户端并调整超时参数解决,具体配置如下:

自定义OkHttp客户端配置

创建配置类,定义带有超时设置的OkHttpClient Bean:

import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;

@Configuration
public class OpenAiConfig {

    @Bean
    public OkHttpClient openAiOkHttpClient() {
        return new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时时间
                .readTimeout(60, TimeUnit.SECONDS)     // 读取超时时间,适配DALL-E生成耗时
                .writeTimeout(30, TimeUnit.SECONDS)    // 写入超时时间
                .build();
    }
}

绑定自定义客户端到OpenAI图像模型

Spring AI会自动注入自定义的OkHttpClient,若需显式配置,可添加以下Bean:

import org.springframework.ai.openai.OpenAiImageModel;
import org.springframework.ai.openai.api.OpenAiImageApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class OpenAiImageConfig {

    @Bean
    public OpenAiImageApi openAiImageApi(OkHttpClient okHttpClient) {
        return new OpenAiImageApi(System.getenv("OPENAI_API_KEY"), okHttpClient);
    }

    @Bean
    public OpenAiImageModel openAiImageModel(OpenAiImageApi openAiImageApi) {
        return new OpenAiImageModel(openAiImageApi);
    }
}

可选:优化控制器异步逻辑

由于图像生成耗时较长,建议将接口改为异步处理,避免阻塞Servlet线程:

@GetMapping("/openai/image")
public CompletableFuture<String> generate(@RequestParam(value = "message") String message) {
    return CompletableFuture.supplyAsync(() -> {
        ImageOptions options = ImageOptionsBuilder.builder()
                .withModel("dall-e-3")
                .withHeight(1024)
                .withWidth(1024)
                .build();

        ImagePrompt imagePrompt = new ImagePrompt(message, options);
        ImageResponse response = imageModel.call(imagePrompt);
        String imageUrl = response.getResult().getOutput().getUrl();

        return "redirect:" + imageUrl;
    });
}

2. 增加OkHttp客户端超时时间能否解决?

可以解决。DALL-E 3生成1024x1024图像通常需要10-30秒,而OkHttp默认读取超时一般为10秒左右,因此会触发超时异常。将readTimeout延长至60秒左右,可覆盖图像生成的正常耗时,避免该错误。

3. 图像搜索是否有与MessageChatMemoryAdvisor等效的组件?

目前Spring AI中没有专门针对图像搜索/生成场景、等效于MessageChatMemoryAdvisor的组件。MessageChatMemoryAdvisor主要用于对话场景的上下文记忆,而图像场景的上下文需求相对较少。若需实现图像相关的记忆功能,可自行扩展:

  • 使用Spring缓存框架(如Redis、Caffeine)存储历史图像生成的prompt与结果记录
  • 自定义Advisor类,在生成图像前查询历史记录,按需复用或调整prompt
  • 结合向量数据库存储图像特征向量,实现相似图像检索的记忆能力

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 12:07:43