> ## Documentation Index
> Fetch the complete documentation index at: https://ibm-llm-runtime-aaf3a78b.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# mellea.stdlib.requirements.python_tools

> Generic Python tool requirements for code generation validation.

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 />

Generic Python tool requirements for code generation validation.

This module provides a set of composable requirements for validating Python code
generated by language models. Requirements can be used individually or bundled
via the python\_code\_generation\_requirements() factory function.

The requirement pipeline validates code in this order:

1. PythonCodeExtraction — code blocks are present and extractable
2. PythonSyntaxValid — code parses without syntax errors
3. PythonExecutionReq — code runs without exceptions and output stays within bounds
4. ImportRestrictions — only whitelisted modules are imported (optional)

OutputSizeLimit is available as a standalone requirement for special cases where
output size validation needs to be separate from execution (e.g., validating code
with non-deterministic output or checking previously-executed code).

## 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> `python_code_generation_requirements` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.7.0.dev0/mellea/stdlib/requirements/python_tools.py#L350" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

```python theme={null}
python_code_generation_requirements(allowed_imports: list[str] | None = None, output_limit_chars: int = 10000, timeout_seconds: int = 5, use_sandbox: bool = False) -> list[Requirement]
```

Bundle generic Python tool requirements with configurable parameters.

Factory function that creates a complete set of requirements for validating
Python code generation, from extraction through execution and output checks.

⚠️ **Performance Improvement**: As of this version, output size checking is
integrated into PythonExecutionReq via the max\_output\_chars parameter,
eliminating the double-execution cost that occurred when OutputSizeLimit was
a separate requirement in the bundle. This reduces execution cost for Docker-
isolated code and reduces the attack surface for untrusted inputs.

**Args:**

* `allowed_imports`: Whitelist of importable top-level modules. If None, all
  imports are allowed. Default None.
* `output_limit_chars`: Maximum allowed characters of captured stdout.
  Default 10,000.
* `timeout_seconds`: Maximum execution time in seconds. Default 5.
* `use_sandbox`: Use llm-sandbox for Docker-isolated execution. Default False.

**Returns:**

* list\[Requirement]: Requirement instances in validation order (always 4):

1. PythonCodeExtraction
2. PythonSyntaxValid
3. PythonExecutionReq (configured with timeout, sandbox, and output limit)
4. ImportRestrictions or NoImportRestrictions

* The fourth requirement is ImportRestrictions if allowed\_imports is provided
* (enforcing the whitelist), or NoImportRestrictions if allowed\_imports is None
* (documenting that no import checks are configured).

**Raises:**

* `ValueError`: If timeout\_seconds is not positive.
* `ValueError`: If output\_limit\_chars is not positive.

**Examples:**

```python theme={null}
>>> # Unrestricted execution with defaults
>>> reqs = python_code_generation_requirements()
>>> len(reqs)
4
>>> isinstance(reqs[3], NoImportRestrictions)
True
>>> # Restricted to safe modules only
>>> reqs = python_code_generation_requirements(
...     allowed_imports=["os", "sys", "json"],
...     output_limit_chars=5_000,
... )
>>> len(reqs)  # always 4, fourth is ImportRestrictions
4
>>> isinstance(reqs[3], ImportRestrictions)
True
>>> # Sandbox mode for untrusted code
>>> reqs = python_code_generation_requirements(
...     use_sandbox=True,
...     timeout_seconds=10,
... )
```

<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> `PythonCodeExtraction` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.7.0.dev0/mellea/stdlib/requirements/python_tools.py#L32" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Code blocks are present and extractable from model output.

This requirement checks whether the model's response contains Python code
blocks that can be extracted for further validation or execution.

<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> `PythonSyntaxValid` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.7.0.dev0/mellea/stdlib/requirements/python_tools.py#L48" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Python code is syntactically valid (parses without AST errors).

Uses Python's ast.parse() to validate syntax without executing code.
Useful for catching malformed code early in the validation pipeline.

<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> `OutputSizeLimit` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.7.0.dev0/mellea/stdlib/requirements/python_tools.py#L95" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Captured output does not exceed size limit (in characters).

Executes code and verifies that the captured stdout does not exceed
the configured character limit. Useful for preventing excessive logging
or infinite output loops.

⚠️ **Prefer PythonExecutionReq(max\_output\_chars=...)**: Starting in this version,
output size checking is integrated into PythonExecutionReq, eliminating the
double-execution cost. Use this class only for special cases where you need
output size validation as a separate execution pass:

1. Validating code with non-deterministic output (where separate execution
   passes are intentional).
2. Re-checking output size of code executed elsewhere, without repeating
   the earlier execution.
3. Niche cases where static tier validation is desired (though static tier
   does not execute code, so this is rarely useful).

For typical use in python\_code\_generation\_requirements(), the bundle now uses
PythonExecutionReq(max\_output\_chars=...) internally, so this class is no
longer added to the bundle.

⚠️ **Static Tier Behavior**: When execution\_tier is "static" (the default),
no code execution occurs and output size is not validated. The requirement
returns result=True, but this does not indicate the requirement was satisfied —
only that validation was skipped. This is intentional: static tier is the
no-execution baseline. If you need actual output size validation, set
execution\_tier to "local", "local\_unsafe", or "docker".

**Args:**

* `limit_chars`: Maximum allowed output size in characters. Defaults to 10,000.
* `execution_tier`: Execution environment tier. Defaults to `"static"`
  (no execution; output limit not enforced).
* `policy`: Optional CapabilityPolicy to override tier defaults.
* `allowed_imports`: Whitelist of importable top-level modules. None allows all.

<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> `ImportRestrictions` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.7.0.dev0/mellea/stdlib/requirements/python_tools.py#L223" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Only whitelisted modules are imported in the code.

Uses AST analysis to find all imports (Import and ImportFrom nodes)
and validates them against an optional allowlist. If an empty list is
provided, all imports are blocked. If None is provided, all imports are accepted.

⚠️ **Not a Security Boundary**: This is a static AST-based guidance check,
not a security control. It only detects static import statements (`import x`
and `from x import y`) and does NOT detect dynamic imports such as:

* `__import__("subprocess")`
* `importlib.import_module("socket")`
* `exec("import urllib")`
* `eval("import os")`

For real isolation from untrusted code, combine this requirement with
`execution_tier="docker"` and a restrictive `CapabilityPolicy`.
The execution environment sandbox provides the actual security boundary,
not the import allowlist.

**Args:**

* `allowed_imports`: List of module names that are allowed to be imported.
  If None, all imports are accepted. If an empty list, all imports are blocked.

<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> `NoImportRestrictions` <sup><a href="https://github.com/generative-computing/mellea/blob/v0.7.0.dev0/mellea/stdlib/requirements/python_tools.py#L329" target="_blank"><Icon icon="github" style="width: 14px; height: 14px;" /></a></sup>

Explicit no-op requirement indicating no import checks are configured.

This requirement always passes and documents that import restrictions are
not being enforced. Used by python\_code\_generation\_requirements() when allowed\_imports
is None, providing semantic clarity in the requirement bundle that import
validation was intentionally skipped (rather than silently omitting the
requirement from the list).

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