Tutorial: Using Generative Stubs
This tutorial shows how to build composable LLM-backed functions using the
@generative decorator — functions with typed return values, docstring-driven
prompts, and consistent behaviour that you can reuse across a codebase.
By the end you will have covered:
- Defining
@generativefunctions with typed returns - Composing multiple generative functions into a pipeline
- Controlling behaviour via
ChatContextand context injection - Precondition and postcondition validation patterns
Prerequisites: Tutorial 01 complete,
pip install mellea, Ollama running locally with granite4.2:3b downloaded.
Step 1: Your first @generative function
A @generative function uses its name, type annotation, and docstring as the
prompt. Call it by passing a MelleaSession as the first argument:
# Requires: mellea
# Returns: str
import mellea
from mellea import generative
@generative
def classify_sentiment(text: str) -> str:
"""Classify the sentiment of the text as 'positive', 'negative', or 'neutral'."""
m = mellea.start_session()
result = classify_sentiment(m, text="The product arrived damaged and support ignored me.")
print(str(result))
negative
Note: Output may vary — LLM responses depend on model and temperature.
The return type annotation shapes the output. With -> str, the model returns
free text. For constrained output, use Literal:
from typing import Literal
from mellea import generative
@generative
def classify_sentiment(text: str) -> Literal["positive", "negative", "neutral"]: ...
Now the output is guaranteed to be one of those three strings.