Skip to main content
Prerequisites: Quick Start complete, pip install mellea, Ollama running locally.
Concept overview: Generative functions explains the design and trade-offs.
@generative is the idiomatic way to define type-safe LLM functions in Mellea. You write a function signature with type hints and a docstring — Mellea generates the implementation, calls the backend, and parses the output into the declared return type.

Basic @generative

The function body is empty (or ...). The decorator generates a prompt from the signature and docstring, calls the backend, and returns a value of the declared type. The first argument is always the MelleaSession. Literal types constrain the model to output one of the allowed values.

Pydantic structured output

Return complex structured objects using Pydantic models:
The model output is automatically parsed and validated against the Pydantic schema. If parsing fails, the IVR loop retries.

Pre- and post-conditions

Add runtime constraints with precondition_requirements (checked before generation) and requirements (checked after). Both accept the same requirement types as instruct():
If a precondition fails, PreconditionException is raised immediately — the model is never called:

Composing generative functions

Chain multiple @generative functions to build typed pipelines. The output of one call becomes the input to the next:
Each call is an independent LLM invocation. The typed interface enforces that each step receives and produces valid data, making pipelines easier to test and debug.

Chain-of-thought reasoning

Advanced: This section shows a performance-oriented pattern for math and reasoning tasks.
The Pydantic structured output pattern works well for explicit chain-of-thought (CoT) reasoning. Separating the reasoning step from the answer extraction step can significantly improve accuracy on tasks like GSM8K.
The structured Thought titles can be surfaced in a UI for observability into the model’s reasoning process.
See also: Generative Functions | Enforce Structured Output | Write Custom Verifiers