Reference Messages
messages.stream
Sends a request and emits events as the reply is generated, as an fs2 Stream.
Reference#
stream(request, options?)#
def stream(request: MessageRequest, options: RequestOptions): Stream[F, StreamEvent]
def stream(request: MessageRequest): Stream[F, StreamEvent]
Parameters
request: aMessageRequest.options: optionalRequestOptionsfor this call.
Returns
A Stream[F, StreamEvent]: message start, content block deltas, message delta and stop events, as the API sends them.
Caveats
- Nothing is sent until the stream runs.
- Stopping early, with
takeor by cancelling, closes the connection. - Retries happen only before the response starts; a stream cut short fails with
StreamTruncated.
Stream helpers#
def textDeltas: Stream[F, String]
def finalMessage(implicit F: Concurrent[F]): F[Message]
def snapshots(implicit F: Concurrent[F]): Stream[F, Message]
textDeltas: only the text, piece by piece, as the model writes it.finalMessage: runs the stream to the end and returns the completeMessage.snapshots: the reply so far, after every event.
Caveats
- They come with
import anthropic4s.syntax._. - Each snapshot costs time in proportion to the reply's size; prefer
textDeltasfor display.
Usage#
Printing as it arrives#
client.messages.stream(request).textDeltas.evalMap(IO.print).compile.drain // print as it arrives
client.messages.stream(request).finalMessage // just the complete reply
client.messages.stream(request).evalTap(render).finalMessage // both
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
Streaming covers it step by step.
Every signature and example on this page is copied, character for character, from the public source of anthropic4s and its Scaladoc. The complete API, every type included, is in the Scaladoc of each module.