ui.MarkdownStream

ui.MarkdownStream(self, id, *, on_error='auto')

A component for streaming markdown or HTML content.

Parameters

id : str

A unique identifier for this MarkdownStream. In Shiny Core, make sure this id matches a corresponding output_markdown_stream call in the app’s UI.

on_error : Literal[‘auto’, ‘actual’, ‘sanitize’, ‘unhandled’] = 'auto'

How to handle errors that occur while streaming. When "unhandled", the app will stop running when an error occurs. Otherwise, a notification is displayed to the user and the app continues to run. * "auto": Sanitize the error message if the app is set to sanitize errors, otherwise display the actual error message. * "actual": Display the actual error message to the user. * "sanitize": Sanitize the error message before displaying it to the user. * "unhandled": Do not display any error message to the user.

Note

Markdown is parsed on the client via marked.js. Consider using markdown for server-side rendering of markdown content.

Examples

#| standalone: true
#| components: [editor, viewer]
#| layout: vertical
#| viewerHeight: 400

## file: app.py
import asyncio

import requests

from shiny import App, reactive, ui

app_ui = ui.page_fluid(
    ui.card(
        ui.card_header("Shiny's README.md"),
        ui.output_markdown_stream("shiny_readme"),
        height="400px",
        class_="mt-3",
        full_screen=True,
    ),
)


def server(input, output, session):
    # Read in the README.md file from the py-shiny repository
    readme = requests.get(
        "https://raw.githubusercontent.com/posit-dev/py-shiny/refs/heads/main/README.md"
    )
    readme_chunks = readme.text.replace("\n", " \n ").split(" ")

    # Generate words from the README.md file (with a small delay)
    async def chunk_generator():
        for chunk in readme_chunks:
            await asyncio.sleep(0.02)
            yield chunk + " "

    md = ui.MarkdownStream("shiny_readme")

    @reactive.effect
    async def _():
        await md.stream(chunk_generator())


app = App(app_ui, server)

Methods

Name Description
clear Empty the UI element of the MarkdownStream.
stream Send a stream of content to the UI.

clear

ui.MarkdownStream.clear()

Empty the UI element of the MarkdownStream.

stream

ui.MarkdownStream.stream(content, clear=True)

Send a stream of content to the UI.

Stream content into the relevant UI element.

Parameters

content : Union[Iterable[str], AsyncIterable[str]]

The content to stream. This can be a Iterable or an AsyncIterable of strings. Note that this includes synchronous and asynchronous generators, which is a useful way to stream content in as it arrives (e.g. from a LLM).

clear : bool = True

Whether to clear the existing content before streaming the new content.

Note

If you already have the content available as a string, you can do .stream([content]) to set the content.