Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.agentscope.core.interruption.InterruptSource;
import io.agentscope.core.message.Msg;
import io.agentscope.core.message.MsgRole;
import io.agentscope.core.model.ModelSchedulers;
import io.agentscope.core.shutdown.GracefulShutdownManager;
import io.agentscope.core.state.AgentState;
import io.agentscope.core.tracing.TracerRegistry;
Expand All @@ -45,7 +46,6 @@
import reactor.core.publisher.Mono;
import reactor.core.publisher.SignalType;
import reactor.core.publisher.Sinks;
import reactor.core.scheduler.Schedulers;

/**
* Abstract base class for all agents in the AgentScope framework.
Expand Down Expand Up @@ -1078,7 +1078,7 @@ private Flux<Event> createEventStream(StreamOptions options, Supplier<Mono<Msg>>
sink.onCancel(callDisposable);
},
FluxSink.OverflowStrategy.BUFFER)
.publishOn(Schedulers.boundedElastic()));
.publishOn(ModelSchedulers.responses()));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* 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.core.model;

import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;

/**
* Shared, lazily created schedulers that isolate model work from application blocking tasks.
*
* <p>Requests, blocking stream reads, and response delivery use separate bounded pools. Threads
* are daemon threads and idle threads expire after 60 seconds. The pools live for the JVM lifetime;
* callers must not dispose these shared schedulers.
*
* <p>Set {@code agentscope.model.requestThreadCap}, {@code agentscope.model.streamThreadCap}, or
* {@code agentscope.model.responseThreadCap} before the corresponding pool is first used. Each
* defaults to the greater of 64 and ten times the available processor count. The per-thread queued
* task limit is {@code agentscope.model.taskQueueCapacity} (default 256). These are task limits,
* not HTTP connection limits. Transport builders also accept caller-owned schedulers.
*/
public final class ModelSchedulers {

private ModelSchedulers() {}

/** Returns the shared scheduler for request preparation and blocking non-streaming calls. */
public static Scheduler requests() {
return Requests.INSTANCE;
}

/** Returns the shared scheduler for blocking stream connection and read operations. */
public static Scheduler streams() {
return Streams.INSTANCE;
}

/** Returns the shared scheduler for ordered response delivery, separate from stream reads. */
public static Scheduler responses() {
return Responses.INSTANCE;
}

private static Scheduler create(String role) {
int defaultCap = Math.max(64, Runtime.getRuntime().availableProcessors() * 10);
return Schedulers.newBoundedElastic(
positiveProperty("agentscope.model." + role + "ThreadCap", defaultCap),
positiveProperty("agentscope.model.taskQueueCapacity", 256),
"agentscope-model-" + role,
60,
true);
}

private static int positiveProperty(String name, int fallback) {
int value = Integer.parseInt(System.getProperty(name, Integer.toString(fallback)));
if (value < 1) throw new IllegalArgumentException(name + " must be positive");
return value;
}

private static final class Requests {
private static final Scheduler INSTANCE = create("request");
}

private static final class Streams {
private static final Scheduler INSTANCE = create("stream");
}

private static final class Responses {
private static final Scheduler INSTANCE = create("response");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.agentscope.core.model.transport;

import io.agentscope.core.model.ModelSchedulers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -50,7 +51,7 @@
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.core.scheduler.Scheduler;

/**
* Pure JDK implementation of the HttpTransport interface.
Expand All @@ -75,6 +76,7 @@ public class JdkHttpTransport implements HttpTransport {

private final HttpClient client;
private final HttpTransportConfig config;
private final Scheduler streamScheduler;
private final AtomicBoolean closed = new AtomicBoolean(false);

/**
Expand All @@ -91,8 +93,7 @@ public class JdkHttpTransport implements HttpTransport {
* @throws NullPointerException if config is null
*/
JdkHttpTransport(HttpTransportConfig config) {
this.config = Objects.requireNonNull(config, "config must not be null");
this.client = buildClient(config);
this(buildClient(Objects.requireNonNull(config, "config must not be null")), config);
}

/**
Expand All @@ -106,8 +107,14 @@ public class JdkHttpTransport implements HttpTransport {
* @throws NullPointerException if client or config is null
*/
public JdkHttpTransport(HttpClient client, HttpTransportConfig config) {
this(client, config, ModelSchedulers.streams());
}

private JdkHttpTransport(
HttpClient client, HttpTransportConfig config, Scheduler streamScheduler) {
this.client = Objects.requireNonNull(client, "client must not be null");
this.config = Objects.requireNonNull(config, "config must not be null");
this.streamScheduler = Objects.requireNonNull(streamScheduler, "streamScheduler");
}

private static HttpClient buildClient(HttpTransportConfig config) {
Expand Down Expand Up @@ -301,7 +308,7 @@ private Flux<String> handleStreamResponse(
}

/**
* Parse SSE or NDJSON lines on a bounded elastic worker because BufferedReader blocks.
* Parse SSE or NDJSON lines on {@code streamScheduler} because BufferedReader blocks.
*/
private Flux<String> processStreamResponse(InputStream inputStream, HttpRequest request) {
if (inputStream == null) {
Expand All @@ -326,7 +333,7 @@ private Flux<String> processStreamResponse(InputStream inputStream, HttpRequest
return isNdjson ? readNdJsonLines(reader) : readSseLines(reader);
})
// reader.lines() uses blocking I/O internally
.subscribeOn(Schedulers.boundedElastic());
.subscribeOn(streamScheduler);
}

/**
Expand Down Expand Up @@ -489,7 +496,7 @@ private String readInputStream(InputStream inputStream) {
private Mono<String> readInputStreamAsync(InputStream inputStream) {
return Mono.fromCallable(() -> readInputStream(inputStream))
.defaultIfEmpty("")
.subscribeOn(Schedulers.boundedElastic());
.subscribeOn(streamScheduler);
}

/**
Expand Down Expand Up @@ -578,6 +585,19 @@ public static Builder builder() {
public static class Builder {
private HttpTransportConfig config = HttpTransportConfig.defaults();
private HttpClient existingClient = null;
private Scheduler streamScheduler;

/**
* Use a caller-owned scheduler for blocking stream reads. The transport never disposes it.
* Defaults to {@link ModelSchedulers#streams()}.
*
* @param scheduler the stream scheduler
* @return this builder
*/
public Builder streamScheduler(Scheduler scheduler) {
this.streamScheduler = Objects.requireNonNull(scheduler, "scheduler");
return this;
}

/**
* Set the transport configuration.
Expand Down Expand Up @@ -610,10 +630,11 @@ public Builder client(HttpClient client) {
* @return a new JdkHttpTransport instance
*/
public JdkHttpTransport build() {
if (existingClient != null) {
return new JdkHttpTransport(existingClient, config);
}
return new JdkHttpTransport(config);
Objects.requireNonNull(config, "config must not be null");
return new JdkHttpTransport(
existingClient != null ? existingClient : buildClient(config),
config,
streamScheduler != null ? streamScheduler : ModelSchedulers.streams());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package io.agentscope.core.model.transport;

import io.agentscope.core.model.ModelSchedulers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
Expand All @@ -30,6 +31,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
Expand All @@ -46,7 +48,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;
import reactor.core.scheduler.Scheduler;

/**
* OkHttp implementation of the HttpTransport interface.
Expand All @@ -69,6 +71,7 @@ public class OkHttpTransport implements HttpTransport {

private final OkHttpClient client;
private final HttpTransportConfig config;
private final Scheduler streamScheduler;

/**
* Create a new OkHttpTransport with default configuration.
Expand All @@ -83,8 +86,7 @@ public OkHttpTransport() {
* @param config the transport configuration
*/
public OkHttpTransport(HttpTransportConfig config) {
this.config = config;
this.client = buildClient(config);
this(buildClient(config), config, ModelSchedulers.streams());
}

/**
Expand All @@ -97,11 +99,17 @@ public OkHttpTransport(HttpTransportConfig config) {
* @param config the transport configuration (used for reference only)
*/
public OkHttpTransport(OkHttpClient client, HttpTransportConfig config) {
this(client, config, ModelSchedulers.streams());
}

private OkHttpTransport(
OkHttpClient client, HttpTransportConfig config, Scheduler streamScheduler) {
this.client = client;
this.config = config;
this.streamScheduler = Objects.requireNonNull(streamScheduler, "streamScheduler");
}

private OkHttpClient buildClient(HttpTransportConfig config) {
private static OkHttpClient buildClient(HttpTransportConfig config) {
OkHttpClient.Builder builder =
new OkHttpClient.Builder()
.connectTimeout(
Expand Down Expand Up @@ -307,7 +315,7 @@ public Flux<String> stream(HttpRequest request) {
closeQuietly(response);
}
})
.subscribeOn(Schedulers.boundedElastic(), false);
.subscribeOn(streamScheduler, false);
}

@Override
Expand Down Expand Up @@ -428,6 +436,19 @@ public static Builder builder() {
public static class Builder {
private HttpTransportConfig config = HttpTransportConfig.defaults();
private OkHttpClient existingClient = null;
private Scheduler streamScheduler;

/**
* Use a caller-owned scheduler for blocking stream reads. The transport never disposes it.
* Defaults to {@link ModelSchedulers#streams()}.
*
* @param scheduler the stream scheduler
* @return this builder
*/
public Builder streamScheduler(Scheduler scheduler) {
this.streamScheduler = Objects.requireNonNull(scheduler, "scheduler");
return this;
}

/**
* Set the transport configuration.
Expand Down Expand Up @@ -460,10 +481,12 @@ public Builder client(OkHttpClient client) {
* @return a new OkHttpTransport instance
*/
public OkHttpTransport build() {
Scheduler effectiveStreamScheduler =
streamScheduler != null ? streamScheduler : ModelSchedulers.streams();
if (existingClient != null) {
return new OkHttpTransport(existingClient, config);
return new OkHttpTransport(existingClient, config, effectiveStreamScheduler);
}
return new OkHttpTransport(config);
return new OkHttpTransport(buildClient(config), config, effectiveStreamScheduler);
}
}

Expand Down
Loading
Loading