langflow-ai/langflow · error · ValueError

Could not extract class name from code

Error message

Could not extract class name from code

What it means

Thrown by validate_custom_component_code (wrapped into HTTP 400 as CustomComponentValidationError by the flow executor) when _safe_extract_class_name cannot find an extractable top-level class definition in the submitted custom component code. The validator needs the class name to find its inputs/outputs, so code without a recognizable class declaration fails immediately.

Source

Thrown at src/backend/base/langflow/agentic/helpers/validation.py:334

    Security: This function MUST NOT execute the code via exec() or eval().
    All validation is performed via AST parsing and compile() checks.
    The full runtime validation happens when the component is loaded into a flow.

    Checks performed:
    1. Syntax validity (ast.parse + compile)
    2. Class name extraction
    3. Overlapping input/output names
    4. Output methods have return statements with values
    5. No reserved output names/methods that would collide with the
       synthetic Tool sentinel (``component_as_tool`` / ``to_toolkit``).
    """
    class_name = _safe_extract_class_name(code)

    try:
        if class_name is None:
            msg = "Could not extract class name from code"
            raise ValueError(msg)

        tree = ast.parse(code)
        compile(ast.Module(body=tree.body, type_ignores=[]), "<string>", "exec")

        input_names, output_names = _extract_io_names(tree, class_name)
        overlap = input_names & output_names
        if overlap:
            msg = f"Inputs and outputs have overlapping names: {overlap}"
            raise ValueError(msg)

        if _RESERVED_OUTPUT_NAME in output_names:
            return ValidationResult(
                is_valid=False,
                code=code,
                error=(
                    f"Output name {_RESERVED_OUTPUT_NAME!r} is reserved by Langflow for the "
                    "synthetic Tool sentinel that the wiring layer auto-generates when a "
                    "component is flipped to Tool Mode. Declaring it on your own Output "

View on GitHub (pinned to 976ec789d2)

Solutions

  1. Ensure the code defines exactly one top-level class inheriting from Component (or similar), e.g. 'class MyTool(Component):', at column 0.
  2. Remove wrapping — the class must not live inside a function, if-block, or string literal.
  3. Re-indent the file with consistent 4-space indentation so the AST-level extractor can see the class.
  4. Validate locally with ast.parse / the same validation helper before sending the flow.

Example fix

# before
def build():
    class MyTool(Component):  # nested -> extractor returns None
        ...
# after
class MyTool(Component):  # top-level
    ...
Defensive patterns

Strategy: validation

Validate before calling

import ast

def has_top_level_class(code: str) -> bool:
    try:
        return any(isinstance(n, ast.ClassDef) and n.col_offset == 0 for n in ast.parse(code).body)
    except SyntaxError:
        return False

assert has_top_level_class(component_code), 'component must define a top-level class'

Type guard

const looksLikeComponent = (code: string): boolean =>
  /^class\s+\w+\s*\(/m.test(code) && !/^\s+class\s/m.test(code.split(/^class/m)[0] + 'class');

Try / catch

Catch the 400 from the execute endpoint and surface detail verbatim to the flow author; block deployment until the component defines a top-level class.

Prevention

When it happens

Trigger: POST to an agentic execute/assist endpoint whose flow JSON contains a CustomComponent whose code has no class statement, only commented-out or string-embedded class code, nested/indented class definitions, or syntax so broken the safe extractor bails (returns None rather than raising).

Common situations: LLM-generated component code that wraps the class in a function or triple-quoted string; user pasted only imports and helper functions; mixed tab/space indentation hiding the class from the extractor; a .py flow file edited by hand and truncated.

Related errors


AI-assisted analysis of langflow-ai/langflow@976ec789d2 (2026-08-14). Data as JSON: /api/errors/98a5ea773f441e8d. Report an issue: GitHub.