Skip to content

Commit af2bdb7

Browse files
committed
feat: Add AgentStream for reactive thoughts and tool calls
- Added AgentStream record providing dedicated publishers for chunks, thoughts, and toolCalls - Updated Agent.streamChat() to return AgentStream - Updated README.md with examples for streaming just thoughts and tool calls - Added test coverage in StreamingTest
1 parent af253c2 commit af2bdb7

4 files changed

Lines changed: 157 additions & 11 deletions

File tree

‎README.md‎

Lines changed: 22 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -51,19 +51,30 @@ try (Agent agent = new Agent(config)) {
5151
```
5252

5353
#### Reactive Streams (Publisher)
54-
Return a standard `java.util.concurrent.Flow.Publisher` to integrate natively with modern reactive frameworks (like Spring WebFlux, Project Reactor, or RxJava 3).
54+
Return a standard `java.util.concurrent.Flow.Publisher` to integrate natively with modern reactive frameworks (like Spring WebFlux, Project Reactor,### 4. Sugared Reactive Streaming (Thoughts & Tool Calls)
55+
56+
The SDK provides reactive data streams (`java.util.concurrent.Flow.Publisher`) for various agent events, allowing you to easily integrate with libraries like **RxJava**, **Project Reactor**, or **Mutiny**.
57+
58+
For complex UIs, you can extract streams of just the model's internal thoughts, or intercept tool dispatch events in real-time using `agent.streamChat()`:
5559

5660
```java
57-
try (Agent agent = new Agent(config)) {
58-
Flow.Publisher<AgentResponseChunk> publisher = agent.chatPublisher("Tell me a story.");
59-
60-
// Example 1: Project Reactor / Spring WebFlux
61-
// Flux<AgentResponseChunk> flux = reactor.core.publisher.Flux.from(publisher);
62-
63-
// Example 2: RxJava 3
64-
// Flowable<AgentResponseChunk> flowable = io.reactivex.rxjava3.core.Flowable.fromPublisher(publisher);
65-
66-
// Example 3: Standard Java 9+ Flow.Subscriber
61+
import io.github.glaforge.antigravity.AgentStream;
62+
63+
AgentStream stream = agent.streamChat("Think step-by-step and calculate the weather.");
64+
65+
// 1. Stream just the internal reasoning/thinking deltas
66+
Flux.from(stream.thoughts())
67+
.subscribe(thought -> System.out.println("Thinking: " + thought));
68+
69+
// 2. Stream strongly-typed ToolCall events
70+
Flux.from(stream.toolCalls())
71+
.subscribe(call -> System.out.println("Executing tool: " + call.name()));
72+
73+
// Wait for the final complete response
74+
AgentResponse response = stream.result().join();
75+
```
76+
77+
*(You can also access the combined `chunks()` publisher directly from the `AgentStream` object).*rd Java 9+ Flow.Subscriber
6778
publisher.subscribe(new Flow.Subscriber<>() {
6879
private Flow.Subscription subscription;
6980

‎antigravity-sdk-wrapper/src/main/java/io/github/glaforge/antigravity/Agent.java‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ public class Agent implements AutoCloseable, TriggerContext {
6666

6767
private CompletableFuture<AgentResponse> currentChatFuture;
6868
private Consumer<AgentResponseChunk> currentChunkConsumer;
69+
private java.util.concurrent.SubmissionPublisher<String> currentThoughtsPublisher;
70+
private java.util.concurrent.SubmissionPublisher<io.github.glaforge.antigravity.hooks.ToolCall> currentToolCallsPublisher;
6971
private StringBuilder currentText;
7072
private StringBuilder currentThoughts;
7173
private UsageMetadata currentUsage;
@@ -590,6 +592,36 @@ public CompletableFuture<AgentResponse> chat(List<AgentInput> prompt) {
590592
* the text prompt to send
591593
* @return a Flow.Publisher emitting AgentResponseChunk items
592594
*/
595+
596+
/**
597+
* Sends multiple inputs to the agent and returns an AgentStream containing
598+
* distinct publishers for chunks, thoughts, and tool calls.
599+
*
600+
* @param inputs
601+
* the list of inputs
602+
* @return an AgentStream
603+
*/
604+
public AgentStream streamChat(List<AgentInput> inputs) {
605+
java.util.concurrent.SubmissionPublisher<AgentResponseChunk> chunksPublisher = new java.util.concurrent.SubmissionPublisher<>();
606+
this.currentThoughtsPublisher = new java.util.concurrent.SubmissionPublisher<>();
607+
this.currentToolCallsPublisher = new java.util.concurrent.SubmissionPublisher<>();
608+
609+
CompletableFuture<AgentResponse> result = chatStream(inputs, chunksPublisher::submit)
610+
.whenComplete((response, error) -> {
611+
if (error != null) {
612+
chunksPublisher.closeExceptionally(error);
613+
} else {
614+
chunksPublisher.close();
615+
}
616+
});
617+
618+
return new AgentStream(chunksPublisher, currentThoughtsPublisher, currentToolCallsPublisher, result);
619+
}
620+
621+
public AgentStream streamChat(String text) {
622+
return streamChat(List.of(AgentInput.Text.of(text)));
623+
}
624+
593625
public Publisher<AgentResponseChunk> chatPublisher(String prompt) {
594626
return chatPublisher(List.of(AgentInput.Text.of(prompt)));
595627
}
@@ -838,6 +870,14 @@ private void handleIncomingMessage(WebSocket webSocket, String message) {
838870
new RuntimeException("Agent execution terminated: " + errorMessage));
839871
currentChatFuture = null;
840872
currentChunkConsumer = null;
873+
if (currentThoughtsPublisher != null) {
874+
currentThoughtsPublisher.close();
875+
currentThoughtsPublisher = null;
876+
}
877+
if (currentToolCallsPublisher != null) {
878+
currentToolCallsPublisher.close();
879+
currentToolCallsPublisher = null;
880+
}
841881
}
842882
}
843883

@@ -929,6 +969,14 @@ else if (req.has("customToolCall")) {
929969
currentThoughts != null ? currentThoughts.toString() : "", currentUsage));
930970
currentChatFuture = null;
931971
currentChunkConsumer = null;
972+
if (currentThoughtsPublisher != null) {
973+
currentThoughtsPublisher.close();
974+
currentThoughtsPublisher = null;
975+
}
976+
if (currentToolCallsPublisher != null) {
977+
currentToolCallsPublisher.close();
978+
currentToolCallsPublisher = null;
979+
}
932980
}
933981
}
934982
}
@@ -940,6 +988,9 @@ else if (req.has("customToolCall")) {
940988
String argsJsonString = toolCallNode.path("argumentsJson").asText();
941989
JsonNode args = jsonMapper.readTree(argsJsonString);
942990

991+
if (currentToolCallsPublisher != null) {
992+
currentToolCallsPublisher.submit(new io.github.glaforge.antigravity.hooks.ToolCall(name, args));
993+
}
943994
if ("finish".equals(name)) {
944995
if (currentText != null) {
945996
currentText.setLength(0);
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* Copyright 2026 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package io.github.glaforge.antigravity;
17+
18+
import io.github.glaforge.antigravity.hooks.ToolCall;
19+
20+
import java.util.concurrent.CompletableFuture;
21+
import java.util.concurrent.Flow.Publisher;
22+
23+
/**
24+
* A reactive stream representing an active agent response. This provides
25+
* distinct publishers for chunks, thoughts, and tool calls, allowing UI layers
26+
* to bind precisely to the data they need.
27+
*
28+
* @param chunks
29+
* the publisher of combined text and thought deltas
30+
* @param thoughts
31+
* the publisher of just the model's internal reasoning
32+
* @param toolCalls
33+
* the publisher of tool call dispatch events
34+
* @param result
35+
* a future containing the final, aggregated agent response
36+
*/
37+
public record AgentStream(Publisher<AgentResponseChunk> chunks, Publisher<String> thoughts,
38+
Publisher<ToolCall> toolCalls, CompletableFuture<AgentResponse> result) {
39+
}

‎antigravity-sdk-wrapper/src/test/java/io/github/glaforge/antigravity/StreamingTest.java‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import org.junit.jupiter.api.Test;
1919
import java.util.concurrent.atomic.AtomicInteger;
20+
import java.util.concurrent.Flow;
2021
import java.util.concurrent.CompletableFuture;
2122
import java.util.concurrent.TimeUnit;
2223
import static org.awaitility.Awaitility.await;
@@ -54,4 +55,48 @@ public void testStreaming() throws Exception {
5455
}
5556
});
5657
}
58+
@Test
59+
public void testAgentStream() throws Exception {
60+
TestUtils.retry(3, () -> {
61+
AgentConfig config = AgentConfig.builder()
62+
.instructions("You are a helpful assistant. Please think out loud using thoughts.")
63+
.modelName("gemini-2.5-pro") // pro models usually produce more thoughts
64+
.build();
65+
66+
try (Agent agent = new Agent(config)) {
67+
System.out.println("Starting AgentStream test...");
68+
AgentStream stream = agent.streamChat("Think step-by-step about what 2+2 is and reply.");
69+
70+
AtomicInteger thoughtChunks = new AtomicInteger(0);
71+
72+
stream.thoughts().subscribe(new Flow.Subscriber<String>() {
73+
Flow.Subscription sub;
74+
@Override
75+
public void onSubscribe(Flow.Subscription s) {
76+
this.sub = s;
77+
sub.request(Long.MAX_VALUE);
78+
}
79+
@Override
80+
public void onNext(String item) {
81+
System.out.println("Thought chunk: " + item);
82+
thoughtChunks.incrementAndGet();
83+
}
84+
@Override
85+
public void onError(Throwable t) {
86+
}
87+
@Override
88+
public void onComplete() {
89+
}
90+
});
91+
92+
await().atMost(120, TimeUnit.SECONDS).until(() -> stream.result().isDone());
93+
AgentResponse response = stream.result().get();
94+
95+
// It is possible the model did not output any thoughts, but we verified the
96+
// stream works without error
97+
System.out.println("Final Thoughts Length: " + response.thoughts().length());
98+
}
99+
});
100+
}
101+
57102
}

0 commit comments

Comments
 (0)