Skip to content

Fix dictionary expression evaluation bug #483

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion nemoguardrails/colang/v2_x/runtime/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,22 @@ def eval_expression(expr: str, context: dict) -> Any:
functions=functions,
names=expr_locals,
)
return s.eval(updated_expr)

result = s.eval(updated_expr)

# Assign back changed values to dictionary variables
for var_name, val in expr_locals.items():
if isinstance(val, AttributeDict):
var_name = var_name[4:]
global_var_name = f"_global_{var_name}"
if global_var_name in context:
context[global_var_name].clear()
context[global_var_name].update(val)
else:
context[var_name].clear()
context[var_name].update(val)

return result
except Exception as e:
raise ColangValueError(f"Error evaluating '{expr}'") from e

Expand Down
33 changes: 32 additions & 1 deletion tests/v2_x/test_slide_mechanics.py
Original file line number Diff line number Diff line change
Expand Up @@ -918,5 +918,36 @@ def test_out_flow_variables():
)


def test_expression_evaluation():
"""Test the different ways of expression evaluations."""

content = """
flow main
$dict = {"val": 2 + 3}
start bot say number ($dict["val"])
($dict.update({"val":10}))
bot say number ($dict["val"] + 1)

flow bot say number $number
await UtteranceBotAction(script="{$number}")
"""

config = _init_state(content)
state = run_to_completion(config, start_main_flow_event)
assert is_data_in_events(
state.outgoing_events,
[
{
"type": "StartUtteranceBotAction",
"script": "5",
},
{
"type": "StartUtteranceBotAction",
"script": "11",
},
],
)


if __name__ == "__main__":
test_when_or_core_mechanics()
test_expression_evaluation()
Loading