Skip to content
Closed
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 @@ -28,10 +28,12 @@
import io.agentscope.extensions.model.openai.dto.OpenAIRequest;
import io.agentscope.extensions.model.openai.dto.OpenAIResponse;
import io.agentscope.extensions.model.openai.exception.OpenAIException;
import java.io.EOFException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
Expand Down Expand Up @@ -403,12 +405,24 @@ public Flux<OpenAIResponse> stream(
.build();

AtomicBoolean seenChunk = new AtomicBoolean(false);
// A stream that ends without either marker below did not finish: the provider, the
// gateway or a proxy closed the connection mid-generation and the transport reports
// that as a normal completion (a server-side FIN is not an error to the HTTP client).
AtomicBoolean sawDoneMarker = new AtomicBoolean(false);
AtomicBoolean sawFinishReason = new AtomicBoolean(false);
return transport.stream(httpRequest)
// The SSE `[DONE]` sentinel terminates the stream: complete the Flux here
// rather than merely filtering it out, otherwise completion is deferred until
// the underlying connection closes (keep-alive gateways may stall this for the
// full idle timeout even though the model has finished responding).
.takeWhile(data -> !SSE_DONE_MARKER.equals(data))
.takeWhile(
data -> {
if (SSE_DONE_MARKER.equals(data)) {
sawDoneMarker.set(true);
return false;
}
return true;
})
.<OpenAIResponse>handle(
(data, sink) -> {
OpenAIResponse response = parseStreamData(data);
Expand Down Expand Up @@ -440,10 +454,18 @@ public Flux<OpenAIResponse> stream(
summaryChoice.setMessage(null);
}
}
markFinishReason(response, sawFinishReason);
sink.next(response);
}
// If response is null (malformed chunk), skip it silently
})
// Completion without [DONE] and without any finish_reason means the answer was
// cut short; surface it instead of returning the partial text as a final one.
.concatWith(
Flux.defer(
() ->
failIfTruncated(
seenChunk, sawDoneMarker, sawFinishReason)))
.onErrorMap(
ex -> {
if (ex instanceof HttpTransportException hte) {
Expand All @@ -465,6 +487,64 @@ public Flux<OpenAIResponse> stream(
}
}

/**
* Remember whether a streamed chunk reported a {@code finish_reason}.
*
* <p>A well-formed stream carries one on its last chunk before the {@code [DONE]} sentinel, so
* observing either proves the provider finished the response rather than being cut off.
*
* @param response the parsed response, which may carry several choices
* @param sawFinishReason set once any choice reports a {@code finish_reason}
*/
private static void markFinishReason(OpenAIResponse response, AtomicBoolean sawFinishReason) {
if (sawFinishReason.get()) {
return;
}
List<OpenAIChoice> choices = response.getChoices();
if (choices == null) {
return;
}
for (OpenAIChoice choice : choices) {
if (choice != null && choice.getFinishReason() != null) {
sawFinishReason.set(true);
return;
}
}
}

/**
* Fail the stream when it ended before the response was complete.
*
* <p>An interrupted generation is indistinguishable from a finished one once the underlying
* connection is gone, so the only evidence left is the terminating marker: either the SSE
* {@code [DONE]} sentinel or a chunk carrying {@code finish_reason}. Without both, the text
* delivered so far is a prefix of the answer and must not be persisted or shown as a full one.
*
* <p>The built-in transports already terminate their fluxes on {@code [DONE]} and never hand the
* marker to this method, so in practice {@code finish_reason} is the signal that matters; the
* {@code [DONE]} check covers custom {@link HttpTransport} implementations that pass it through.
*
* <p>The error carries an {@link EOFException} cause so it is classified as retryable: a body
* that stopped mid-stream is an I/O-level truncation, not a request the server rejected.
*
* @param seenChunk whether any streamed chunk was delivered at all
* @param sawDoneMarker whether the {@code [DONE]} sentinel was received
* @param sawFinishReason whether any chunk reported a {@code finish_reason}
* @return an empty flux when the response completed, an error flux when it did not
*/
private static <T> Flux<T> failIfTruncated(
AtomicBoolean seenChunk, AtomicBoolean sawDoneMarker, AtomicBoolean sawFinishReason) {
if (sawDoneMarker.get() || sawFinishReason.get() || !seenChunk.get()) {
return Flux.empty();
}
return Flux.error(
new OpenAIException(
"Streaming response ended before completion: the stream closed without the"
+ " [DONE] sentinel and no chunk reported a finish_reason, so the"
+ " partial response is truncated",
new EOFException("SSE stream ended without [DONE]")));
}

/**
* Resolve the actual HTTP error status code when the API returns 200 OK
* but contains an error payload.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ private static MockResponse successStreamResponse(String content) {
return new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/event-stream")
.setBody(sseChunk(content) + sseDone());
.setBody(sseChunk(content) + sseFinish("stop") + sseDone());
}

private static String sseChunk(String content) {
Expand All @@ -288,6 +288,18 @@ private static String sseChunk(String content) {
+ "\"},\"finish_reason\":null}]}\n\n";
}

/**
* The terminating chunk of a real OpenAI stream: it carries the {@code finish_reason} that
* proves the response completed. Without it a stream that simply stops is indistinguishable
* from one the gateway cut off, which {@code OpenAIClient} now reports as a failure.
*/
private static String sseFinish(String finishReason) {
return "data: {\"object\":\"chat.completion.chunk\",\"choices\":[{\"delta\":{},"
+ "\"finish_reason\":\""
+ finishReason
+ "\"}]}\n\n";
}

private static String sseDone() {
return "data: [DONE]\n\n";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,35 +15,52 @@
*/
package io.agentscope.extensions.model.openai;

import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;

import io.agentscope.core.model.ExecutionConfig;
import io.agentscope.core.model.GenerateOptions;
import io.agentscope.core.model.transport.HttpRequest;
import io.agentscope.core.model.transport.HttpResponse;
import io.agentscope.core.model.transport.HttpTransport;
import io.agentscope.core.model.transport.HttpTransportFactory;
import io.agentscope.extensions.model.openai.dto.OpenAIMessage;
import io.agentscope.extensions.model.openai.dto.OpenAIRequest;
import io.agentscope.extensions.model.openai.dto.OpenAIResponse;
import io.agentscope.extensions.model.openai.exception.OpenAIException;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;

/**
* Tests that the OpenAI streaming response is terminated deterministically by the SSE
* {@code [DONE]} sentinel, independent of the underlying HTTP connection lifecycle.
* Tests that the OpenAI streaming response is terminated deterministically by the SSE {@code
* [DONE]} sentinel, and that a stream that ends without ever proving it finished fails instead of
* being accepted as a complete answer.
*
* <p>The first case is the regression test for {@code [DONE]} being merely filtered out instead of
* completing the {@link Flux}: against an OpenAI-compatible gateway that keeps the connection open
* (HTTP keep-alive) after emitting {@code [DONE]}, the stream would only complete when the socket
* was eventually closed by an idle timeout, stalling the ReAct turn for up to a minute.
*
* <p>Regression test for the case where {@code [DONE]} was merely filtered out instead of
* completing the {@link Flux}. Against an OpenAI-compatible gateway that keeps the connection
* open (HTTP keep-alive) after emitting {@code [DONE]}, the stream would only complete when the
* socket was eventually closed by an idle timeout, stalling the ReAct turn for up to a minute.
* <p>The other cases are the regression test for a connection closed mid-generation: that produces
* {@code onComplete}, not {@code onError}, so the truncated text used to be persisted and shown as
* if the model had finished normally.
*/
@Tag("unit")
@DisplayName("OpenAI Stream Termination Tests")
class OpenAIStreamTerminationTest {

private static final String CHUNK_CONTENT =
"{\"id\":\"1\",\"choices\":[{\"delta\":{\"content\":\"hello\"},\"index\":0}]}";
private static final String CHUNK_CONTENT_MORE =
"{\"id\":\"1\",\"choices\":[{\"delta\":{\"content\":\" world\"},\"index\":0}]}";
private static final String CHUNK_FINISH =
"{\"id\":\"1\",\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\",\"index\":0}]}";

Expand All @@ -69,26 +86,126 @@ public void close() {}
};
}

/**
* A transport that emits the given SSE lines and then completes cleanly — simulating a
* connection closed by the provider or by a gateway in front of it.
*/
private static HttpTransport transportEmitting(List<String> sseLines) {
return new HttpTransport() {
@Override
public HttpResponse execute(HttpRequest request) {
throw new UnsupportedOperationException("not used in this test");
}

@Override
public Flux<String> stream(HttpRequest request) {
return Flux.fromIterable(sseLines);
}

@Override
public void close() {}
};
}

private static OpenAIRequest sampleRequest() {
return OpenAIRequest.builder()
.model("gpt-4o-mini")
.messages(List.of(OpenAIMessage.builder().role("user").content("hi").build()))
.build();
}

private static Flux<OpenAIResponse> streamFrom(OpenAIClient client) {
return client.stream(
"test-key", "http://localhost", sampleRequest(), GenerateOptions.builder().build());
}

@Test
@DisplayName("Stream should complete on [DONE] even if the connection stays open")
void streamCompletesOnDoneSentinelWithoutWaitingForConnectionClose() {
OpenAIClient client = new OpenAIClient(keepAliveTransportAfterDone());

StepVerifier.create(
client.stream(
"test-key",
"http://localhost",
sampleRequest(),
GenerateOptions.builder().build()))
StepVerifier.create(streamFrom(client))
.expectNextCount(2)
.expectComplete()
.verify(Duration.ofSeconds(5));
}

@Test
@DisplayName("Stream should fail when it ends without [DONE] and without a finish_reason")
void streamFailsWhenConnectionClosesBeforeTheResponseCompletes() {
OpenAIClient client =
new OpenAIClient(transportEmitting(List.of(CHUNK_CONTENT, CHUNK_CONTENT_MORE)));

StepVerifier.create(streamFrom(client))
.expectNextCount(2)
.expectErrorSatisfies(
error -> {
OpenAIException typed = assertInstanceOf(OpenAIException.class, error);
assertTrue(
typed.getMessage().contains("ended before completion"),
"unexpected message: " + typed.getMessage());
assertTrue(
ExecutionConfig.RETRYABLE_ERRORS.test(typed),
"a truncated stream must be retryable, otherwise the retry"
+ " machinery never sees it");
})
.verify(Duration.ofSeconds(5));
}

@Test
@DisplayName("Stream should complete when finish_reason arrives without [DONE]")
void streamCompletesWhenFinishReasonArrivesWithoutDoneSentinel() {
OpenAIClient client =
new OpenAIClient(transportEmitting(List.of(CHUNK_CONTENT, CHUNK_FINISH)));

StepVerifier.create(streamFrom(client))
.expectNextCount(2)
.expectComplete()
.verify(Duration.ofSeconds(5));
}

@Test
@DisplayName("Stream should still complete on [DONE] when no chunk carries a finish_reason")
void streamCompletesOnDoneSentinelWithoutFinishReason() {
OpenAIClient client = new OpenAIClient(transportEmitting(List.of(CHUNK_CONTENT, "[DONE]")));

StepVerifier.create(streamFrom(client))
.expectNextCount(1)
.expectComplete()
.verify(Duration.ofSeconds(5));
}

@Test
@DisplayName("Stream over the JDK transport should fail when the server closes mid-stream")
void streamOverRealTransportFailsWhenTheServerClosesMidStream() throws IOException {
MockWebServer server = new MockWebServer();
server.start();
try {
// The body simply stops: no terminating chunk, no [DONE], and the connection is
// closed cleanly, which is what a gateway cutting the response short looks like.
server.enqueue(
new MockResponse()
.setResponseCode(200)
.setHeader("Content-Type", "text/event-stream")
.setBody(sseLine(CHUNK_CONTENT) + sseLine(CHUNK_CONTENT_MORE)));

OpenAIClient client = new OpenAIClient(HttpTransportFactory.getDefault());

StepVerifier.create(
client.stream(
"test-key",
server.url("/v1").toString(),
sampleRequest(),
GenerateOptions.builder().build()))
.expectNextCount(2)
.expectErrorSatisfies(error -> assertInstanceOf(OpenAIException.class, error))
.verify(Duration.ofSeconds(10));
} finally {
server.shutdown();
}
}

private static String sseLine(String payload) {
return "data: " + payload + "\n\n";
}
}
Loading