Skip to content

Commit e8dfcb0

Browse files
damianmomotgooglecopybara-github
authored andcommitted
feat: resume Gemini generations paused with a continuation token
PiperOrigin-RevId: 992253585
1 parent 17249d6 commit e8dfcb0

4 files changed

Lines changed: 1136 additions & 14 deletions

File tree

‎core/src/main/java/com/google/adk/models/Gemini.java‎

Lines changed: 109 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,9 @@
2020

2121
import com.google.adk.Version;
2222
import com.google.adk.internal.http.HttpClientFactory;
23+
import com.google.adk.models.GeminiContinuation.ResumeRequest;
24+
import com.google.adk.models.GeminiContinuation.StreamedOutput;
25+
import com.google.common.annotations.VisibleForTesting;
2326
import com.google.common.collect.ImmutableList;
2427
import com.google.common.collect.ImmutableMap;
2528
import com.google.errorprone.annotations.CanIgnoreReturnValue;
@@ -38,11 +41,14 @@
3841
import com.google.genai.types.PartialArg;
3942
import io.reactivex.rxjava3.core.Flowable;
4043
import java.time.Duration;
44+
import java.util.ArrayDeque;
4145
import java.util.ArrayList;
46+
import java.util.Deque;
4247
import java.util.LinkedHashMap;
4348
import java.util.List;
4449
import java.util.Map;
4550
import java.util.Objects;
51+
import java.util.Optional;
4652
import java.util.concurrent.CompletableFuture;
4753
import java.util.concurrent.ExecutorService;
4854
import okhttp3.OkHttpClient;
@@ -276,31 +282,121 @@ public Flowable<LlmResponse> generateContent(LlmRequest llmRequest, boolean stre
276282
logger.trace("Request Contents: {}", llmRequest.contents());
277283
logger.trace("Request Config: {}", config);
278284

285+
List<Content> contents = llmRequest.contents();
279286
if (stream) {
280287
logger.debug("Sending streaming generateContent request to model {}", effectiveModelName);
281288
CompletableFuture<ResponseStream<GenerateContentResponse>> streamFuture =
282-
apiClient.async.models.generateContentStream(
283-
effectiveModelName, llmRequest.contents(), config);
284-
289+
apiClient.async.models.generateContentStream(effectiveModelName, contents, config);
285290
return Flowable.defer(
286291
() ->
287-
processRawResponses(
288-
Flowable.fromFuture(streamFuture).flatMapIterable(iterable -> iterable)));
292+
streamResumingPauses(
293+
effectiveModelName, new GeminiContinuation(contents, config), streamFuture));
289294
} else {
290295
logger.debug("Sending generateContent request to model {}", effectiveModelName);
291-
return Flowable.fromFuture(
292-
apiClient
293-
.async
294-
.models
295-
.generateContent(effectiveModelName, llmRequest.contents(), config)
296-
.thenApplyAsync(LlmResponse::create));
296+
CompletableFuture<GenerateContentResponse> responseFuture =
297+
apiClient.async.models.generateContent(effectiveModelName, contents, config);
298+
return Flowable.defer(
299+
() ->
300+
generateResumingPauses(
301+
effectiveModelName, new GeminiContinuation(contents, config), responseFuture));
297302
}
298303
}
299304

305+
@VisibleForTesting
300306
static Flowable<LlmResponse> processRawResponses(Flowable<GenerateContentResponse> rawResponses) {
301307
return Flowable.defer(() -> new StreamingResponseAggregator().process(rawResponses));
302308
}
303309

310+
/**
311+
* Returns the final response of a generation, sending another request each time the model pauses.
312+
* Repeats instead of recursing, so a generation resumed many times keeps a flat stack.
313+
*/
314+
private Flowable<LlmResponse> generateResumingPauses(
315+
String modelName,
316+
GeminiContinuation continuation,
317+
CompletableFuture<GenerateContentResponse> firstResponse) {
318+
Deque<CompletableFuture<GenerateContentResponse>> responses = new ArrayDeque<>();
319+
responses.add(firstResponse);
320+
return Flowable.defer(() -> Flowable.fromFuture(responses.remove()))
321+
.mapOptional(response -> completeOrResume(modelName, continuation, response, responses))
322+
.repeatUntil(responses::isEmpty);
323+
}
324+
325+
/**
326+
* Returns the final response of the generation, or empty after queueing the request to resume it.
327+
*/
328+
private Optional<LlmResponse> completeOrResume(
329+
String modelName,
330+
GeminiContinuation continuation,
331+
GenerateContentResponse response,
332+
Deque<CompletableFuture<GenerateContentResponse>> responses) {
333+
LlmResponse llmResponse = LlmResponse.create(response);
334+
Optional<ResumeRequest> next =
335+
continuation.advance(
336+
GeminiContinuation.resumeToken(response),
337+
llmResponse.content().flatMap(Content::parts).orElse(ImmutableList.of()),
338+
llmResponse.usageMetadata().orElse(null));
339+
if (next.isEmpty()) {
340+
return Optional.of(continuation.complete(llmResponse));
341+
}
342+
responses.add(
343+
apiClient.async.models.generateContent(
344+
modelName, next.get().contents(), next.get().config()));
345+
return Optional.empty();
346+
}
347+
348+
/**
349+
* Streams a generation, sending another request each time the model pauses, and sums the usage of
350+
* all requests on the final response. Repeats instead of recursing, so a generation resumed many
351+
* times keeps a flat stack.
352+
*/
353+
private Flowable<LlmResponse> streamResumingPauses(
354+
String modelName,
355+
GeminiContinuation continuation,
356+
CompletableFuture<ResponseStream<GenerateContentResponse>> firstStream) {
357+
Deque<CompletableFuture<ResponseStream<GenerateContentResponse>>> streams = new ArrayDeque<>();
358+
streams.add(firstStream);
359+
StreamingResponseAggregator aggregator = new StreamingResponseAggregator();
360+
return Flowable.defer(() -> streamRequest(modelName, continuation, streams))
361+
.repeatUntil(streams::isEmpty)
362+
.concatMap(aggregator::processRawResponse)
363+
.concatWith(
364+
Flowable.defer(
365+
() -> aggregator.processFinalResponse().map(continuation::withSummedUsage)));
366+
}
367+
368+
/**
369+
* Streams the chunks of one request, then queues the request that resumes the generation, if any.
370+
*/
371+
private Flowable<GenerateContentResponse> streamRequest(
372+
String modelName,
373+
GeminiContinuation continuation,
374+
Deque<CompletableFuture<ResponseStream<GenerateContentResponse>>> streams) {
375+
StreamedOutput output = new StreamedOutput(continuation);
376+
return Flowable.fromFuture(streams.remove())
377+
.flatMapIterable(stream -> stream)
378+
.mapOptional(output::record)
379+
.doOnComplete(() -> queueResume(modelName, continuation, output, streams));
380+
}
381+
382+
/**
383+
* Records {@code output} in {@code continuation} and queues the request that resumes the
384+
* generation, if any.
385+
*/
386+
private void queueResume(
387+
String modelName,
388+
GeminiContinuation continuation,
389+
StreamedOutput output,
390+
Deque<CompletableFuture<ResponseStream<GenerateContentResponse>>> streams) {
391+
continuation
392+
.advance(output.token(), output.parts(), output.usage())
393+
.ifPresent(
394+
next ->
395+
streams.add(
396+
apiClient.async.models.generateContentStream(
397+
modelName, next.contents(), next.config())));
398+
}
399+
304400
@Override
305401
public BaseLlmConnection connect(LlmRequest llmRequest) {
306402
if (!apiClient.vertexAI()) {
@@ -326,7 +422,7 @@ protected CompletableFuture<GeminiLiveTransport> connectLiveTransport(
326422
return apiClient.async.live.connect(modelName, config).thenApply(GenAiLiveTransport::new);
327423
}
328424

329-
private static final class StreamingResponseAggregator {
425+
static final class StreamingResponseAggregator {
330426
private final List<Part> accumulatedSequence = new ArrayList<>();
331427
private final StringBuilder currentTextBuffer = new StringBuilder();
332428
// Always reassigned in accumulateParts() before it is read; the initializer is never observed.
@@ -337,7 +433,7 @@ private static final class StreamingResponseAggregator {
337433
* and nothing else worth keeping. Compared by rebuilding rather than against a single literal,
338434
* so a terminator that also carries an explicit {@code thought=false} is still recognised.
339435
*/
340-
private static boolean isStreamTerminator(Part part) {
436+
static boolean isStreamTerminator(Part part) {
341437
if (!part.text().map(String::isEmpty).orElse(false)) {
342438
return false;
343439
}

0 commit comments

Comments
 (0)