@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
pip install mellea, Ollama running locally with granite4:micro 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:
-> str, the model returns
free text. For constrained output, use Literal:
Step 2: Typed and structured returns
Generative functions support any JSON-serialisable return type —str, int,
bool, list, dict, and Pydantic models:
FeedbackAnalysis instance. If the model output
doesn’t conform, Mellea retries.
Step 3: Compose generative functions
Because each@generative function is just a Python function, you compose them
the same way as any other code:
Full example: docs/examples/generative_slots/generate_with_context.py
Step 4: Steer all functions via context
A key advantage of@generative functions over direct instruct() calls: you can
change the behaviour of every function in a session by injecting context once.
m.reset() clears injected context while keeping the session and backend alive.
Step 5: Pre- and postcondition validation
For production pipelines, validate inputs before the LLM call and outputs afterwards using plain Python:@generative call as a lightweight verifier.
Full example: docs/examples/generative_slots/investment_advice.py
What you built
A pattern for replacing ad-hocinstruct() calls with reusable, typed,
context-steerable generative functions:
| Pattern | What it gives you |
|---|---|
@generative with Literal return | Constrained output, no parsing |
@generative with Pydantic return | Structured output, validated schema |
Multiple @generative functions | Composable pipeline in plain Python |
ChatContext + CBlock injection | Shared persona or policy across all functions |
| Pre/postcondition checks | Input validation and output compliance |
See also: Generative Functions | The Requirements System | Write Custom Verifiers