ContextExpression - AG2
ContextExpression
``autogen.ContextExpressiondataclass
ContextExpression(expression)
A class to evaluate logical expressions using context variables.
Args:
expression (str): 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}"
Raises:
SyntaxError: If the expression cannot be parsed
ValueError: If the expression contains disallowed operations
``expressioninstance-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 TYPE: ContextVariables |
| RETURNS | DESCRIPTION |
|---|---|
bool |
The result of evaluating the expression 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>157<br>158<br>159<br>160<br>161<br>162<br>163<br>164<br>165<br>166<br>167<br>168<br>169<br>170<br>171<br>172<br>173<br>174<br>175<br>176<br>177<br>178<br>179<br>180<br>181<br>182<br>183<br>184<br>185<br>186<br>187<br>188<br>189<br>190<br>191<br>192<br>193<br>194<br>195<br>196<br>197<br>198<br>199<br>200<br>201<br>202<br>203<br>204<br>205<br>206<br>207<br>208<br>209<br>210<br>211<br>212<br>213<br>214<br>215<br>216<br>217<br>218<br>219<br>220<br>221<br>222<br>223<br>224<br>225<br>226<br>227<br>228<br> |
<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> |