From 163ebd859ded73b6e91999d77e1e120b0ff8c0ca Mon Sep 17 00:00:00 2001 From: Acerola Date: Thu, 26 Nov 2026 18:26:30 +0800 Subject: [PATCH] fix(anthropic): migrate AnthropicChatModel to ModelSchedulers (#4437) --- .../model/anthropic/AnthropicChatModel.java | 9 +- .../AnthropicChatModelSchedulingTest.java | 235 ++++++++++++++++++ 2 files changed, 239 insertions(+), 5 deletions(-) create mode 100644 agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/test/java/io/agentscope/extensions/model/anthropic/AnthropicChatModelSchedulingTest.java diff --git a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/main/java/io/agentscope/extensions/model/anthropic/AnthropicChatModel.java b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/main/java/io/agentscope/extensions/model/anthropic/AnthropicChatModel.java index c9ed7c1d7b..40b36fb24c 100644 --- a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/main/java/io/agentscope/extensions/model/anthropic/AnthropicChatModel.java +++ b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/main/java/io/agentscope/extensions/model/anthropic/AnthropicChatModel.java @@ -28,6 +28,7 @@ import io.agentscope.core.model.GenerateOptions; import io.agentscope.core.model.ModelContextWindows; import io.agentscope.core.model.ModelException; +import io.agentscope.core.model.ModelSchedulers; import io.agentscope.core.model.ModelUtils; import io.agentscope.core.model.ToolSchema; import io.agentscope.core.model.transport.ProxyConfig; @@ -44,7 +45,6 @@ import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; -import reactor.core.scheduler.Schedulers; /** * Anthropic Chat Model implementation using the official Anthropic Java SDK. @@ -338,9 +338,7 @@ protected Flux doStream( // Convert the SDK's Stream to Flux return AnthropicResponseParser.parseStreamEvents( - Flux.fromStream(streamResponse.stream()) - .subscribeOn( - Schedulers.boundedElastic()), + Flux.fromStream(streamResponse.stream()), startTime) .doFinally( signalType -> { @@ -375,7 +373,8 @@ protected Flux doStream( // Apply timeout and retry if configured return ModelUtils.applyTimeoutAndRetry( - responseFlux.subscribeOn(Schedulers.boundedElastic()), + responseFlux.subscribeOn( + streamEnabled ? ModelSchedulers.streams() : ModelSchedulers.requests()), options, defaultOptions, modelName, diff --git a/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/test/java/io/agentscope/extensions/model/anthropic/AnthropicChatModelSchedulingTest.java b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/test/java/io/agentscope/extensions/model/anthropic/AnthropicChatModelSchedulingTest.java new file mode 100644 index 0000000000..6e22d21915 --- /dev/null +++ b/agentscope-extensions/agentscope-extensions-model/agentscope-extensions-model-anthropic/src/test/java/io/agentscope/extensions/model/anthropic/AnthropicChatModelSchedulingTest.java @@ -0,0 +1,235 @@ +/* + * Copyright 2024-2026 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package io.agentscope.extensions.model.anthropic; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.anthropic.models.messages.MessageParam; +import io.agentscope.core.message.Msg; +import io.agentscope.core.message.MsgRole; +import io.agentscope.core.message.TextBlock; +import io.agentscope.core.model.ChatResponse; +import io.agentscope.extensions.model.anthropic.formatter.AnthropicChatFormatter; +import java.io.IOException; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import okhttp3.mockwebserver.MockResponse; +import okhttp3.mockwebserver.MockWebServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import reactor.core.Disposable; + +@Tag("unit") +class AnthropicChatModelSchedulingTest { + + private static final String MESSAGE_RESPONSE = + """ + { + "id": "msg_sched", "type": "message", "role": "assistant", + "model": "claude-sonnet-4.5", + "content": [{"type": "text", "text": "Hello"}], + "stop_reason": "end_turn", "stop_sequence": null, + "usage": {"input_tokens": 1, "output_tokens": 1} + } + """; + + private static final String STREAM_RESPONSE = + """ + event: message_start + data: {"type":"message_start","message":{"id":"msg_sched","type":"message","role":"assistant","model":"claude-sonnet-4.5","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"output_tokens":0}}} + + event: content_block_start + data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}} + + event: content_block_delta + data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}} + + event: content_block_stop + data: {"type":"content_block_stop","index":0} + + event: message_delta + data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":1}} + + event: message_stop + data: {"type":"message_stop"} + + """; + + private MockWebServer server; + + @BeforeEach + void setUp() throws IOException { + server = new MockWebServer(); + server.start(); + } + + @AfterEach + void tearDown() throws IOException { + server.shutdown(); + } + + @Test + void streamingConnectAndIterationRunOnModelStreamsScheduler() throws Exception { + server.enqueue( + new MockResponse() + .setHeader("Content-Type", "text/event-stream") + .setHeadersDelay(300, TimeUnit.MILLISECONDS) + .setBody(STREAM_RESPONSE)); + + AtomicReference connectThread = new AtomicReference<>(); + AnthropicChatModel model = + AnthropicChatModel.builder() + .baseUrl(server.url("/anthropic/").toString()) + .apiKey("test-api-key") + .modelName("claude-sonnet-4.5") + .stream(true) + .formatter(new TrackingFormatter(connectThread)) + .build(); + + String callerThread = Thread.currentThread().getName(); + List emitThreads = new CopyOnWriteArrayList<>(); + List responses = new CopyOnWriteArrayList<>(); + AtomicReference errorRef = new AtomicReference<>(); + CountDownLatch terminal = new CountDownLatch(1); + + long subscribeStartNanos = System.nanoTime(); + Disposable subscription = + model.stream(userMessages(), null, null) + .doOnNext( + response -> { + emitThreads.add(Thread.currentThread().getName()); + responses.add(response); + }) + .subscribe( + ignored -> {}, + failure -> { + errorRef.set(failure); + terminal.countDown(); + }, + terminal::countDown); + long subscribeMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - subscribeStartNanos); + + try { + assertTrue( + subscribeMs < 150, + "subscribe() must not block on createStreaming(), took " + subscribeMs + "ms"); + assertTrue(terminal.await(10, TimeUnit.SECONDS), "Stream did not finish"); + } finally { + subscription.dispose(); + } + + assertNull(errorRef.get()); + assertNotNull(connectThread.get()); + assertNotEquals(callerThread, connectThread.get()); + assertTrue( + connectThread.get().startsWith("agentscope-model-stream-"), + "Expected agentscope-model-stream-* connect thread, got: " + connectThread.get()); + assertFalse( + connectThread.get().startsWith("boundedElastic-"), + "Connect must not run on boundedElastic: " + connectThread.get()); + + assertFalse(emitThreads.isEmpty()); + for (String emitThread : emitThreads) { + assertTrue( + emitThread.startsWith("agentscope-model-stream-"), + "Expected agentscope-model-stream-* emit thread, got: " + emitThread); + assertFalse( + emitThread.startsWith("boundedElastic-"), + "Emit must not run on boundedElastic: " + emitThread); + } + + List texts = + responses.stream() + .flatMap(r -> r.getContent().stream()) + .filter(TextBlock.class::isInstance) + .map(TextBlock.class::cast) + .map(TextBlock::getText) + .toList(); + assertEquals(List.of("Hello"), texts); + } + + @Test + void nonStreamingKickoffRunsOnModelRequestsScheduler() { + server.enqueue( + new MockResponse() + .setHeader("Content-Type", "application/json") + .setBody(MESSAGE_RESPONSE)); + + AtomicReference requestThread = new AtomicReference<>(); + AnthropicChatModel model = + AnthropicChatModel.builder() + .baseUrl(server.url("/anthropic/").toString()) + .apiKey("test-api-key") + .modelName("claude-sonnet-4.5") + .stream(false) + .formatter(new TrackingFormatter(requestThread)) + .build(); + + String callerThread = Thread.currentThread().getName(); + List responses = + model.stream(userMessages(), null, null) + .collectList() + .block(Duration.ofSeconds(10)); + + assertNotNull(responses); + assertNotNull(requestThread.get()); + assertNotEquals(callerThread, requestThread.get()); + assertTrue( + requestThread.get().startsWith("agentscope-model-request-"), + "Expected agentscope-model-request-* thread, got: " + requestThread.get()); + assertFalse( + requestThread.get().startsWith("boundedElastic-"), + "Non-streaming must not run on boundedElastic: " + requestThread.get()); + + List texts = + responses.stream() + .flatMap(r -> r.getContent().stream()) + .filter(TextBlock.class::isInstance) + .map(TextBlock.class::cast) + .map(TextBlock::getText) + .toList(); + assertEquals(List.of("Hello"), texts); + } + + private static List userMessages() { + return List.of(Msg.builder().role(MsgRole.USER).textContent("Hello").build()); + } + + private static final class TrackingFormatter extends AnthropicChatFormatter { + private final AtomicReference threadRecorder; + + TrackingFormatter(AtomicReference threadRecorder) { + this.threadRecorder = threadRecorder; + } + + @Override + public List doFormat(List msgs) { + threadRecorder.compareAndSet(null, Thread.currentThread().getName()); + return super.doFormat(msgs); + } + } +}