LLM streaming delivers output token by token as it’s generated. This reduces latency, as users see the first results in the UI within milliseconds instead of waiting seconds for a complete answer.
However, current major frameworks don’t support these functionalities.
The major Java frameworks for LLM integration, Spring AI and LangChain4j, support streaming at a limited level. We can get a live stream of text as the model generates it, but neither framework turns that stream into a collection of typed objects out of the box.
Note that model providers differ in how they combine streaming with thinking and tools. Anthropic’s native thinking produces explicit reasoning blocks, but other providers may not surface reasoning in the same way.
First, we show how to stream a single object without reasoning and tool calls. The test method is whenStreaming_thenReceivesParkingRecommendation():
void whenStreaming_thenReceivesParkingRecommendation() {
streamParkingRecommendations(PARKING_PROMPT);
}
PARKING_PROMPT asks for a single parking recommendation, and the private method streamParkingRecommendations() does the actual object streaming:
Flux<ParkingRecommendation> stream = new StreamingPromptRunnerBuilder(runner)
.streaming()
.withPrompt(PARKING_PROMPT)
.createObjectStream(ParkingRecommendation.class);
stream
.timeout(Duration.ofSeconds(120))
.doOnNext(rec -> {
logger.info(
"Received recommendation: scenario={}, option={}, cost={}, summary={}",
rec.scenario(),
rec.chosenOption(),
rec.estimatedTotalCost(),
rec.summary());
}).blockLast(Duration.ofSeconds(240));
Here:
- We create a Flux<ParkingRecommendation> by calling createObjectStream(). A Flux is a Reactor type representing an asynchronous sequence of zero or more elements that arrive over time rather than all at once. In this example, the model emits a ParkingRecommendation object.
- PARKING_PROMPT instructs the LLM to find the optimal parking option out of three available options: street parking, metered parking, and garage parking. The prompt specifies constraints and costs for each alternative.
- The pipeline subscribes with doOnNext() to collect and log each object.
- blockLast() blocks the calling thread until the stream completes. This is appropriate in a test context, though production code would chain further reactive operators instead of blocking. For example, we would return the Flux directly to a web endpoint that streams the response to the client.
We can run the unit test method whenStreaming_thenReceivesParkingRecommendation() like this:
$ mvn test -pl embabel-streaming -P integration -Dtest=StreamingWithThinkingAndToolingLiveTest#whenStreaming_thenReceivesParkingRecommendation
After the stream completes, logs confirm the stream delivers a complete ParkingRecommendation object:
17:34:13.781 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=Midtown Manhattan parking for 3-hour client meeting with 30-minute arrival buffer, option=GARAGE, cost=90, summary=Choose garage parking. The meeting duration (3 hours) exceeds the metered parking limit (2 hours), eliminating that option. Street parking in Midtown Manhattan is extremely unreliable and searching could make you late for the meeting. The guaranteed spot and ability to stay for the full meeting duration justifies the $90 cost for this professional context.
The object includes all the properties we expect: scenario, chosenOption, estimatedTotalCost, and summary.
5. Streaming Multiple Objects
The streamParkingRecommendations() method can stream multiple objects. To show it, we request three recommendations with TIMED_PARKING_PROMPT:
void whenStreamingMultipleScenarios_thenReceivesRecommendationPerScenario() {
streamParkingRecommendations(TIMED_PARKING_PROMPT);
}
When streaming:
- doOnNext() collects and logs each object as it arrives
- blockLast() waits for the stream to complete
We can run the unit test method whenStreamingMultipleScenarios_thenReceivesRecommendationPerScenario like this:
$ mvn test -pl embabel-streaming -P integration -Dtest=StreamingWithThinkingAndToolingLiveTest#whenStreamingMultipleScenarios_thenReceivesRecommendationPerScenario
Instead of obtaining a single batched response with all objects, we get each ParkingRecommendation as a separate object as it is received:
18:31:24.200 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=Early morning (before 8am), option=STREET, cost=0, summary=Arrive before 8am to take advantage of free street parking. Meters are not enforced until 8am, providing zero-cost parking. Be prepared to feed the meter or move to a garage if your meeting extends past 8am.
18:31:27.354 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=Business hours (9am-5pm), option=GARAGE, cost=45, summary=For a 3-hour business meeting with only a 30-minute arrival window, a parking garage is the most reliable option. Street parking in Midtown is extremely competitive during peak hours, and the time spent searching could cause you to miss your meeting. Garage rates typically range $35-55 for 3 hours in Midtown Manhattan.
18:31:28.895 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=Evening (after 6pm), option=STREET, cost=0, summary=Street meters become free after 6pm, making this the best option if you're confident your 3-hour meeting will end before 9pm. However, have a backup plan: identify a 24-hour garage nearby in case your meeting runs late, as many garages close at 9pm and you could be locked in or locked out.
The logged timing of each object creation certifies that complete objects are obtained sequentially and that the collection is filled incrementally.
6. Streaming with Reasoning
First, we must enable deep thinking by configuring LlmOptions with a token budget:
void whenStreamingWithThinking_thenReceivesReasoningAndRecommendation() {
LlmOptions thinkingOptions = new LlmOptions().withThinking(Thinking.withTokenBudget(8000));
PromptRunner runner = ai.withDefaultLlm().withLlm(thinkingOptions);
streamParkingRecommendationsWithThinking(runner, TIMED_PARKING_PROMPT);
}
The budget controls how many tokens the model may spend on reasoning before producing the answer, and it must be lower than max_tokens (8192 for claude-opus-4-8).
Objects are streamed in the private method streamParkingRecommendationsWithThinking(). It uses createObjectStreamWithThinking() instead of createObjectStream(), and the return type changes accordingly:
Flux<StreamingEvent<ParkingRecommendation>> stream = new StreamingPromptRunnerBuilder(runner)
.streaming()
.withPrompt(prompt)
.createObjectStreamWithThinking(ParkingRecommendation.class);
StreamingEvent wraps typed objects and reasoning fragments, as the stream interleaves both kinds of events. The doOnNext() callback distinguishes them via the event.isObject() and event.isThinking() checks, collecting them into separate lists, received for objects and reasoning for thinking fragments:
.doOnNext(event -> {
if (event.isObject()) {
ParkingRecommendation rec = event.getObject();
if (rec != null) {
logger.info("Received recommendation: scenario={}, option={}, cost={}, summary={}",
rec.scenario(), rec.chosenOption(), rec.estimatedTotalCost(), rec.summary());
}
} else if (event.isThinking() && !isTagOnly(event.getThinking())) {
logger.info("Received reasoning: {}", event.getThinking());
} })
We can run the unit test whenStreamingWithThinking_thenReceivesReasoningAndRecommendation() as follows:
$ mvn test -pl embabel-streaming -P integration -Dtest=StreamingWithThinkingAndToolingLiveTest#whenStreamingWithThinking_thenReceivesReasoningAndRecommendation
Logs demonstrate that recommendations and reasoning fragments are processed as they arrive.
16:10:03.315 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received reasoning: Scenario 1: Early morning before 8am, meters are free. STREET is best, cost 0.
16:10:04.376 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=Early morning (before 8am), option=STREET, cost=0, summary=Street meters are free before 8am, so park at a street meter for zero cost. Arrive before the 8am paid window begins and be ready to move or pay once metering starts.
16:10:05.501 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received reasoning: Scenario 2: Business hours 9am-5pm, 3-hour stay, all paid options apply. Midtown meters are costly (~$5.50/hr) and often limited to 1-hour windows, risky for a 3-hour stay. A garage offers a reliable flat daytime rate (~$40-50). Choose GARAGE.
16:10:07.198 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=Business hours (9am-5pm), option=GARAGE, cost=45, summary=For a 3-hour daytime stay, a garage is most reliable. Midtown meters run high (~$5.50/hr) and often cap at 1-hour limits, making them impractical for 3 hours. A garage flat rate of roughly $45 avoids ticket risk and repeated meter trips.
16:10:08.288 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received reasoning: Scenario 3: Evening after 6pm, meters free. STREET is best at cost 0. Garages risk closing at 9pm, jeopardizing a 3-hour stay. Street meter is free and has no closing risk.
16:10:09.705 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=Evening (after 6pm), option=STREET, cost=0, summary=Meters are free after 6pm, so street parking costs nothing. Avoid garages here since some close at 9pm, putting a 3-hour stay at risk of being locked in or rushed. Street parking offers free, flexible exit timing.
Note that each reasoning block represents a single line, as Embabel aggregates mini-chunks into a single line.
A simple helper, isTagOnly(), strips empty reasoning inside XML tags (such as <think></think>).
Finally, let’s combine tool calling with streaming and thinking. For a blocking call, the Baeldung article LLM Tool Call Reasoning Using Embabel Agentic AI Framework shows how tool calls benefit from LLM reasoning.
The API is very similar to the reasoning use case, except for the tool registration withToolObject(new ParkingTooling()) and a logging inspector for observability:
void whenStreamingWithThinkingAndTooling_thenReceivesRecommendationAndReasoning() {
PromptRunner runner = ai.withDefaultLlm()
.withToolObject(new ParkingTooling())
.withToolCallInspectors(new ToolCallLoggingInspector(LogLevel.INFO, logger));
streamParkingRecommendationsWithThinking(runner, TOOL_PARKING_PROMPT);
}
TOOL_PARKING_PROMPT instructs the model to actively use the tools before giving three recommendations, and the streamParkingRecommendationsWithThinking() method streams them.
The pipeline uses the same createObjectStreamWithThinking() and the same event.isObject() / event.isThinking() pattern. The key difference is tool call timing: the model provides initial reasoning before calling tools, then reasons over the tool call results, and finally emits the objects.
We can run the unit test whenStreamingWithThinkingAndTooling_thenReceivesRecommendationAndReasoning() like this:
$ mvn test -pl embabel-streaming -P integration -Dtest=StreamingWithThinkingAndToolingLiveTest#whenStreamingWithThinkingAndTooling_thenReceivesRecommendationAndReasoning
18:29:24.236 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received reasoning: Let me probe all three parking options for Midtown Manhattan for a 3-hour meeting. Since arriving late is not acceptable, the garage (guaranteed) is likely best. Let me gather data.
18:29:26.039 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - beforeToolCall: tool=reserveGarage, argsLength=29
18:29:26.042 [boundedElastic-1] INFO Embabel - [distracted_nash] calling tool reserveGarage({"arg0": "Midtown Manhattan"})
18:29:26.045 [boundedElastic-1] INFO Embabel - [distracted_nash] tool reserveGarage returned Garage reserved near Midtown Manhattan ($30/hour, guaranteed) in 2ms with payload {"arg0": "Midtown Manhattan"}
18:29:26.047 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - afterToolCall: tool=reserveGarage, status=Text, resultLength=61, durationMs=7
18:29:26.048 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - beforeToolCall: tool=findMeterParking, argsLength=40
18:29:26.049 [boundedElastic-1] INFO Embabel - [distracted_nash] calling tool findMeterParking({"arg0": "Midtown Manhattan", "arg1": 3})
18:29:26.050 [boundedElastic-1] INFO Embabel - [distracted_nash] tool findMeterParking returned Metered parking found near Midtown Manhattan ($5/hour, 2-hour limit) in 0ms with payload {"arg0": "Midtown Manhattan", "arg1": 3}
18:29:26.050 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - afterToolCall: tool=findMeterParking, status=Text, resultLength=68, durationMs=1
18:29:26.050 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - beforeToolCall: tool=findStreetParking, argsLength=40
18:29:26.050 [boundedElastic-1] INFO Embabel - [distracted_nash] calling tool findStreetParking({"arg0": "Midtown Manhattan", "arg1": 3})
18:29:26.050 [boundedElastic-1] INFO Embabel - [distracted_nash] tool findStreetParking returned Street parking found near Midtown Manhattan (free) in 0ms with payload {"arg0": "Midtown Manhattan", "arg1": 3}
18:29:26.050 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - afterToolCall: tool=findStreetParking, status=Text, resultLength=50, durationMs=0
18:29:27.131 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received reasoning: Analysis:
18:29:28.306 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received reasoning: - GARAGE: $30/hr × 3 = $90, guaranteed, no risk of being late. Best for "late is not acceptable."
18:29:28.948 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received reasoning: - METER: $5/hr × 3 = $15, but 2-hour limit means it doesn't cover 3 hours; would require moving the car mid-meeting — not viable without interrupting, and finding a space takes time. Risk of lateness.
18:29:29.629 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received reasoning: - STREET: Free, but uncertain and may take time to find — risk of arriving late. Least recommended.
18:29:29.639 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received reasoning: Since arriving late is not acceptable, GARAGE is best.
18:29:31.646 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=3-hour client meeting in Midtown Manhattan starting in 30 minutes; arriving late is unacceptable, option=GARAGE, cost=90, summary=BEST: Reserve the garage. At $30/hour for 3 hours ($90), it is guaranteed near the destination with no search time, fully eliminating any risk of arriving late. Worth the premium when punctuality is non-negotiable.
18:29:33.522 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=3-hour client meeting in Midtown Manhattan starting in 30 minutes; arriving late is unacceptable, option=METER, cost=15, summary=SECOND: Metered parking is cheap at $5/hour ($15), but it carries a 2-hour limit, so it does not cover the full 3-hour meeting and would force you to interrupt the meeting to move or refeed the car. Availability is only moderate, adding some search time. Acceptable only as a fallback.
18:29:35.205 [boundedElastic-1] INFO StreamingWithThinkingAndToolingLiveTest - Received recommendation: scenario=3-hour client meeting in Midtown Manhattan starting in 30 minutes; arriving late is unacceptable, option=STREET, cost=0, summary=THIRD: Free street parking costs nothing, but it is uncertain and can require significant time to find a spot in Midtown. With only 30 minutes before the meeting and lateness unacceptable, this option poses the highest risk and is least recommended.
Similar to whenStreamingWithThinking_thenReceivesReasoningAndRecommendation(), the stream delivers both a recommendation and a reasoning block (after the tools do their tasks).
8. Conclusion
In this article, we showed how to use the Embabel Fluent API to produce a stream of typed Java objects, with thinking and tool results handled by the framework.
Streaming raw text is straightforward in both Spring AI and LangChain4j, but streaming typed objects is not something either framework handles out of the box. Embabel addresses this at the framework level, removing the need to manually buffer tokens, parse NDJSON, or filter reasoning blocks. The same pattern scales from a single object to a collection and from a simple prompt to a multi-tool reasoning chain. For applications where both structure and responsiveness matter, this removes a layer of boilerplate that would otherwise fall on every team building agentic AI applications.
The code backing this article is available on GitHub. Once you're
logged in as a Baeldung Pro Member, start learning and coding on the project.