Docs Learn
Streaming
client.messages.stream returns the reply as an fs2.Stream of events while the model
writes it. It is resource-safe and cancellable.
You will learn
- How to print a reply piece by piece with
textDeltas - How to stream and still get the complete reply with
finalMessage - How to react to individual stream events
- What happens to the connection when you stop early
Text, piece by piece#
Import anthropic4s.syntax._ for the stream helpers. textDeltas keeps only the text;
finalMessage folds the stream into the complete reply:
import anthropic4s.syntax._
client.messages
.stream(request)
.textDeltas // just the text, piece by piece
.evalMap(IO.print)
.compile
.drain
client.messages.stream(request).finalMessage // or: stream, and keep only the complete reply
Events and the complete reply#
The stream carries every event the API sends. The Streaming example prints each text delta as a
side effect with evalTap, then folds the same stream into the complete reply to print its token
usage:
/** Prints the reply while it is being written, then the token usage. */
object Streaming extends IOApp.Simple {
def run: IO[Unit] =
Anthropic4s.fromEnv[IO].use { client =>
// Streaming has no request timeout to worry about, so the output limit can be generous.
val request = MessageRequest(
Model.ClaudeOpus5_5,
maxTokens = 64000,
MessageParam.user("Write a haiku about monads, then explain it.")
)
.withThinking(ThinkingConfig.adaptive)
client.messages
.stream(request)
.evalTap {
case StreamEvent.ContentBlockDelta(_, Delta.Text(text)) => IO.print(text)
case _ => IO.unit
}
.finalMessage // the same stream, folded into the complete reply
.flatMap(reply => IO.println(s"\n\n${reply.usage.show}"))
}
}
Stopping early#
Because the stream owns the connection, stopping it early closes the connection: take,
cancellation, or a timeout around it all do. There is nothing to clean up by hand.
Recap
stream(request).textDeltasfor the text,.finalMessagefor the whole reply.- The stream is an ordinary
fs2.Stream:evalTap,takeand timeouts all work. - Stopping the stream closes the connection.
Every snippet on this page is copied, character for character, from the
anthropic4s repository: its README, docs/play.md or examples/,
which compiles with the build.