Tutorial: Your First Generative Program
In this tutorial you build a document analysis pipeline that extracts a summary, classifies sentiment, and surfaces key issues from customer feedback. You start with the simplest possible Mellea program and add reliability and structure at each step.
By the end you will have covered:
instruct()with user variables and requirements- Rejection sampling and
SamplingResult - Composing generative functions into a pipeline
@generativein depth: This tutorial uses@generativein the final pipeline step. For a dedicated walkthrough of typed returns,Literal, and Pydantic models, see Tutorial 03: Using Generative Stubs.
Prerequisites: Quick Start complete,
Mellea installed (uv add mellea), Ollama running locally with granite4.1:3b downloaded.
Step 1: One instruction
Start with the smallest possible program: a single call to instruct().
# Requires: mellea
# Returns: str
import mellea
m = mellea.start_session()
summary = m.instruct(
"Summarise this customer feedback in one sentence: "
"The onboarding was confusing and took far too long. "
"Support was helpful once I got through."
)
print(str(summary))
The initial experience with the product's onboarding process was
challenging but support staff provided valuable assistance later.
Note: LLM output is non-deterministic. Your result will vary in wording.
instruct() returns a ModelOutputThunk. Calling str() on it (or accessing
.value) gives you the string. This is already a generative program: it calls an
LLM and returns structured text.
The problem is reliability. The model might return two sentences, or three, or include a preamble. Move to the next step to enforce the format.
Step 2: Adding user variables
Hardcoding the text in the instruction string makes the function impossible to reuse.
Use user_variables and {{double_braces}} template syntax:
# Requires: mellea
# Returns: str
import mellea
def summarize_feedback(m: mellea.MelleaSession, text: str) -> str:
result = m.instruct(
"Summarise this customer feedback in one sentence: {{text}}",
user_variables={"text": text},
)
return str(result)
m = mellea.start_session()
feedback = (
"The onboarding was confusing and took far too long. "
"Support was helpful once I got through."
)
print(summarize_feedback(m, feedback))
The onboarding process was complicated and time-consuming, but the
support team proved to be highly beneficial upon successful connection.
Note: LLM output is non-deterministic. Your result will vary in wording, but should be a single sentence.
The description is now a Jinja2 template. Variables are rendered at generation time, not embedded in the source code.