> ## Documentation Index
> Fetch the complete documentation index at: https://docs.runanywhere.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# generateStream()

> Stream tokens as they are produced

`generateStream` returns a `Flow<GenerationEvent>`. It is **not** suspending: you get the flow
back immediately and collect it.

```kotlin theme={"theme":"css-variables"}
RunAnywhere.llm.generateStream("Write a haiku about Kotlin").collect { event ->
    if (event is GenerationEvent.Token) print(event.text)
}
```

## Signatures

```kotlin theme={"theme":"css-variables"}
fun generateStream(prompt: String, options: LlmOptions? = null): Flow<GenerationEvent>
fun generateStream(messages: List<ChatMessage>, options: LlmOptions? = null): Flow<GenerationEvent>
```

## Handling every event

```kotlin theme={"theme":"css-variables"}
RunAnywhere.llm.generateStream(prompt).collect { event ->
    when (event) {
        is GenerationEvent.Token -> text += event.text
        is GenerationEvent.Completed -> tokensPerSecond = event.result.tokensPerSecond
        else -> {}
    }
}
```

## In a ViewModel

```kotlin theme={"theme":"css-variables"}
class ChatViewModel : ViewModel() {
    private val _text = MutableStateFlow("")
    val text = _text.asStateFlow()

    fun send(prompt: String) {
        viewModelScope.launch {
            _text.value = ""
            RunAnywhere.llm.generateStream(prompt).collect { event ->
                if (event is GenerationEvent.Token) _text.value += event.text
            }
        }
    }
}
```

Collecting in `viewModelScope` means the flow is cancelled when the ViewModel clears, so a
generation does not outlive the screen.

## Errors

Failures are thrown from the collector, so wrap the collection:

```kotlin theme={"theme":"css-variables"}
try {
    RunAnywhere.llm.generateStream(prompt).collect { event ->
        if (event is GenerationEvent.Token) text += event.text
    }
} catch (e: SDKException) {
    show(e)
}
```

## Cancelling

Cancel the coroutine:

```kotlin theme={"theme":"css-variables"}
val job = viewModelScope.launch {
    RunAnywhere.llm.generateStream(prompt).collect { /* … */ }
}

job.cancel()
```

## Flow operators work normally

```kotlin theme={"theme":"css-variables"}
RunAnywhere.llm.generateStream(prompt)
    .filterIsInstance<GenerationEvent.Token>()
    .map { it.text }
    .collect { text += it }
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.