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 responsechat: yield user prompts until a stop command is enteredsys_prompt: append a line to the active system prompt
Input widgets
text_input: free-form textbuttons: pick one of a set of optionsdate_picker: pick a dateslider: pick a number in a rangetree_selector: select leaves from a nested tree
Output blocks
markdown: render markdown contenttable: render tabular dataspinner: show a spinner while work runsresultimage: render image-file bytes
Layout
section— group related output blocks
Lifecycle
session_title: set the title associated with the current sessionexit: end the app runquit: end the app run as a user-initiated quit
Symbols
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,
) → NoneRender a bar chart.
Parameters
Chart data; typically a pandas DataFrame.
Column name to use for the x-axis.
Column name (or names) to plot on the y-axis.
Column name (or names) used to colour the bars.
Orient bars horizontally rather than vertically.
Stack multiple series rather than grouping side-by-side.
Examples
Compare quarterly revenue by region:
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,
) → strPresent the user with a set of buttons and return their selection.
Parameters
Labels for the buttons to display.
Optional prompt shown above the buttons.
Returns
The label of the button the user clicked.
Raises
If the submitted value is not one of the offered button labels.
Examples
Ask the user to choose from several options:
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
Prefix that, when matched, ends the chat loop. Default = "/quit"
Examples
Build a conversational app that stops when the user enters
/goodbye:
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',
) → boolPresent the user with a binary choice and return True/False.
Parameters
optional prompt shown above the buttons.
the button option representing true.
the button option representing false.
Returns
boolean value representing whether the user chose the true or false option.
Examples
Ask for confirmation using labels suited to the decision:
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,
) → datePresent the user with a date picker.
Parameters
Prompt shown alongside the picker.
Optional initial date, as a date or ISO-format
string.
Returns
The date the user chose.
Examples
Ask the user to choose a departure date, starting with a suggested value:
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,
) → NoReturnEnd 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
Process-style exit code; 0 for success, non-zero
for failure.
Human-readable summary of why the run ended.
Value to return to the caller, or None.
Optional structured cause metadata for failure exits.
See ErrorCause.
Raises
Always. The outermost app catches it and ends the run.
Examples
End an app successfully when there is nothing more to do:
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,
) → strGenerate a response from the active LLM with optional instruction and visibility control.
Parameters
Whether to include the response back in the LLM context.
Optional system instruction to guide generation (e.g., for structured outputs).
Additional keyword arguments passed directly to the underlying LLM
(e.g., temperature, max_tokens, etc.).
Returns
The generated text response from the LLM.
Examples
Generate from previously inserted context while controlling whether the result remains in the conversation:
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,
) → NoneRender 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
Raw contents of a PNG, JPEG, WebP, GIF, or SVG image file.
MIME type identifying the supplied image format.
Optional accessible description of the image.
Examples
Render an image stored on disk:
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,
) → NoneInsert 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
The user message to insert into the LLM context.
Examples
Add facts to the shared conversation before generating a response:
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,
) → NoneRender a line chart.
Parameters
Chart data; typically a pandas DataFrame.
Column name to use for the x-axis.
Column name (or names) to plot on the y-axis.
Column name (or names) used to colour the lines.
Examples
Plot a temperature forecast over time:
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,
) → NoneRender 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
the markdown content to display
Examples
Emit a complete block immediately, then build another block over several streamed updates:
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() → NoReturnEnd 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
Always. The outermost app catches it and ends the run.
Examples
Stop an app when the user chooses not to continue:
import yera as yr
if not yr.confirm("Would you like to play another round?"):
yr.quit()
response
response(
prompt: str,
**kwargs,
) → strSend 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
The user-message prompt to send.
Additional options forwarded to the underlying LLM (e.g. provider-specific generation parameters).
Returns
The LLM's text response.
Examples
Generate and display a concise response from the active LLM:
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,
) → SectionGroup 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
Heading shown in the section header.
Optional summary shown for the completed section.
Whether the section collapses when it completes.
Name of the glyph shown in the section header.
Optional named colour applied to the section heading.
Returns
A Section context manager.
Examples
Group related output and mark the section as successful:
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,
) → NoneSet 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 to associate with the current session.
Examples
Give the current session a descriptive title:
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,
) → floatPresent the user with a slider over a numeric range.
Parameters
Lower bound of the slider.
Upper bound of the slider.
Prompt shown alongside the slider.
Optional initial position. Defaults to
min_value if not provided.
Raises
If the submitted value is outside the slider range.
Returns
The value the user selected.
Examples
Ask the user to choose a number within a range:
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',
) → SpinnerStreamShow 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
Initial message shown alongside the spinner.
Initial registered glyph name.
Initial named colour.
Message shown after successful completion.
Registered glyph shown after successful completion.
Named colour shown after successful completion.
Returns
A SpinnerStream context manager.
Examples
Show progress while a longer operation runs:
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,
) → NoneAppend a line to the active LLM context's system prompt.
Parameters
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:
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,
) → TableStreamRender a table.
Parameters
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.
True for full borders, False for none, or
"horizontal" for horizontal lines only.
Returns
A TableStream handle whose add_rows method appends rows to the same table.
Examples
Render a table and append more rows later:
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,
) → strPrompt the user for free-form text input.
Parameters
Optional label shown alongside the input field.
Returns
The text the user submitted.
Examples
Ask the user to enter a value:
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] | NonePresent a nested tree and return the selected leaf values.
Parameters
Nested option mapping or an object implementing
__yera_tree__().
Optional prompt shown above the tree.
Minimum number of leaves that must be selected.
Optional maximum number of leaves that may be selected.
Optional label for an action that returns None
without validating the selection.
Raises
If the source cannot provide a valid tree mapping.
If the supplied tree is malformed.
If the submitted selection violates its cardinality, contains duplicates, or includes a value outside the requested tree.
Returns
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__():
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.")