|
| 1 | +"""Runtime expression support for FlowDefinition CEL expressions.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import copy |
| 6 | +import dataclasses |
| 7 | +from itertools import pairwise |
| 8 | +import json |
| 9 | +import re |
| 10 | +from typing import TYPE_CHECKING, Any, cast |
| 11 | + |
| 12 | +from pydantic import BaseModel |
| 13 | + |
| 14 | + |
| 15 | +if TYPE_CHECKING: |
| 16 | + from crewai.flow.runtime import Flow |
| 17 | + |
| 18 | + |
| 19 | +_EXPRESSION_PATTERN = re.compile(r"\$\{([^{}]*)\}") |
| 20 | + |
| 21 | +__all__ = ["FlowExpressionError", "evaluate_expression", "render_with_block"] |
| 22 | + |
| 23 | + |
| 24 | +class FlowExpressionError(ValueError): |
| 25 | + """A FlowDefinition expression failed to parse or evaluate.""" |
| 26 | + |
| 27 | + |
| 28 | +def render_with_block(flow: Flow[Any], value: Any) -> Any: |
| 29 | + """Render CEL expressions inside a FlowDefinition ``with:`` payload.""" |
| 30 | + context = _expression_context(flow) |
| 31 | + return _render_value(value, context) |
| 32 | + |
| 33 | + |
| 34 | +def evaluate_expression(flow: Flow[Any], expression: str) -> Any: |
| 35 | + """Evaluate a FlowDefinition CEL expression against runtime context.""" |
| 36 | + expression = expression.strip() |
| 37 | + if not expression: |
| 38 | + raise FlowExpressionError("empty CEL expression") |
| 39 | + return _eval_cel(expression, _expression_context(flow)) |
| 40 | + |
| 41 | + |
| 42 | +def _expression_context(flow: Flow[Any]) -> dict[str, Any]: |
| 43 | + return { |
| 44 | + "state": flow._copy_and_serialize_state(), |
| 45 | + "outputs": _outputs_by_name(flow._method_outputs), |
| 46 | + } |
| 47 | + |
| 48 | + |
| 49 | +def _outputs_by_name(method_outputs: list[Any]) -> dict[str, Any]: |
| 50 | + outputs: dict[str, Any] = {} |
| 51 | + for entry in method_outputs: |
| 52 | + method = "" |
| 53 | + output = entry |
| 54 | + if isinstance(entry, dict) and "output" in entry: |
| 55 | + method = str(entry.get("method", "")) |
| 56 | + output = entry["output"] |
| 57 | + output = copy.deepcopy(output) |
| 58 | + if isinstance(output, BaseModel): |
| 59 | + output = output.model_dump(mode="json") |
| 60 | + elif dataclasses.is_dataclass(output) and not isinstance(output, type): |
| 61 | + output = dataclasses.asdict(output) |
| 62 | + outputs[method] = output |
| 63 | + return outputs |
| 64 | + |
| 65 | + |
| 66 | +def _render_value(value: Any, context: dict[str, Any]) -> Any: |
| 67 | + if isinstance(value, str): |
| 68 | + return _render_string(value, context) |
| 69 | + if isinstance(value, dict): |
| 70 | + return {key: _render_value(item, context) for key, item in value.items()} |
| 71 | + if isinstance(value, list): |
| 72 | + return [_render_value(item, context) for item in value] |
| 73 | + return value |
| 74 | + |
| 75 | + |
| 76 | +def _render_string(value: str, context: dict[str, Any]) -> Any: |
| 77 | + matches = list(_EXPRESSION_PATTERN.finditer(value)) |
| 78 | + if not matches: |
| 79 | + _raise_for_invalid_interpolation(value) |
| 80 | + return value |
| 81 | + |
| 82 | + _raise_for_literal_braces(value[: matches[0].start()]) |
| 83 | + for previous, current in pairwise(matches): |
| 84 | + _raise_for_literal_braces(value[previous.end() : current.start()]) |
| 85 | + _raise_for_literal_braces(value[matches[-1].end() :]) |
| 86 | + |
| 87 | + if len(matches) == 1 and matches[0].span() == (0, len(value)): |
| 88 | + expression = matches[0].group(1).strip() |
| 89 | + if not expression: |
| 90 | + raise FlowExpressionError("empty CEL expression in with block") |
| 91 | + return _eval_cel(expression, context) |
| 92 | + |
| 93 | + rendered: list[str] = [] |
| 94 | + position = 0 |
| 95 | + for match in matches: |
| 96 | + start, end = match.span() |
| 97 | + literal = value[position:start] |
| 98 | + rendered.append(literal) |
| 99 | + |
| 100 | + expression = match.group(1).strip() |
| 101 | + if not expression: |
| 102 | + raise FlowExpressionError("empty CEL expression in with block") |
| 103 | + result = _eval_cel(expression, context) |
| 104 | + rendered.append(result if isinstance(result, str) else json.dumps(result)) |
| 105 | + position = end |
| 106 | + |
| 107 | + literal = value[position:] |
| 108 | + rendered.append(literal) |
| 109 | + |
| 110 | + return "".join(rendered) |
| 111 | + |
| 112 | + |
| 113 | +def _raise_for_invalid_interpolation(value: str) -> None: |
| 114 | + if "${" not in value: |
| 115 | + return |
| 116 | + raise FlowExpressionError( |
| 117 | + "invalid CEL interpolation in with block: expressions must be enclosed " |
| 118 | + "as ${...} and cannot contain braces" |
| 119 | + ) |
| 120 | + |
| 121 | + |
| 122 | +def _raise_for_literal_braces(value: str) -> None: |
| 123 | + if "{" not in value and "}" not in value: |
| 124 | + return |
| 125 | + raise FlowExpressionError( |
| 126 | + "invalid CEL interpolation in with block: expressions must be enclosed " |
| 127 | + "as ${...} and cannot contain braces" |
| 128 | + ) |
| 129 | + |
| 130 | + |
| 131 | +def _eval_cel(expression: str, context: dict[str, Any]) -> Any: |
| 132 | + try: |
| 133 | + from celpy import Environment |
| 134 | + from celpy.adapter import CELJSONEncoder, json_to_cel |
| 135 | + from celpy.evaluation import Context |
| 136 | + |
| 137 | + environment = Environment() |
| 138 | + program = environment.program(environment.compile(expression)) |
| 139 | + result = program.evaluate(cast(Context, json_to_cel(context))) |
| 140 | + return json.loads(json.dumps(result, cls=CELJSONEncoder)) |
| 141 | + except Exception as e: |
| 142 | + raise FlowExpressionError( |
| 143 | + f"failed to evaluate CEL expression {expression!r}: {e}" |
| 144 | + ) from e |
0 commit comments