liveBook · Manning

Stream()

As explained in Spring AI in Action

stream() is a ChatClient operation that initiates a streamed response instead of waiting for a complete response.

stream() makes ChatClient emit an LLM response incrementally instead of waiting for the complete answer. The operation returns Flux<String>, whose pieces typically arrive one word at a time. section 3.4.3

Use streaming by changing the application at three points:

  • Replace call() with stream().content() in the service. section 3.4.3
  • Return the resulting Flux from the controller. section 3.4.3
  • Configure the endpoint for a streamed response MIME type rather than application/json. section 3.4.3
Listing 3.7 A board game service that streams the response
@Override
public Flux<String> askQuestion(Question question) {    #1
  var gameRules = gameRulesService.getRulesFor(question.gameTitle());

  return chatClient.prompt()
      .system(systemSpec -> systemSpec
          .text(promptTemplate)
          .param("gameTitle", question.gameTitle())
          .param("rules", gameRules))
      .user(question.question())
      .stream()         #2
      .content();
}

Streams a board-game answer through ChatClient after enriching the prompt with game rules. section 3.4.3

How Spring AI in Action covers it

How deep it goes
Explains call changes, Flux<String>, controller returns, and MIME handling while deferring deeper Project Reactor study.
Examples
Uses a board-game question service, AskController, HTTPie requests, and incremental answer chunks.
What it assumes
Assumes a working ChatClient application and introduces Flux as zero-to-many reactive data pieces.
What you can do after
Apply via ChatClient by returning Flux<String>, calling stream().content(), and exposing the reactive result from a controller.
How it connects
Connects ChatClient streaming with Project Reactor, Flux, reactive programming, and controller endpoints.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring AI in Action. The section links point to the parts of the book it draws on.