yera.dsl.functions

Prompting, input, output, layout, and lifecycle functions.

The building blocks an app function uses to interact with the LLM, present output, and collect input from the user.

Prompting

  • response: send a prompt and get a text response
  • chat: yield user prompts until a stop command is entered
  • sys_prompt: append a line to the active system prompt

Input widgets

Output blocks

Layout

  • section — group related output blocks

Lifecycle

  • session_title: set the title associated with the current session
  • exit: end the app run
  • quit: end the app run as a user-initiated quit

Symbols

def bar_chart — Render a bar chart.
def buttons — Present the user with a set of buttons and return their selection.
def chat — Yield user prompts until one starts with ``stop_str``.
def confirm — Present the user with a binary choice and return True/False.
def date_picker — Present the user with a date picker.
def exit — End the current app run immediately.
def gen — Generate a response from the active LLM with optional instruction and visibility control.
def image — Render an image from image-file bytes.
def insert — Insert a prompt into the active LLM context.
def line_chart — Render a line chart.
def markdown — Render a markdown block.
def quit — End the current app run immediately as a user-initiated quit.
def response — Send a prompt to the active LLM and return its text response.
def section — Group output blocks into a mutable, collapsible section.
def session_title — Set the title associated with the current session.
def slider — Present the user with a slider over a numeric range.
def spinner — Show a configurable spinner while a block of work runs.
def sys_prompt — Append a line to the active LLM context's system prompt.
def table — Render a table.
def text_input — Prompt the user for free-form text input.
def tree_selector — Present a nested tree and return the selected leaf values.

bar_chart

bar_chart(
    data: object,
    x: str | None = None,
    y: str | Sequence[str] | None = None,
    colour: str | Sequence[str] | None = None,
    horizontal: bool = False,
    stack: bool = True,
) → None

Render a bar chart.

Parameters

data
type: object

Chart data; typically a pandas DataFrame.

x
type: str | None = None

Column name to use for the x-axis.

y
type: str | Sequence[str] | None = None

Column name (or names) to plot on the y-axis.

colour
type: str | Sequence[str] | None = None

Column name (or names) used to colour the bars.

horizontal
type: bool = False

Orient bars horizontally rather than vertically.

stack
type: bool = True

Stack multiple series rather than grouping side-by-side.

Examples

Compare quarterly revenue by region:

python
import pandas as pd

import yera as yr

revenue = pd.DataFrame(
    {
        "quarter": ["Q1", "Q2", "Q1", "Q2"],
        "amount": [120, 145, 98, 167],
        "region": ["North", "North", "South", "South"],
    }
)

yr.bar_chart(
    revenue,
    x="quarter",
    y="amount",
    colour="region",
    stack=False,
)

buttons

buttons(
    options: list[str],
    label: str | None = None,
) → str

Present the user with a set of buttons and return their selection.

Parameters

options
type: list[str]

Labels for the buttons to display.

label
type: str | None = None

Optional prompt shown above the buttons.

Returns

type: str

The label of the button the user clicked.

Raises

InputValueError

If the submitted value is not one of the offered button labels.

Examples

Ask the user to choose from several options:

python
import yera as yr

drink = yr.buttons(
    ["Tea", "Coffee", "Water"],
    label="What would you like to drink?",
)

chat

chat(
    stop_str: str = '/quit',
) → Generator[str]

Yield user prompts until one starts with stop_str.

Repeatedly prompts the user for text input, yielding each prompt. When the user submits a prompt starting with stop_str, the run quits and iteration stops.

Parameters

stop_str
type: str = '/quit'

Prefix that, when matched, ends the chat loop. Default = "/quit"

Examples

Build a conversational app that stops when the user enters /goodbye:

python
import yera as yr

@yr.app
def history_guide() -> None:
    yr.sys_prompt("You are a friendly history guide.")

    for question in yr.chat(stop_str="/goodbye"):
        yr.response(question)

confirm

confirm(
    label: str | None = None,
    true_option: str = 'Yes',
    false_option: str = 'No',
) → bool

Present the user with a binary choice and return True/False.

Parameters

label
type: str | None = None

optional prompt shown above the buttons.

true_option
type: str = 'Yes'

the button option representing true.

false_option
type: str = 'No'

the button option representing false.

Returns

type: bool

boolean value representing whether the user chose the true or false option.

Examples

Ask for confirmation using labels suited to the decision:

python
import yera as yr

include_museums = yr.confirm(
    "Should the itinerary include museums?",
    true_option="Include them",
    false_option="Skip them",
)

if include_museums:
    yr.markdown("Museums will be included.")

date_picker

date_picker(
    label: str,
    default_date: date | str | None = None,
) → date

Present the user with a date picker.

Parameters

label
type: str

Prompt shown alongside the picker.

default_date
type: date | str | None = None

Optional initial date, as a date or ISO-format string.

Returns

type: date

The date the user chose.

Examples

Ask the user to choose a departure date, starting with a suggested value:

python
import yera as yr

departure = yr.date_picker(
    "When would you like to leave?",
    default_date="2027-06-15",
)
yr.markdown(f"Your departure date is **{departure}**.")

exit

exit(
    exit_code: int,
    reason: str,
    return_value: object,
    error_cause: ErrorCause | None = None,
) → NoReturn

End the current app run immediately.

Nothing after this call runs, including the rest of any app that called the current one. On success, return_value is checked against the outermost app's declared return type, as if that app had returned it.

Parameters

exit_code
type: int

Process-style exit code; 0 for success, non-zero for failure.

reason
type: str

Human-readable summary of why the run ended.

return_value
type: object

Value to return to the caller, or None.

error_cause
type: ErrorCause | None = None

Optional structured cause metadata for failure exits. See ErrorCause.

Raises

AppExit

Always. The outermost app catches it and ends the run.

Examples

End an app successfully when there is nothing more to do:

python
import yera as yr

@yr.app
def choose_book() -> str | None:
    title = yr.text_input("Which book would you like?")

    if not title:
        yr.exit(
            0,
            "No book was selected.",
            None,
        )

    return title

gen

gen(
    on_wire: bool = True,
    instruction: str | None = None,
    **kwargs,
) → str

Generate a response from the active LLM with optional instruction and visibility control.

Parameters

on_wire
type: bool = True

Whether to include the response back in the LLM context.

instruction
type: str | None = None

Optional system instruction to guide generation (e.g., for structured outputs).

**kwargs
type: _GenerationOption

Additional keyword arguments passed directly to the underlying LLM (e.g., temperature, max_tokens, etc.).

Returns

type: str

The generated text response from the LLM.

Examples

Generate from previously inserted context while controlling whether the result remains in the conversation:

python
import yera as yr

yr.insert("The garden is small, shaded, and has clay soil.")

suggestions = yr.gen(
    instruction="Suggest three suitable plants.",
    on_wire=True,
)

image

image(
    content: bytes,
    media_type: ImageMediaType = 'image/png',
    alt: str | None = None,
) → None

Render an image from image-file bytes.

The image is fitted responsively to the available display width while preserving its intrinsic aspect ratio. PNG, JPEG, WebP, GIF, and SVG images are supported. Rendering depends on the active output environment.

Parameters

content
type: bytes

Raw contents of a PNG, JPEG, WebP, GIF, or SVG image file.

media_type
type: ImageMediaType = 'image/png'

MIME type identifying the supplied image format.

alt
type: str | None = None

Optional accessible description of the image.

Examples

Render an image stored on disk:

python
from pathlib import Path

import yera as yr

content = Path("family-photo.jpg").read_bytes()
yr.image(
    content,
    media_type="image/jpeg",
    alt="A family picnic beside a lake",
)

insert

insert(
    prompt: str,
) → None

Insert a prompt into the active LLM context.

Unlike response, this does not generate a response; it merely appends the given prompt to the conversation history.

Parameters

prompt
type: str

The user message to insert into the LLM context.

Examples

Add facts to the shared conversation before generating a response:

python
import yera as yr

yr.insert("The birthday party has twelve guests.")
yr.insert("Two guests are vegetarian.")

menu = yr.gen(
    instruction="Suggest a simple buffet menu.",
    on_wire=True,
)

line_chart

line_chart(
    data: object,
    x: str | None = None,
    y: str | Sequence[str] | None = None,
    colour: str | Sequence[str] | None = None,
) → None

Render a line chart.

Parameters

data
type: object

Chart data; typically a pandas DataFrame.

x
type: str | None = None

Column name to use for the x-axis.

y
type: str | Sequence[str] | None = None

Column name (or names) to plot on the y-axis.

colour
type: str | Sequence[str] | None = None

Column name (or names) used to colour the lines.

Examples

Plot a temperature forecast over time:

python
import pandas as pd

import yera as yr

forecast = pd.DataFrame(
    {
        "hour": ["09:00", "12:00", "15:00", "18:00"],
        "temperature": [14, 18, 20, 17],
    }
)

yr.line_chart(
    forecast,
    x="hour",
    y="temperature",
)

markdown

markdown(
    content: str,
) → None

Render a markdown block.

Can be called directly to emit a single block, or used as a stream handle to append further chunks over time.

Parameters

content
type: str

the markdown content to display

Examples

Emit a complete block immediately, then build another block over several streamed updates:

python
import yera as yr

yr.markdown(
    "## Recipe of the day\n\n"
    "Today's recipe is **lemon risotto**."
)

with yr.markdown.stream() as progress:
    progress.append("Preparing the ingredients")
    progress.new_line("Cooking the rice")
    progress.new_line("Adding lemon and parmesan")

quit

quit() → NoReturn

End the current app run immediately as a user-initiated quit.

Distinct from exit: signals that the user chose to stop rather than the app completing or failing.

Raises

AppQuit

Always. The outermost app catches it and ends the run.

Examples

Stop an app when the user chooses not to continue:

python
import yera as yr

if not yr.confirm("Would you like to play another round?"):
    yr.quit()

response

response(
    prompt: str,
    **kwargs,
) → str

Send a prompt to the active LLM and return its text response.

Tokens will simultaneously be pushed onto the event stream for display in your UI or printed to stdout.

Parameters

prompt
type: str

The user-message prompt to send.

**kwargs
type: _GenerationOption

Additional options forwarded to the underlying LLM (e.g. provider-specific generation parameters).

Returns

type: str

The LLM's text response.

Examples

Generate and display a concise response from the active LLM:

python
import yera as yr

answer = yr.response(
    "What is the capital of France?",
    temperature=0,
)

section

section(
    title: str,
    summary: str | None = None,
    auto_collapse: bool = True,
    glyph: str = 'thread',
    colour: NamedColour | None = None,
) → Section

Group output blocks into a mutable, collapsible section.

Sections may contain ordinary output blocks or nested sections. While the context is open, its title, glyph, and colour may be changed through the returned section object. The success() and error() methods apply standard completion appearances without closing the section. In the web UI, the section may collapse automatically when its context exits.

Parameters

title
type: str

Heading shown in the section header.

summary
type: str | None = None

Optional summary shown for the completed section.

auto_collapse
type: bool = True

Whether the section collapses when it completes.

glyph
type: str = 'thread'

Name of the glyph shown in the section header.

colour
type: NamedColour | None = None

Optional named colour applied to the section heading.

Returns

type: Section

A Section context manager.

Examples

Group related output and mark the section as successful:

python
import yera as yr

with yr.section("Preparing your itinerary") as current:
    yr.markdown("Found three places to visit.")
    current.success("Itinerary ready")

session_title

session_title(
    title: str,
) → None

Set the title associated with the current session.

Session-aware hosts may persist and display the title. In runtimes without sessions, the emitted metadata update has no persistent effect.

Parameters

title
type: str

Title to associate with the current session.

Examples

Give the current session a descriptive title:

python
import yera as yr

topic = yr.text_input("What would you like to learn about?")
yr.session_title(f"Learning about {topic}")

slider

slider(
    min_value: float,
    max_value: float,
    label: str,
    default_value: float | None = None,
) → float

Present the user with a slider over a numeric range.

Parameters

min_value
type: float

Lower bound of the slider.

max_value
type: float

Upper bound of the slider.

label
type: str

Prompt shown alongside the slider.

default_value
type: float | None = None

Optional initial position. Defaults to min_value if not provided.

Raises

InputValueError

If the submitted value is outside the slider range.

Returns

type: float

The value the user selected.

Examples

Ask the user to choose a number within a range:

python
import yera as yr

servings = yr.slider(
    1,
    12,
    label="How many people are you cooking for?",
    default_value=4,
)

spinner

spinner(
    message: str = 'Working',
    glyph: str = 'run',
    colour: NamedColour = 'orange',
    end_message: str = 'Done',
    end_glyph: str = 'check',
    end_colour: NamedColour = 'green',
) → SpinnerStream

Show a configurable spinner while a block of work runs.

The spinner may change its message, glyph, and colour while active. On successful exit it resolves to the configured completion appearance; on exceptional exit it uses the fixed failure appearance.

Parameters

message
type: str = 'Working'

Initial message shown alongside the spinner.

glyph
type: str = 'run'

Initial registered glyph name.

colour
type: NamedColour = 'orange'

Initial named colour.

end_message
type: str = 'Done'

Message shown after successful completion.

end_glyph
type: str = 'check'

Registered glyph shown after successful completion.

end_colour
type: NamedColour = 'green'

Named colour shown after successful completion.

Returns

type: SpinnerStream

A SpinnerStream context manager.

Examples

Show progress while a longer operation runs:

python
import yera as yr

with yr.spinner(
    "Searching the recipe book",
    end_message="Recipes found",
) as progress:
    recipes = find_recipes()
    progress.update("Sorting by preparation time")
    recipes.sort(key=lambda recipe: recipe.preparation_time)

sys_prompt

sys_prompt(
    prompt: str,
) → None

Append a line to the active LLM context's system prompt.

Parameters

prompt
type: str

Text to add to the system prompt for subsequent chat and struct calls in the current LLM context.

Examples

Set the assistant's behaviour before generating a response:

python
import yera as yr

yr.sys_prompt("Answer each question in one short sentence.")
yr.response("Why is the sky blue?")

table

table(
    data: object = None,
    border: bool | Literal['horizontal'] = True,
) → TableStream

Render a table.

Parameters

data
type: object = None

Table data. Accepts pandas DataFrames, dicts of column lists, lists of dicts, lists of lists, or any iterable that can be converted to rows. Pass None for an empty table.

border
type: bool | Literal['horizontal'] = True

True for full borders, False for none, or "horizontal" for horizontal lines only.

Returns

type: TableStream

A TableStream handle whose add_rows method appends rows to the same table.

Examples

Render a table and append more rows later:

python
import yera as yr

planets = yr.table(
    [
        {"Planet": "Mercury", "Moons": 0},
        {"Planet": "Earth", "Moons": 1},
    ]
)
planets.add_rows(
    [{"Planet": "Mars", "Moons": 2}]
)

text_input

text_input(
    message: str | None = None,
) → str

Prompt the user for free-form text input.

Parameters

message
type: str | None = None

Optional label shown alongside the input field.

Returns

type: str

The text the user submitted.

Examples

Ask the user to enter a value:

python
import yera as yr

name = yr.text_input("What is your name?")
yr.markdown(f"Hello, **{name}**!")

tree_selector

tree_selector(
    tree: TreeSelectorSource,
    label: str | None = None,
    min_selections: int = 1,
    max_selections: int | None = None,
    cancel_label: str | None = None,
) → list[str] | None

Present a nested tree and return the selected leaf values.

Parameters

tree
type: TreeSelectorSource

Nested option mapping or an object implementing __yera_tree__().

label
type: str | None = None

Optional prompt shown above the tree.

min_selections
type: int = 1

Minimum number of leaves that must be selected.

max_selections
type: int | None = None

Optional maximum number of leaves that may be selected.

cancel_label
type: str | None = None

Optional label for an action that returns None without validating the selection.

Raises

TypeError

If the source cannot provide a valid tree mapping.

ValueError

If the supplied tree is malformed.

InputValueError

If the submitted selection violates its cardinality, contains duplicates, or includes a value outside the requested tree.

Returns

type: list[str] | None

The canonical values of the selected leaves in submitted order, or None when cancellation is enabled and selected.

Examples

Select values supplied by an object implementing __yera_tree__():

python
import yera as yr

class AnimalChoices:
    def __yera_tree__(self) -> dict[str, object]:
        return {
            "Mammals": {
                "Red panda": "red-panda",
                "Sea otter": "sea-otter",
            },
            "Birds": {
                "Puffin": "puffin",
                "Kingfisher": "kingfisher",
            },
        }

animals = yr.tree_selector(
    AnimalChoices(),
    label="Choose one or two favourite animals",
    min_selections=1,
    max_selections=2,
    cancel_label="Cancel",
)

if animals is None:
    yr.markdown("No animals were selected.")