Skip to content
Open
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
16 changes: 12 additions & 4 deletions envs/repl_env/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,18 @@ def _default_answer(
]
try:
response = self._chat(final_prompt, model)
# Try to extract FINAL(...) from the response
match = re.search(r"FINAL\((.*?)\)", response, re.DOTALL)
if match:
return match.group(1).strip()
# Try to extract FINAL(...) from the response. Paren-counting handles
# nested parens and mid-sentence FINAL without regex flag trade-offs.
idx = response.find("FINAL(")
if idx != -1:
depth, start = 0, idx + len("FINAL")
for i, ch in enumerate(response[idx + len("FINAL"):], start=idx + len("FINAL")):
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0:
return response[start + 1 : i].strip()
# If no FINAL pattern, return the raw response as best-effort
return response.strip() if response.strip() else None
except Exception:
Expand Down
16 changes: 12 additions & 4 deletions envs/repl_env/server/repl_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,10 +536,18 @@ def _extract_final_answer(self, stdout: str) -> Optional[str]:
Returns:
Final answer string or None if not found
"""
# Pattern 1: RLM-style FINAL(answer)
final_match = re.search(r"FINAL\((.*?)\)", stdout, re.DOTALL)
if final_match:
return final_match.group(1).strip()
# Pattern 1: RLM-style FINAL(answer). Paren-counting handles nested
# parens (e.g. FINAL(f(x))) and multi-line values without regex flag trade-offs.
idx = stdout.find("FINAL(")
if idx != -1:
depth, start = 0, idx + len("FINAL")
for i, ch in enumerate(stdout[idx + len("FINAL"):], start=idx + len("FINAL")):
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0:
return stdout[start + 1 : i].strip()

# Pattern 2: RLM-style FINAL_VAR(variable_name)
final_var_match = re.search(r"FINAL_VAR\((\w+)\)", stdout)
Expand Down
26 changes: 26 additions & 0 deletions tests/envs/test_repl_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,32 @@ def test_final_pattern_basic(self):
assert obs.done
assert obs.metadata["final_answer"] == "42"

@pytest.mark.parametrize(
"code, expected",
[
# Nested function calls inside FINAL(...).
("print('FINAL(f(x))')", "f(x)"),
# Tuple as the final answer.
("print('FINAL((1, 2, 3))')", "(1, 2, 3)"),
# Math expression with multiple nested parens (e2b_repl_example).
(
"print('FINAL(2^(2^(2^(2))) = 65536)')",
"2^(2^(2^(2))) = 65536",
),
# Dict containing a tuple value.
("print(\"FINAL({'a': (1, 2)})\")", "{'a': (1, 2)}"),
# Output after FINAL must not bleed into the extracted answer.
("print('FINAL(42)\\nresult: (ok)')", "42"),
],
)
def test_final_pattern_nested_parentheses(self, code, expected):
"""FINAL(...) extraction must handle nested parentheses (rlm #75)."""
env = REPLEnvironment()
env.reset()
obs = env.step(REPLAction(code=code))
assert obs.done
assert obs.metadata["final_answer"] == expected
Comment on lines +250 to +256
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Test suite doesn't cover the cross-line over-match regression

All parametrized cases print FINAL(...) as an isolated single-line string, so they pass with either the current (DOTALL) or the corrected (no DOTALL) regex. Adding one case where stdout contains a ) on a subsequent line — e.g. print('FINAL(42)\nresult: (ok)') expecting "42" — would have caught the DOTALL bug and will guard against regressions.

Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/envs/test_repl_env.py
Line: 248-254

Comment:
**Test suite doesn't cover the cross-line over-match regression**

All parametrized cases print `FINAL(...)` as an isolated single-line string, so they pass with *either* the current (DOTALL) or the corrected (no DOTALL) regex. Adding one case where `stdout` contains a `)` on a subsequent line — e.g. `print('FINAL(42)\nresult: (ok)')` expecting `"42"` — would have caught the DOTALL bug and will guard against regressions.

How can I resolve this? If you propose a fix, please make it concise.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated


def test_final_var_pattern(self):
"""Test FINAL_VAR() pattern."""
env = REPLEnvironment()
Expand Down