# ContextExpression

## ``autogen.ContextExpression`dataclass`[

```
ContextExpression(expression)
```

A class to evaluate logical expressions using context variables.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `expression` | A string containing a logical expression with context variable references. - Variable references use ${var_name} syntax: ${logged_in}, ${attempts} - String literals can use normal quotes: 'hello', "world" - Supported operators: - Logical: not/!, and/&, or/\| - Comparison: >, <, >=, <=, ==, != - Supported functions: - len(${var_name}): Gets the length of a list, string, or other collection - Parentheses can be used for grouping - Examples: - "not ${logged_in} and ${is_admin} or ${guest_checkout}" - "!${logged_in} & ${is_admin} \| ${guest_checkout}" - "len(${orders}) > 0 & ${user_active}" - "len(${cart_items}) == 0 \| ${checkout_started}"<br>**TYPE:**`str` |

| RAISES | DESCRIPTION |
| --- | --- |
| `SyntaxError` | If the expression cannot be parsed |
| `ValueError` | If the expression contains disallowed operations |

### ``expression`instance-attribute`[

```
expression
```

### ``evaluate [

```
evaluate(context_variables)
```

Evaluate the expression using the provided context variables.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `context_variables` | Dictionary of context variables to use for evaluation<br>**TYPE:**`ContextVariables` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `bool` | The result of evaluating the expression<br>**TYPE:**`bool` |

| RAISES | DESCRIPTION |
| --- | --- |
| `KeyError` | If a variable referenced in the expression is not found in the context |

Source code in `autogen/agentchat/group/context_expression.py`

|     |     |
| --- | --- |
| ```<br>def evaluate(self, context_variables: ContextVariables) -> bool:<br>    """Evaluate the expression using the provided context variables.<br>    Args:<br>        context_variables: Dictionary of context variables to use for evaluation<br>    Returns:<br>        bool: The result of evaluating the expression<br>    Raises:<br>        KeyError: If a variable referenced in the expression is not found in the context<br>    """<br>    # Create a modified expression that we can safely evaluate<br>    eval_expr = self._python_expr  # Use the Python-syntax version<br>    # First, handle len() functions with variable references inside<br>    len_pattern = r"len\(\${([^}]*)}\)"<br>    len_matches = list(re.finditer(len_pattern, eval_expr))<br>    # Process all len() operations first<br>    for match in len_matches:<br>        var_name = match.group(1)<br>        # Check if variable exists in context, raise KeyError if not<br>        if not context_variables.contains(var_name):<br>            raise KeyError(f"Missing context variable: '{var_name}'")<br>        var_value = context_variables.get(var_name)<br>        # Calculate the length - works for lists, strings, dictionaries, etc.<br>        try:<br>            length_value = len(var_value)  # type: ignore[arg-type]<br>        except TypeError:<br>            # If the value doesn't support len(), treat as 0<br>            length_value = 0<br>        # Replace the len() expression with the actual length<br>        full_match = match.group(0)<br>        eval_expr = eval_expr.replace(full_match, str(length_value))<br>    # Then replace remaining variable references with their values<br>    for var_name in self._variable_names:<br>        # Skip variables that were already processed in len() expressions<br>        if any(m.group(1) == var_name for m in len_matches):<br>            continue<br>        # Check if variable exists in context, raise KeyError if not<br>        if not context_variables.contains(var_name):<br>            raise KeyError(f"Missing context variable: '{var_name}'")<br>        # Get the value from context<br>        var_value = context_variables.get(var_name)<br>        # Format the value appropriately based on its type<br>        if isinstance(var_value, (bool, int, float)):<br>            formatted_value = str(var_value)<br>        elif isinstance(var_value, str):<br>            formatted_value = f"'{var_value}'"  # Quote strings<br>        elif isinstance(var_value, (list, dict, tuple)):<br>            # For collections, convert to their boolean evaluation<br>            formatted_value = str(bool(var_value))<br>        else:<br>            formatted_value = str(var_value)<br>        # Replace the variable reference with the formatted value<br>        eval_expr = eval_expr.replace(f"$\{{{var_name}}}", formatted_value)<br>    try:<br>        return eval(eval_expr)  # type: ignore[no-any-return]<br>    except Exception as e:<br>        raise ValueError(<br>            f"Error evaluating expression '{self.expression}' (are you sure you're using $\{{my_context_variable_key}}): {str(e)}"<br>        )<br>``` |
