> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mellea.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# mellea.core.requirement

> `Requirement` interface for constrained and validated generation.

export const SidebarFix = () => <script dangerouslySetInnerHTML={{
  __html: `
        (function () {
          const INTERVAL_MS = 500;

          const upgradeSidebar = () => {
            const links = document.querySelectorAll('a[href^="#"]');

            links.forEach((link) => {
              if (link.dataset.badged === "true") return;

              const rawText = (link.textContent || "").trim();

              // ========== FUNC ==========
              if (rawText.startsWith("FUNC ")) {
                const label = rawText.replace(/^FUNC\\s+/, "").trim();

                while (link.firstChild) link.removeChild(link.firstChild);

                // 👉 Make the whole link a single flex row & prevent wrapping
                link.style.display = "flex";
                link.style.alignItems = "center";
                link.style.whiteSpace = "nowrap";
                link.style.columnGap = "0.5rem";

                const badge = document.createElement("span");
                badge.style.marginRight = "0.5rem";
                badge.style.display = "inline-flex";
                badge.style.alignItems = "center";
                badge.style.borderRadius = "9999px";
                badge.style.padding = "0rem 0.6rem";
                badge.style.fontSize = "0.5rem";
                badge.style.fontWeight = "700";
                badge.style.letterSpacing = "0.05em";
                badge.style.backgroundColor = "rgba(48, 100, 227, 0.20)";
                badge.style.color = "#1D4ED8";

                badge.textContent = "FUNC";

                link.appendChild(badge);
                link.appendChild(document.createTextNode(label));
                link.dataset.badged = "true";
                return;
              }

              // ========== CLASS ==========
              if (rawText.startsWith("CLASS ")) {
                const label = rawText.replace(/^CLASS\\s+/, "").trim();

                while (link.firstChild) link.removeChild(link.firstChild);

                // 👉 Same flex / nowrap treatment for class links
                link.style.display = "flex";
                link.style.alignItems = "center";
                link.style.whiteSpace = "nowrap";
                link.style.columnGap = "0.5rem";

                const badge = document.createElement("span");
                badge.style.marginRight = "0.5rem";
                badge.style.display = "inline-flex";
                badge.style.alignItems = "center";
                badge.style.borderRadius = "9999px";
                badge.style.padding = "0rem 0.6rem";
                badge.style.fontSize = "0.5rem";
                badge.style.fontWeight = "700";
                badge.style.letterSpacing = "0.05em";
                badge.style.backgroundColor = "rgba(74, 222, 128, 0.20)";
                badge.style.color = "#15803D";

                badge.textContent = "CLASS";

                link.appendChild(badge);
                link.appendChild(document.createTextNode(label));
                link.dataset.badged = "true";
                return;
              }
            });
          };

          upgradeSidebar();
          setInterval(upgradeSidebar, INTERVAL_MS);
        })();
      `
}} />;

<SidebarFix />

`Requirement` interface for constrained and validated generation.

A `Requirement` pairs a human-readable description with a validation function that
inspects a [`Context`](base#class-context) (and optionally a backend) to determine whether a model output
meets a constraint. `ValidationResult` carries the pass/fail verdict along with an
optional reason, score, and the [`ModelOutputThunk`](base#class-modeloutputthunk) produced during validation.
`PartialValidationResult` provides a tri-state variant (`"pass"`, `"fail"`,
`"unknown"`) for per-chunk streaming validation.
Helper factories such as `default_output_to_bool` make it easy to build requirements
without boilerplate.

## Functions

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `default_output_to_bool` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L174" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
default_output_to_bool(x: CBlock | str) -> bool
```

Convert a model output string to a boolean by checking for a "yes" answer.

Checks if the output is exactly equal to "yes" or "y" (case-insensitive). If not,
also checks if any of the words in the output are "yes" (case-insensitive).

**Args:**

* `x`: The model output to evaluate, as a [`CBlock`](base#class-cblock) or plain string.

**Returns:**

* `True` if the output indicates a "yes" answer, `False` otherwise.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

## Classes

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#4ADE8033]/20 text-[#15803D]">CLASS</span> `ValidationResult` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L22" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

ValidationResults store the output of a Requirement's validation. They can be used to return additional info from validation functions, which is useful for sampling/repairing.

**Args:**

* `result`: Boolean indicating whether the requirement passed.
* `reason`: Optional human-readable explanation for the verdict.
* `score`: Optional numeric score returned by the validator.
* `thunk`: The [`ModelOutputThunk`](base#class-modeloutputthunk) produced during LLM-as-a-Judge validation, if applicable.
* `context`: The context associated with the validation backend call, if applicable.

<div className="h-8" />

**Methods:**

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `reason` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L51" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
reason(self) -> str | None
```

Reason for the validation result.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `score` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L56" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
score(self) -> float | None
```

An optional score for the validation result.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `thunk` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L61" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
thunk(self) -> ModelOutputThunk | None
```

The ModelOutputThunk associated with the validation func if an llm was used to generate the final result.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `context` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L66" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
context(self) -> Context | None
```

The context associated with validation if a backend was used to generate the final result.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `as_bool` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L70" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
as_bool(self) -> bool
```

Return a boolean value based on the validation result.

**Returns:**

* `True` if the requirement passed, `False` otherwise.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#4ADE8033]/20 text-[#15803D]">CLASS</span> `PartialValidationResult` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L87" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Tri-state result from per-chunk streaming validation.

Unlike :class:`ValidationResult`, which stores its verdict as a private
`_result: bool`, this class exposes `success` as a public property.
The asymmetry is intentional: the tri-state value cannot be recovered from
a `bool`, so a public property is the only way to distinguish `"fail"`
from `"unknown"` after construction.

**Args:**

* `success`: Validation state — `"pass"` (constraint satisfied so far),
  `"fail"` (constraint violated, stop streaming), or
  `"unknown"` (insufficient data yet, continue streaming).
* `reason`: Optional human-readable explanation.
* `score`: Optional numeric confidence score.
* `thunk`: Optional ModelOutputThunk from the validation call.
* `context`: Optional context associated with the validation call.

<div className="h-8" />

**Methods:**

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `success` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L128" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
success(self) -> Literal['pass', 'fail', 'unknown']
```

The tri-state validation result.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `reason` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L133" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
reason(self) -> str | None
```

Reason for the validation result.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `score` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L138" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
score(self) -> float | None
```

An optional score for the validation result.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `thunk` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L143" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
thunk(self) -> ModelOutputThunk | None
```

The ModelOutputThunk associated with the validation call, if any.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `context` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L148" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
context(self) -> Context | None
```

The context associated with the validation call, if any.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `as_bool` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L152" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
as_bool(self) -> bool
```

Return True for `"pass"`, False for `"fail"` or `"unknown"`.

`"unknown"` maps to `False` intentionally. In streaming contexts,
check `pvr.success == "unknown"` before treating `False` as a definitive
failure — `"unknown"` means insufficient data so far, not a constraint
violation.

**Returns:**

* `True` if the partial result is `"pass"`, `False` otherwise.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#4ADE8033]/20 text-[#15803D]">CLASS</span> `Requirement` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L198" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Requirements are a special type of Component used as input to the Validate step in Instruct/Validate/Repair patterns.

**Args:**

* `description`: A natural-language description of the requirement. Sometimes included in
  `Instruction` prompts; use `check_only=True` to suppress this.
* `validation_fn`: If provided, this function is executed
  instead of LLM-as-a-Judge. The `bool()` of its return value defines pass/fail.
* `output_to_bool`: Translates LLM-as-a-Judge output to a boolean.
  Defaults to a "yes"-detection heuristic.
* `check_only`: When `True`, the requirement description is excluded from `Instruction` prompts.

**Attributes:**

* `description`: A natural-language description of the requirement.
* `output_to_bool`: Function used to convert LLM-as-a-Judge
  output into a boolean pass/fail result.
* `validation_fn`: Optional custom validation
  function that bypasses the LLM-as-a-Judge strategy entirely.
* `check_only`: When `True`, the requirement description is excluded from `Instruction`
  prompts to avoid influencing model output.

<div className="h-8" />

**Methods:**

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `validate` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L237" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
validate(self, backend: Backend, ctx: Context) -> ValidationResult
```

Chooses the appropriate validation strategy and applies it to the given context.

Uses `validation_fn` if one was provided, otherwise falls back to LLM-as-a-Judge
by generating a judgement response with the backend.

**Args:**

* `backend`: The inference backend used when the LLM-as-a-Judge strategy is selected.
* `ctx`: The context to validate, which must contain a [`ModelOutputThunk`](base#class-modeloutputthunk) as its last output.
* `format`: Optional structured output format for the judgement call.
* `model_options`: Optional model options to pass to the backend during the judgement call.

**Returns:**

* The result of the validation, including a boolean pass/fail and optional metadata.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `stream_validate` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L286" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
stream_validate(self, chunk: str) -> PartialValidationResult
```

Hook for per-chunk streaming validation.

The default implementation returns `PartialValidationResult("unknown")`
— meaning insufficient data to decide yet. Subclasses override this method
to inspect the current chunk and return `"pass"` or `"fail"` early.

Implementations may accumulate state on `self` across calls within a
single attempt. The orchestrator clones the requirement (`copy(req)`)
before each attempt, so state does not bleed across retries.

Shallow-copy caveat: mutable container fields (e.g. `self._buffer = []`)
are shared by reference under `copy()`. Reassign rather than mutate in
place (`self._buffer = self._buffer + [chunk]`, not
`self._buffer.append(chunk)`), or override `__copy__` for proper
isolation.  If an override raises, the enclosing
:func:`~mellea.stdlib.streaming.stream_with_chunking` call aborts before
any backend generation starts and the exception propagates unchanged.
Overrides with externally visible side effects (file writes, network
calls) should perform them only after any logic that could raise, since
the framework cannot roll them back.

Implementations must not call `mot.astream()` or otherwise read the
underlying stream; the orchestrator is the single consumer of the MOT
stream (see `ModelOutputThunk.astream`). Requirements that need access
to the text seen so far should accumulate it themselves from the
`chunk` values they receive.

**Args:**

* `chunk`: A single complete semantic chunk produced by the chunking
  strategy (e.g. one sentence for [`SentenceChunker`](../stdlib/chunking#class-sentencechunker)). This is
  the delta since the previous `stream_validate` call for this
  attempt, not the accumulated output. Requirements that need
  earlier context should retain it on `self` across calls.
* `backend`: The inference backend, available for backend-assisted checks.
* `ctx`: The current generation context. During streaming the MOT is
  not yet computed, so `ctx` does not contain the generated
  output; use `chunk` (and any state accumulated on `self`)
  instead.

**Returns:**

* `"unknown"` by default. Subclasses may return
* `"pass"` (constraint satisfied so far) or `"fail"` (constraint violated,
* streaming should be aborted). `"pass"` does not short-circuit the final
* `validate()` call; the orchestrator decides whether to skip it.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `parts` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L336" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
parts(self) -> list[Component | CBlock]
```

Returns all of the constituent parts of a Requirement.

**Returns:**

* List of constituent components. Empty by default; subclasses override
* to expose their internal structure.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />

#### <span className="ml-2 inline-flex items-center rounded-full px-2 py-1 text-[0.7rem] font-bold tracking-wide bg-[#3064E3]/20 text-[#1D4ED8]">FUNC</span> `format_for_llm` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.6.0/mellea/core/requirement.py#L345" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
format_for_llm(self) -> TemplateRepresentation | str
```

Returns a [`TemplateRepresentation`](base#class-templaterepresentation) for LLM-as-a-Judge evaluation of this requirement.

Populates the template with the requirement's `description` and the stored model
`_output`. Must only be called from within a `validate` call for this same requirement,
after `_output` has been set.

**Returns:**

* TemplateRepresentation | str: A [`TemplateRepresentation`](base#class-templaterepresentation) containing the description
* and the model output to be judged.

<div className="w-full h-px bg-gray-200 dark:bg-gray-700 my-4" />
