deepset-ai/haystack · error · ValueError

Invalid template for condition: {condition_value}

Error message

Invalid template for condition: {condition_value}

What it means

ConditionalRouter validates every route's 'condition' as a Jinja2 template string during _validate_routes (called from __init__). If the condition value is not a string (or is a string that fails template validation), a ValueError is raised. The specific message here is the fallback raised for non-string conditions or strings failing validation.

Source

Thrown at haystack/components/routers/conditional_router.py:519

            # Validate outputs are consistent
            outputs = route["output"] if isinstance(route["output"], list) else [route["output"]]
            output_types = route["output_type"] if isinstance(route["output_type"], list) else [route["output_type"]]
            output_names = route["output_name"] if isinstance(route["output_name"], list) else [route["output_name"]]

            # Check lengths match
            if not len(outputs) == len(output_types) == len(output_names):
                raise ValueError(f"Route output, output_type and output_name must have same length: {route}")

            # Condition is always a Jinja2 template — validate it
            if not self._validate_template(self._env, route["condition"]):
                condition_value = route["condition"]
                if not isinstance(condition_value, str):
                    raise ValueError(
                        f"Invalid template for condition: {condition_value!r} (type: {type(condition_value).__name__})."
                        f"Condition must be a string representing a valid Jinja2 template. "
                        f"For example, use {str(condition_value)!r} instead of {condition_value!r}."
                    )
                raise ValueError(f"Invalid template for condition: {condition_value}")

            # Only validate output as Jinja2 template when output_passthrough is False (default)
            output_passthrough = route.get("output_passthrough", False)
            if not output_passthrough:
                for output in outputs:
                    if not self._validate_template(self._env, output):
                        if not isinstance(output, str):
                            raise ValueError(
                                f"Invalid template for output: {output!r} (type: {type(output).__name__}). "
                                f"Output must be a string representing a valid Jinja2 template. "
                                f"For example, use {str(output)!r} instead of {output!r}."
                            )
                        raise ValueError(f"Invalid template for output: {output}")

    @staticmethod
    def _extract_variables(env: Environment, templates: list[str]) -> set[str]:
        """
        Extracts all variables from a list of Jinja template strings.

View on GitHub (pinned to e318778c9b)

Solutions

  1. Convert the condition to a Jinja2 template string, e.g. use '{{ flag }}' instead of the bare boolean True
  2. Check the exact value repr in the error message; the message suggests the str() version when applicable
  3. Ensure any config/dict sources parse conditions as strings (quote them in YAML)

Example fix

# before
ConditionalRouter(routes=[{"condition": True, "output": "{{ x }}", "output_name": "ok", "output_type": str}])
# after
ConditionalRouter(routes=[{"condition": "{{ flag }}", "output": "{{ x }}", "output_name": "ok", "output_type": str}])
Defensive patterns

Strategy: validation

Validate before calling

routes = [{"condition": "{{ flag }}", "output": "{{ x }}", "output_name": "ok", "output_type": str}]
assert all(isinstance(r["condition"], str) for r in routes), "route condition must be a Jinja2 template string"

Type guard

def is_valid_condition(cond) -> bool:
    return isinstance(cond, str)

Try / catch

try:
    router = ConditionalRouter(routes=routes)
except ValueError as e:
    if "Invalid template for condition" in str(e):
        routes = [{**r, "condition": str(r["condition"])} for r in routes]
        router = ConditionalRouter(routes=routes)
    else:
        raise

Prevention

When it happens

Trigger: Passing a non-string as a route condition, e.g. {'condition': True, ...} or {'condition': 1, ...}, or a string that is not a valid Jinja2 template.

Common situations: Building routes programmatically where a boolean condition is passed instead of a template string like '{{ flag }}'; YAML/JSON config loading that yields booleans or None for conditions.

Related errors


AI-assisted analysis of deepset-ai/haystack@e318778c9b (2026-08-30). Data as JSON: /api/errors/518f2cc20ec770bb. Report an issue: GitHub.