-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathcode_execution.py
More file actions
1626 lines (1376 loc) · 56.2 KB
/
code_execution.py
File metadata and controls
1626 lines (1376 loc) · 56.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# mypy: ignore-errors
"""
Code execution reward functions for evaluating code correctness.
This module provides functions to evaluate the correctness of code by:
1. Extracting code blocks from messages
2. Executing the code in a secure environment (local or E2B sandbox)
3. Comparing the output with expected results
Available reward functions:
- local_code_execution_reward: Execute code locally and evaluate correctness
- e2b_code_execution_reward: Execute code in E2B sandbox and evaluate correctness
- fractional_code_reward: Execute code and return exact pass rate
"""
import faulthandler
import json
import multiprocessing
import os
import platform
import re
import resource
import shlex # Added for robust splitting of arguments
import signal
import subprocess
import sys
import tempfile
import traceback
from io import StringIO
from multiprocessing.managers import DictProxy
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
# Try to import from e2b_code_interpreter first (preferred)
try:
from e2b_code_interpreter.sync import Sandbox # type: ignore # Use SyncSandbox
_HAS_E2B = True
_E2B_SOURCE = "e2b_code_interpreter"
except ImportError:
# Fallback to e2b
try:
# Assuming 'e2b' package's default Sandbox is synchronous.
# If 'e2b' also defaults to async, this part might need adjustment too.
from e2b import Sandbox # type: ignore
_HAS_E2B = True
_E2B_SOURCE = "e2b"
except ImportError:
_HAS_E2B = False
_E2B_SOURCE = "" # Use empty string instead of None
from ..models import EvaluateResult, Message, MetricResult
from ..reward_function import reward_function
def _target_func_for_execution(result_container, execute_func, args):
try:
result = execute_func(*args)
result_container.update(result)
except Exception as e:
error_traceback = traceback.format_exc()
result_container.update(
{
"success": False,
"output": None,
"error": f"Execution error: {str(e)}\n{error_traceback}",
}
)
def extract_code_blocks(text: str, language: Optional[str] = None) -> List[Dict[str, str]]:
"""
Extract code blocks from text.
Args:
text: The text to extract code blocks from
language: Optional language to filter by (e.g., "python", "javascript")
Returns:
List of dictionaries with "code" and "language" keys
"""
pattern = r"```(\w*)\n([\s\S]*?)\n```"
matches = re.findall(pattern, text)
code_blocks = []
verbose_patterns_removed = []
# Define patterns for verbose text that might appear inside code blocks
# These patterns will be removed.
# Using re.DOTALL to make '.' match newlines.
verbose_regex_patterns = [
re.compile(r"<think>.*?</think>", re.DOTALL),
re.compile(r"<reasoning>.*?</reasoning>", re.DOTALL),
re.compile(r"Thinking:\s*.*?(?=\n\S)", re.DOTALL), # Matches "Thinking: ..." until a new non-whitespace line
re.compile(r"^\s*Here's the Python code.*?\n", re.MULTILINE | re.IGNORECASE),
re.compile(r"^\s*Okay, here is the code:.*?\n", re.MULTILINE | re.IGNORECASE),
]
for lang, code_content in matches:
if language and lang and language.lower() != lang.lower():
continue
detected_lang = lang.lower() if lang else "unknown"
original_code_content = code_content
cleaned_code_content = code_content
for verbose_pattern in verbose_regex_patterns:
cleaned_code_content = verbose_pattern.sub("", cleaned_code_content)
if cleaned_code_content != original_code_content:
verbose_patterns_removed.append(f"Verbose content removed from '{detected_lang}' block.")
block_info = {
"language": detected_lang,
"code": cleaned_code_content.strip(),
}
if verbose_patterns_removed:
block_info["verbosity_cleaned_reason"] = "; ".join(verbose_patterns_removed)
verbose_patterns_removed = []
code_blocks.append(block_info)
return code_blocks
@reward_function
def local_code_execution_reward(
messages: List[Message],
ground_truth: Optional[str] = None, # This is the new expected_output_str
language: str = "python",
timeout: int = 5,
max_memory_mb: int = 100, # Specific to local execution
**kwargs,
) -> EvaluateResult:
"""
Evaluate code correctness by executing it locally and comparing the output.
This function executes code in a secure sandbox with memory limits, CPU limits,
and timeouts to prevent malicious code from harming the system.
Args:
messages: List of conversation messages. The last message is assumed to be the
assistant's response containing the code.
ground_truth: Expected output string from code execution. This corresponds to
the `expected_output_str` in the previous signature.
language: Programming language of the code ("python", "javascript", etc.)
timeout: Maximum execution time in seconds.
max_memory_mb: Maximum memory usage in megabytes (default: 100).
**kwargs: Additional keyword arguments.
Returns:
EvaluateResult with score and metrics.
"""
metrics: Dict[str, MetricResult] = {}
if (
not messages
or not isinstance(messages[-1], Message)
or messages[-1].role != "assistant"
or messages[-1].content is None
):
return EvaluateResult(
score=0.0,
reason="Invalid or missing assistant response in messages.",
metrics={
"error": MetricResult(
score=0.0,
is_score_valid=False,
reason="Last message not a valid assistant response.",
)
},
)
# Normalize content to string; Message.content may be str or list of content parts
last_content = messages[-1].content
response_content = (
last_content if isinstance(last_content, str) else "".join([p.text for p in (last_content or [])])
)
expected_output_str = ground_truth
code_blocks = extract_code_blocks(response_content, language)
if not code_blocks:
return EvaluateResult(
score=0.0,
reason=f"No {language} code blocks found in model's response.",
metrics={
"error": MetricResult(
score=0.0,
reason=f"No {language} code blocks found in model's response.",
is_score_valid=False,
)
},
)
code = code_blocks[0]["code"]
metrics["extracted_code"] = MetricResult(
score=0.0,
reason=f"Extracted code:\n```{language}\n{code}\n```",
is_score_valid=True,
)
if expected_output_str:
metrics["expected_output"] = MetricResult(
score=0.0,
reason=f"Expected output:\n{expected_output_str}",
is_score_valid=True,
)
if language.lower() == "python":
execution_result = execute_python_code(
code, timeout
) # max_memory_mb is handled inside _execute_python_in_subprocess
elif language.lower() in ["javascript", "js"]:
execution_result = execute_javascript_code(code, timeout)
else:
metrics["error"] = MetricResult(score=0.0, reason=f"Unsupported language: {language}", is_score_valid=False)
return EvaluateResult(score=0.0, reason=f"Unsupported language: {language}", metrics=metrics)
if execution_result["success"]:
output = execution_result["output"]
metrics["execution_result"] = MetricResult(
score=1.0,
reason=f"Code executed successfully with output:\n{output}",
is_score_valid=True,
)
if expected_output_str:
similarity = compare_outputs(output, expected_output_str)
match_reason = (
f"Output similarity: {similarity:.2f}\n\nExpected:\n{expected_output_str}\n\nActual:\n{output}"
)
metrics["output_match"] = MetricResult(
score=similarity, reason=match_reason, is_score_valid=similarity == 1.0
)
final_reason = f"Execution successful. Output similarity: {similarity:.2f}."
return EvaluateResult(score=similarity, reason=final_reason, metrics=metrics)
final_reason = "Execution successful. No expected output to compare."
return EvaluateResult(score=1.0, reason=final_reason, metrics=metrics)
else:
error = execution_result["error"]
metrics["execution_result"] = MetricResult(
score=0.0,
reason=f"Code execution failed with error:\n{error}",
is_score_valid=False,
)
final_reason = f"Code execution failed: {error}"
return EvaluateResult(score=0.0, reason=final_reason, metrics=metrics)
def _process_target_wrapper(execute_func: Callable, args: Tuple, result_container: DictProxy):
try:
result = execute_func(*args)
result_container.update(result)
except Exception as e:
error_traceback = traceback.format_exc()
result_container.update(
{
"success": False,
"output": None,
"error": f"Execution error: {str(e)}\n{error_traceback}",
}
)
def _execute_code_in_process(execute_func: Callable, args: Tuple, timeout: int = 5) -> Dict[str, Any]:
"""
Execute code in a separate process with timeout and resource limits.
Args:
execute_func: Function to execute the code
args: Arguments to pass to the execute function
timeout: Maximum execution time in seconds
Returns:
Dictionary with execution results
"""
manager = multiprocessing.Manager()
result_dict = manager.dict()
process = multiprocessing.Process(target=_process_target_wrapper, args=(execute_func, args, result_dict))
process.start()
process.join(timeout=timeout + 0.5)
if process.is_alive():
process.terminate()
process.join(0.5)
if process.is_alive():
process.kill()
return {
"success": False,
"output": None,
"error": f"Timeout: execution timed out after {timeout} seconds",
}
if not result_dict:
return {
"success": False,
"output": None,
"error": "Execution failed without producing any output",
}
return dict(result_dict)
def _execute_python_in_subprocess(code: str, timeout: int) -> Dict[str, Any]:
"""
Inner function to execute Python code in a subprocess.
Args:
code: Python code to execute
timeout: Maximum execution time in seconds
Returns:
Dictionary with execution results
"""
try:
with tempfile.NamedTemporaryFile(suffix=".py", delete=False) as temp_file:
temp_file_path = temp_file.name
safe_code = (
"import sys\n"
"import os\n"
"import signal\n"
"import resource\n"
"import platform\n\n"
"def _reliability_guard():\n"
" memory_limit = 100 * 1024 * 1024 # 100 MB\n"
" if platform.uname().system != 'Darwin':\n"
" resource.setrlimit(resource.RLIMIT_AS, (memory_limit, memory_limit))\n"
" resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit))\n"
" resource.setrlimit(resource.RLIMIT_STACK, (memory_limit, memory_limit))\n"
" import builtins\n"
" builtins.exit = None\n"
" builtins.quit = None\n"
" os.environ['OMP_NUM_THREADS'] = '1'\n"
" os.system = None\n"
" os.popen = None\n"
" os.execl = None\n"
" os.execve = None\n"
" os.fork = None\n"
" os.remove = None\n"
" os.removedirs = None\n"
" os.rmdir = None\n"
" os.unlink = None\n"
" os.access = None\n"
"\n"
"_reliability_guard()\n\n" + code
)
temp_file.write(safe_code.encode("utf-8"))
def timeout_handler(signum, frame):
raise TimeoutError(f"Execution timed out after {timeout} seconds")
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(timeout)
try:
process = subprocess.Popen(
[sys.executable, temp_file_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
preexec_fn=lambda: resource.setrlimit(resource.RLIMIT_CPU, (timeout, timeout + 1)),
)
stdout, stderr = process.communicate()
signal.alarm(0)
if process.returncode == 0:
return {
"success": True,
"output": stdout.strip(),
"error": None,
}
else:
return {
"success": False,
"output": None,
"error": stderr.strip(),
}
except TimeoutError as e:
return {"success": False, "output": None, "error": str(e)}
finally:
signal.alarm(0)
if os.path.exists(temp_file_path):
os.unlink(temp_file_path)
except Exception as e:
error_traceback = traceback.format_exc()
return {
"success": False,
"output": None,
"error": f"Setup error: {str(e)}\n{error_traceback}",
}
def execute_python_code(code: str, timeout: int = 5) -> Dict[str, Any]:
"""
Execute Python code in a secure sandbox.
Args:
code: Python code to execute
timeout: Maximum execution time in seconds
Returns:
Dictionary with execution results
"""
return _execute_code_in_process(_execute_python_in_subprocess, args=(code, timeout), timeout=timeout)
def _execute_javascript_in_subprocess(code: str, timeout: int) -> Dict[str, Any]:
"""
Inner function to execute JavaScript code in a subprocess.
Args:
code: JavaScript code to execute
timeout: Maximum execution time in seconds
Returns:
Dictionary with execution results
"""
try:
try:
subprocess.run(["node", "--version"], capture_output=True, check=True)
except (subprocess.SubprocessError, FileNotFoundError):
return {
"success": False,
"output": None,
"error": "Node.js is not installed or not found in PATH",
}
with tempfile.NamedTemporaryFile(suffix=".js", delete=False) as temp_file:
temp_file_path = temp_file.name
safe_code = (
"// Safety wrapper to prevent dangerous operations\n"
"process.on('uncaughtException', function(err) {\n"
" console.error('Uncaught exception:', err.message);\n"
" process.exit(1);\n"
"});\n\n"
"process.exit = function() { console.error('exit() is disabled'); };\n"
"process.kill = function() { console.error('kill() is disabled'); };\n"
"const fs = require('fs');\n"
"const originalFsReadFile = fs.readFileSync;\n"
"const originalFsWriteFile = fs.writeFileSync;\n"
"fs.readFileSync = function() { console.error('fs.readFileSync() is disabled'); return ''; };\n"
"fs.writeFileSync = function() { console.error('fs.writeFileSync() is disabled'); };\n"
"const originalRequire = require;\n"
"global.require = function(module) {\n"
" const safeModules = ['assert', 'buffer', 'crypto', 'events', 'path', 'querystring',\n"
" 'string_decoder', 'stream', 'timers', 'url', 'util', 'zlib'];\n"
" if (safeModules.includes(module)) {\n"
" return originalRequire(module);\n"
" } else {\n"
" console.error(`Requiring module '${module}' is not allowed for security reasons`);\n"
" return {};\n"
" }\n"
"};\n\n"
"try {\n"
" " + code.replace("\n", "\n ") + "\n"
"} catch (error) {\n"
" console.error('Code execution error:', error.message);\n"
" process.exitCode = 1;\n"
"}\n"
)
temp_file.write(safe_code.encode("utf-8"))
def timeout_handler(signum, frame):
raise TimeoutError(f"Execution timed out after {timeout} seconds")
signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(timeout)
try:
process = subprocess.Popen(
[
"node",
"--no-warnings",
"--max-old-space-size=100",
temp_file_path,
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
try:
stdout, stderr = process.communicate(timeout=timeout)
except subprocess.TimeoutExpired:
process.kill()
stdout, stderr = process.communicate()
signal.alarm(0)
return {
"success": False,
"output": None,
"error": f"JavaScript execution timed out after {timeout} seconds (subprocess.TimeoutExpired). Output: {stdout.strip()}, Error: {stderr.strip()}",
}
signal.alarm(0)
if process.returncode == 0:
return {
"success": True,
"output": stdout.strip(),
"error": None,
}
else:
return {
"success": False,
"output": None,
"error": stderr.strip() or f"JavaScript process exited with code {process.returncode}",
}
except TimeoutError as e:
process.kill()
_, _ = process.communicate()
return {
"success": False,
"output": None,
"error": f"JavaScript execution timed out after {timeout} seconds (signal.alarm): {str(e)}",
}
finally:
signal.alarm(0)
if os.path.exists(temp_file_path):
os.unlink(temp_file_path)
except Exception as e:
error_traceback = traceback.format_exc()
return {
"success": False,
"output": None,
"error": f"Setup error: {str(e)}\n{error_traceback}",
}
def execute_javascript_code(code: str, timeout: int = 5) -> Dict[str, Any]:
"""
Execute JavaScript code in a secure sandbox.
Args:
code: JavaScript code to execute
timeout: Maximum execution time in seconds
Returns:
Dictionary with execution results
"""
return _execute_code_in_process(_execute_javascript_in_subprocess, args=(code, timeout), timeout=timeout)
def compare_outputs(actual: str, expected: str) -> float:
"""
Compare actual and expected outputs to calculate a similarity score.
Args:
actual: Actual output from code execution
expected: Expected output
Returns:
Similarity score between 0.0 and 1.0
"""
actual_norm = normalize_output(actual)
expected_norm = normalize_output(expected)
if actual_norm == expected_norm:
return 1.0
if is_numeric(actual_norm) and is_numeric(expected_norm):
try:
actual_num = float(actual_norm)
expected_num = float(expected_norm)
if expected_num == 0:
return 1.0 if actual_num == 0 else 0.0
rel_diff = abs(actual_num - expected_num) / abs(expected_num)
if rel_diff <= 0.001:
return 1.0
elif rel_diff <= 0.01:
return 0.9
elif rel_diff <= 0.1:
return 0.7
else:
return max(0.0, 1.0 - min(1.0, rel_diff))
except (ValueError, TypeError):
pass
if (
actual_norm.startswith("[")
and actual_norm.endswith("]")
and expected_norm.startswith("[")
and expected_norm.endswith("]")
):
try:
actual_list = json.loads(actual_norm)
expected_list = json.loads(expected_norm)
if not actual_list and not expected_list:
return 1.0
if not isinstance(actual_list, list) or not isinstance(expected_list, list):
raise ValueError("Not a list")
len_similarity = 1.0 - min(
1.0,
abs(len(actual_list) - len(expected_list)) / max(1, max(len(actual_list), len(expected_list))),
)
items_similarity = 0.0
if len(actual_list) > 0 and len(expected_list) > 0:
total_similarity = 0.0
for exp_item in expected_list:
best_match = 0.0
for act_item in actual_list:
item_similarity = compare_outputs(str(act_item), str(exp_item))
best_match = max(best_match, item_similarity)
total_similarity += best_match
items_similarity = total_similarity / len(expected_list)
return 0.3 * len_similarity + 0.7 * items_similarity
except (ValueError, json.JSONDecodeError):
pass
if "\n" in actual_norm or "\n" in expected_norm:
actual_lines = actual_norm.strip().split("\n")
expected_lines = expected_norm.strip().split("\n")
if not actual_lines and not expected_lines:
return 1.0
len_similarity = 1.0 - min(
1.0,
abs(len(actual_lines) - len(expected_lines)) / max(1, max(len(actual_lines), len(expected_lines))),
)
lines_similarity = 0.0
common_len = min(len(actual_lines), len(expected_lines))
if common_len > 0:
total_similarity = 0.0
for i in range(common_len):
line_similarity = string_similarity(actual_lines[i], expected_lines[i])
total_similarity += line_similarity
lines_similarity = total_similarity / common_len
return 0.3 * len_similarity + 0.7 * lines_similarity
return string_similarity(actual_norm, expected_norm)
def string_similarity(s1: str, s2: str) -> float:
"""
Calculate string similarity using character-level comparison.
Args:
s1: First string
s2: Second string
Returns:
Similarity score between 0.0 and 1.0
"""
if not s1 and not s2:
return 1.0
if not s1 or not s2:
return 0.0
m, n = len(s1), len(s2)
lcs_length = longest_common_subsequence_length(s1, s2)
return lcs_length / max(m, n)
def longest_common_subsequence_length(s1: str, s2: str) -> int:
"""
Calculate the length of the longest common subsequence.
Args:
s1: First string
s2: Second string
Returns:
Length of longest common subsequence
"""
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
def normalize_output(output: str) -> str:
"""
Normalize output for comparison.
Args:
output: Output string to normalize
Returns:
Normalized output string
"""
normalized = output.strip()
normalized = normalized.replace("\r\n", "\n").replace("\r", "\n")
normalized = re.sub(r"\s+", " ", normalized)
return normalized
def is_numeric(value: str) -> bool:
"""
Check if a string value represents a numeric value.
Args:
value: String value to check
Returns:
True if the value is numeric, False otherwise
"""
try:
float(value)
return True
except (ValueError, TypeError):
return False
def noop(*args: Any, **kwargs: Any) -> Any:
"""A no-operation function that returns None."""
return None
def execute_code_with_e2b(
code: str,
language: str = "python",
timeout: int = 30,
api_key: Optional[str] = None,
) -> Dict[str, Any]:
"""
Execute code within an E2B sandbox.
Args:
code: Code to execute
language: Programming language of the code ("python", "javascript", etc.)
timeout: Maximum execution time in seconds
api_key: Optional E2B API key (if not provided, will use E2B_API_KEY env var)
Returns:
Dictionary with execution results
"""
if not _HAS_E2B:
return {
"success": False,
"output": None,
"error": "E2B package not installed. Install with: pip install e2b",
}
try:
if api_key is None and os.environ.get("E2B_API_KEY") is None:
return {
"success": False,
"output": None,
"error": "API key is required for E2B execution. Set it using the api_key parameter or E2B_API_KEY environment variable.",
}
with Sandbox(api_key=api_key) as sandbox:
stdout = []
stderr = []
def capture_stdout(output):
if hasattr(output, "line"):
stdout.append(output.line)
else:
stdout.append(str(output))
def capture_stderr(output):
if hasattr(output, "line"):
stderr.append(output.line)
else:
stderr.append(str(output))
sandbox.on_exit = lambda *args: None # type: ignore[method-assign, assignment]
if language.lower() in ["python", "py"]:
file_path = "/code/script.py"
cmd = "python3 /code/script.py"
elif language.lower() in ["javascript", "js"]:
file_path = "/code/script.js"
cmd = "node /code/script.js"
else:
return {
"success": False,
"output": None,
"error": f"Unsupported language for E2B: {language}",
}
try:
fs_handler = None
if _E2B_SOURCE == "e2b_code_interpreter":
if hasattr(sandbox, "filesystem"):
fs_handler = sandbox.filesystem
elif _E2B_SOURCE == "e2b":
if hasattr(sandbox, "_filesystem"):
fs_handler = sandbox._filesystem
elif hasattr(sandbox, "filesystem"):
fs_handler = sandbox.filesystem
if not fs_handler:
return {
"success": False,
"output": None,
"error": "Could not access E2B sandbox filesystem handler.",
}
try:
fs_handler.make_dir("/code")
except Exception:
pass
fs_handler.write(file_path, code)
except Exception as e:
return {
"success": False,
"output": None,
"error": f"Failed to write code to sandbox: {str(e)}",
}
try:
result = sandbox.commands.run(
cmd,
on_stdout=capture_stdout,
on_stderr=capture_stderr,
timeout=timeout,
)
output = "\n".join(stdout)
error_output = "\n".join(stderr)
if result.exit_code == 0:
return {"success": True, "output": output, "error": None}
else:
return {
"success": False,
"output": None,
"error": f"Process exited with code {result.exit_code}: {error_output}",
}
except Exception as e:
return {
"success": False,
"output": None,
"error": f"Execution error: {str(e)}",
}
except Exception as e:
error_traceback = traceback.format_exc()
return {
"success": False,
"output": None,
"error": f"E2B setup error: {str(e)}\n{error_traceback}",
}
@reward_function
def e2b_code_execution_reward(
messages: List[Message],
ground_truth: Optional[str] = None,
language: str = "python",
timeout: int = 30,
api_key: Optional[str] = None,
**kwargs,
) -> EvaluateResult:
"""
Evaluate code correctness by executing it in E2B sandbox and comparing the output.
E2B provides a secure, cloud-based sandbox for executing code safely.
Args:
messages: List of conversation messages. The last message is assumed to be the
assistant's response containing the code.
ground_truth: Expected output string from code execution. This corresponds to
the `expected_output_str` in the previous signature.
language: Programming language of the code ("python", "javascript", etc.)
timeout: Maximum execution time in seconds.
api_key: Optional E2B API key (if not provided, will use E2B_API_KEY env var).
**kwargs: Additional keyword arguments.
Returns:
EvaluateResult with score and metrics.
"""
if not _HAS_E2B:
return EvaluateResult(
score=0.0,
reason="E2B package not installed.",
metrics={
"error": MetricResult(
score=0.0,
reason="E2B package not installed. Install with: pip install e2b",
is_score_valid=False,
)
},
)
if api_key is None and os.environ.get("E2B_API_KEY") is None:
return EvaluateResult(
score=0.0,
reason="E2B API key is required.",
metrics={
"error": MetricResult(
score=0.0,
reason="E2B API key is required. Set the E2B_API_KEY environment variable or provide api_key parameter.",
is_score_valid=False,
)
},
)
metrics: Dict[str, MetricResult] = {}
if (
not messages
or not isinstance(messages[-1], Message)
or messages[-1].role != "assistant"
or messages[-1].content is None
):
return EvaluateResult(
score=0.0,
reason="Invalid or missing assistant response in messages.",
metrics={
"error": MetricResult(
score=0.0,
is_score_valid=False,
reason="Last message not a valid assistant response.",
)
},
)
last_content = messages[-1].content
response_content = (
last_content if isinstance(last_content, str) else "".join([p.text for p in (last_content or [])])
)
expected_output_str = ground_truth
code_blocks = extract_code_blocks(response_content, language)
if not code_blocks:
return EvaluateResult(
score=0.0,
reason=f"No {language} code blocks found in model's response.",
metrics={
"error": MetricResult(
score=0.0,
reason=f"No {language} code blocks found in model's response.",
is_score_valid=False,
)
},
)
code = code_blocks[0]["code"]
metrics["extracted_code"] = MetricResult(
score=0.0,
reason=f"Extracted code:\n```{language}\n{code}\n```",
is_score_valid=True,
)
if expected_output_str:
metrics["expected_output"] = MetricResult(
score=0.0,
reason=f"Expected output:\n{expected_output_str}",
is_score_valid=True,
)
execution_result = execute_code_with_e2b(code=code, language=language, timeout=timeout, api_key=api_key)
if execution_result["success"]:
output = execution_result["output"]
metrics["execution_result"] = MetricResult(
score=1.0,
reason=f"Code executed successfully in E2B sandbox with output:\n{output}",
is_score_valid=True,
)
if expected_output_str:
similarity = compare_outputs(output, expected_output_str)
match_reason = (
f"Output similarity: {similarity:.2f}\n\nExpected:\n{expected_output_str}\n\nActual:\n{output}"
)
metrics["output_match"] = MetricResult(
score=similarity, reason=match_reason, is_score_valid=similarity == 1.0
)
final_reason = f"E2B execution successful. Output similarity: {similarity:.2f}."
return EvaluateResult(score=similarity, reason=final_reason, metrics=metrics)