spring-ai icon indicating copy to clipboard operation
spring-ai copied to clipboard

AnthropicChatOptions.timeout(Duration) set via ChatClient (default or per-request) is silently ignored — only construction-time timeout applies

Open seeun0210 opened this issue 4 months ago • 2 comments

Please do a quick search on GitHub issues first, there might be already a duplicate issue for the one you are about to create. If the bug is trivial, just go ahead and create the issue. Otherwise, please take a few moments and fill in the following sections:

Bug description

The official docs show this as valid, working usage:

var chatOptions = AnthropicChatOptions.builder()
    .model("claude-sonnet-4-20250514")
    .maxTokens(1024)
    .timeout(Duration.ofSeconds(120))
    .build();

We followed this exact documented pattern — set .timeout(Duration.ofSeconds(N)) via ChatClient.Builder.defaultOptions() and via per-request ChatClient.prompt().options(...) — and it did not work. The configured Duration is silently accepted (no error, no warning) but has zero effect on the actual HTTP timeout used for the call.

The only place a timeout Duration actually takes effect is AnthropicChatModel construction time — i.e. the spring.ai.anthropic.timeout property, consumed once by AnthropicChatAutoConfiguration when it builds the shared AnthropicChatModel bean. Nothing set afterwards — not ChatClient.Builder.defaultOptions(), not a per-request ChatClient.prompt().options(...) override — has any effect, contrary to what the docs show.

Practical impact: because the Anthropic SDK retries transient failures up to maxRetries (default 2, so 3 total attempts), an unconfigured/short construction-time timeout compounds silently: with the SDK's DEFAULT_TIMEOUT (60s) and no spring.ai.anthropic.timeout set, any call that legitimately needs more than 60s (e.g. web_search tool use, large maxTokens generations) reliably fails after ~180s (3 × 60s) — no matter what AnthropicChatOptions.timeout(...) is set via ChatClient, following the documented pattern exactly.

Environment

  • Spring AI version: 2.0.0 (confirmed still present on main as of this report)
  • Module: spring-ai-anthropic, spring-ai-autoconfigure-model-anthropic
  • Java 21

Steps to reproduce

  1. Start a local HTTP server that responds to POST /v1/messages after a fixed delay (e.g. 2s), returning a minimal valid Message JSON body.
  2. Build an AnthropicChatModel with a short construction-time timeout (e.g. 500ms) — deliberately too short for the delayed response above.
  3. Call it through ChatClient with a longer per-request timeout (e.g. 5s), exactly as documented — this should legitimately allow the 2s-delayed mock response to succeed.

See Minimal Complete Reproducible example below for the exact code.

Expected behavior

Per the documented example, the per-request .timeout(Duration.ofSeconds(5)) should apply, and the call should succeed after ~2s (mock server delay < 5s per-request timeout).

Actual behavior

The call fails at ~500ms × 3 attempts — the construction-time 500ms timeout is used for every attempt; the per-request 5s value is completely ignored. Confirmed via an AnthropicHttpClientBuilderCustomizer interceptor logging the live chain.readTimeoutMillis()/chain.call().timeout() at call time: it consistently reports the construction-time value (500ms), never the per-request value (5000ms), across all 3 retry attempts.

Minimal Complete Reproducible example

try (MockWebServer server = new MockWebServer()) {
    server.enqueue(new MockResponse().setHeadersDelay(2, TimeUnit.SECONDS)
        .setResponseCode(200)
        .setHeader("Content-Type", "application/json")
        .setBody("""
            {"id":"msg-test","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"model":"claude-haiku-4-5-20251001","stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}
            """));
    server.start();

    AnthropicChatModel chatModel = AnthropicChatModel.builder()
        .options(AnthropicChatOptions.builder()
            .baseUrl(server.url("/").toString())
            .apiKey("test-key")
            .model("claude-haiku-4-5-20251001")
            .maxTokens(10)
            .timeout(Duration.ofMillis(500)) // short construction-time timeout
            .build())
        .build();
    ChatClient chatClient = ChatClient.builder(chatModel).build();

    // Per the docs, this 5s per-request timeout should let the 2s-delayed call
    // succeed. Instead, it's ignored and the call fails at ~500ms.
    String content = chatClient.prompt()
        .user("hello")
        .options(AnthropicChatOptions.builder().timeout(Duration.ofSeconds(5)))
        .call()
        .content();
}

Root cause (traced via bytecode + source)

AnthropicChatAutoConfiguration.anthropicChatModel(...) only threads AnthropicConnectionProperties.timeout (the spring.ai.anthropic.timeout property) into the AnthropicChatOptions used to build the shared AnthropicChatModel bean, once, at startup:

if (connectionProperties.getTimeout() != null) {
    builder.timeout(connectionProperties.getTimeout());
}
...
var chatModel = AnthropicChatModel.builder().options(options)...build();

But AnthropicChatModel.internalCall()/internalStream() (the per-call path used by every ChatClient request) never reads the merged runtime AnthropicChatOptions.getTimeout() to build a per-call com.anthropic.core.RequestOptions — it always calls messageService.withRawResponse().create(request) / createStreaming(request) (no explicit RequestOptions argument), so RequestOptions.none() is used, and the actual HTTP client behavior is whatever was baked into the shared AnthropicClient at construction time.

Fix

We have a working fix + regression tests: #6605.

Related: #512 (general HTTP client configuration umbrella issue) and #4970 (open PR adding connect-timeout/read-timeout config properties, still construction-time-only) don't cover this specific case.

seeun0210 avatar Jul 13 '26 01:07 seeun0210

For context, related-but-distinct issues found while searching for duplicates: #4103 (general feature request for ChatClient-level timeout support, provider-agnostic — doesn't seem aware Anthropic already has a documented AnthropicChatOptions.timeout(Duration) that's simply not wired through) and #512 (general HTTP client configuration umbrella). Neither covers this specific case: an existing, documented, provider-specific timeout option that's silently ignored outside model construction.

seeun0210 avatar Jul 13 '26 01:07 seeun0210

Also checked closed issues and related open PRs — nothing duplicates this exact case. #4970 (open PR, adds connect-timeout/read-timeout config properties for several providers including Anthropic) is adjacent but doesn't fix this: it's still a construction-time-only mechanism, so the documented per-call AnthropicChatOptions.timeout(Duration) pattern this issue is about would remain silently ignored even with that PR merged.

seeun0210 avatar Jul 13 '26 01:07 seeun0210