Skip to content

Commit 4d00381

Browse files
committed
fix bug in execute code
1 parent 575692f commit 4d00381

File tree

3 files changed

+22
-7
lines changed

3 files changed

+22
-7
lines changed

optillm/plugins/executecode_plugin.py

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,29 @@
1010

1111
def extract_python_code(text: str) -> List[str]:
1212
"""Extract Python code blocks from text."""
13+
# print(f"Extracting code: {text}")
1314
pattern = r'```python\s*(.*?)\s*```'
1415
return re.findall(pattern, text, re.DOTALL)
1516

1617
def execute_code(code: str) -> str:
1718
"""Execute Python code in a Jupyter notebook environment."""
18-
with tempfile.NamedTemporaryFile(suffix='.ipynb', delete=False) as tmp:
19-
notebook = nbformat.v4.new_notebook()
20-
notebook['cells'] = [nbformat.v4.new_code_cell(code)]
21-
nbformat.write(notebook, tmp)
19+
20+
notebook = nbformat.v4.new_notebook()
21+
notebook['cells'] = [nbformat.v4.new_code_cell(code)]
22+
23+
# Convert notebook to JSON string
24+
notebook_json = nbformat.writes(notebook)
25+
26+
# Convert JSON string to bytes
27+
notebook_bytes = notebook_json.encode('utf-8')
28+
29+
with tempfile.NamedTemporaryFile(mode='wb', suffix='.ipynb', delete=False) as tmp:
30+
tmp.write(notebook_bytes)
31+
tmp.flush()
32+
tmp_name = tmp.name
2233

2334
try:
24-
with open(tmp.name) as f:
35+
with open(tmp_name, 'r', encoding='utf-8') as f:
2536
nb = nbformat.read(f, as_version=4)
2637
ep = ExecutePreprocessor(timeout=30, kernel_name='python3')
2738
ep.preprocess(nb, {'metadata': {'path': './'}})
@@ -38,7 +49,7 @@ def execute_code(code: str) -> str:
3849

3950
return output.strip()
4051
finally:
41-
os.unlink(tmp.name)
52+
os.unlink(tmp_name)
4253

4354
def should_execute_request_code(query: str) -> bool:
4455
"""Decide whether to execute code from the request based on the query."""

requirements.txt

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,6 @@ lxml
1616
presidio_analyzer
1717
presidio_anonymizer
1818
nbformat
19-
nbconvert
19+
nbconvert
20+
ipython
21+
ipykernel

setup.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
"presidio_anonymizer",
2525
"nbconvert",
2626
"nbformat",
27+
"ipython",
28+
"ipykernel",
2729
],
2830
author="codelion",
2931
author_email="codelion@okyasoft.com",

0 commit comments

Comments
 (0)