Spaces:
Sleeping
Sleeping
Improved python code tool
Browse files
agent.py
CHANGED
|
@@ -67,7 +67,7 @@ def run_python_code(code: str):
|
|
| 67 |
# Also allow basic numpy/pandas imports
|
| 68 |
is_safe = is_safe or line.startswith("import numpy") or line.startswith("import pandas")
|
| 69 |
if not is_safe:
|
| 70 |
-
|
| 71 |
|
| 72 |
try:
|
| 73 |
# Capture stdout to get print output
|
|
@@ -903,25 +903,29 @@ def assistant(state: AgentState) -> Dict[str, Any]:
|
|
| 903 |
def extract_json_from_text(text: str) -> dict:
|
| 904 |
"""Extract JSON from text, handling markdown code blocks."""
|
| 905 |
try:
|
| 906 |
-
print(f"Attempting to extract JSON from text: {text[:
|
| 907 |
|
| 908 |
# Look for markdown code blocks - the most common pattern
|
| 909 |
if "```" in text:
|
| 910 |
print("Found markdown code block")
|
| 911 |
# Find all code blocks
|
| 912 |
blocks = []
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
if "```" in line
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
|
|
|
|
|
|
|
|
|
| 924 |
blocks.append(block_content)
|
|
|
|
| 925 |
|
| 926 |
# Try to parse each block as JSON
|
| 927 |
for block in blocks:
|
|
@@ -932,19 +936,38 @@ def extract_json_from_text(text: str) -> dict:
|
|
| 932 |
if block.startswith("json"):
|
| 933 |
block = block[4:].strip()
|
| 934 |
|
| 935 |
-
|
| 936 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 937 |
continue
|
| 938 |
|
| 939 |
-
# Look for JSON-like patterns in the text
|
| 940 |
-
|
| 941 |
-
|
| 942 |
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
|
| 946 |
-
|
| 947 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 948 |
|
| 949 |
# If we're here, we couldn't find a valid JSON object
|
| 950 |
print("Could not extract valid JSON from text")
|
|
@@ -1008,19 +1031,36 @@ def python_code_node(state: AgentState) -> Dict[str, Any]:
|
|
| 1008 |
# Extract tool arguments
|
| 1009 |
action_input = state.get("action_input", {})
|
| 1010 |
print(f"Python code action_input: {action_input}")
|
|
|
|
| 1011 |
|
| 1012 |
# Try different ways to extract the code
|
| 1013 |
code = ""
|
| 1014 |
if isinstance(action_input, dict):
|
| 1015 |
code = action_input.get("code", "")
|
|
|
|
| 1016 |
elif isinstance(action_input, str):
|
|
|
|
| 1017 |
code = action_input
|
|
|
|
| 1018 |
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1024 |
else:
|
| 1025 |
# Call the code execution function
|
| 1026 |
result = run_python_code(code)
|
|
|
|
| 67 |
# Also allow basic numpy/pandas imports
|
| 68 |
is_safe = is_safe or line.startswith("import numpy") or line.startswith("import pandas")
|
| 69 |
if not is_safe:
|
| 70 |
+
return f"Error: Code contains potentially unsafe import: {line}"
|
| 71 |
|
| 72 |
try:
|
| 73 |
# Capture stdout to get print output
|
|
|
|
| 903 |
def extract_json_from_text(text: str) -> dict:
|
| 904 |
"""Extract JSON from text, handling markdown code blocks."""
|
| 905 |
try:
|
| 906 |
+
print(f"Attempting to extract JSON from text: {text[:200]}...")
|
| 907 |
|
| 908 |
# Look for markdown code blocks - the most common pattern
|
| 909 |
if "```" in text:
|
| 910 |
print("Found markdown code block")
|
| 911 |
# Find all code blocks
|
| 912 |
blocks = []
|
| 913 |
+
lines = text.split('\n')
|
| 914 |
+
i = 0
|
| 915 |
+
while i < len(lines):
|
| 916 |
+
line = lines[i]
|
| 917 |
+
if "```" in line:
|
| 918 |
+
# Start of code block
|
| 919 |
+
start_idx = i + 1
|
| 920 |
+
i += 1
|
| 921 |
+
# Find the end of the code block
|
| 922 |
+
while i < len(lines) and "```" not in lines[i]:
|
| 923 |
+
i += 1
|
| 924 |
+
if i < len(lines):
|
| 925 |
+
# Found the end
|
| 926 |
+
block_content = '\n'.join(lines[start_idx:i])
|
| 927 |
blocks.append(block_content)
|
| 928 |
+
i += 1
|
| 929 |
|
| 930 |
# Try to parse each block as JSON
|
| 931 |
for block in blocks:
|
|
|
|
| 936 |
if block.startswith("json"):
|
| 937 |
block = block[4:].strip()
|
| 938 |
|
| 939 |
+
# Validate JSON before parsing
|
| 940 |
+
parsed = json.loads(block)
|
| 941 |
+
print(f"Successfully parsed JSON: {parsed}")
|
| 942 |
+
return parsed
|
| 943 |
+
except json.JSONDecodeError as e:
|
| 944 |
+
print(f"JSON parse error: {e}")
|
| 945 |
continue
|
| 946 |
|
| 947 |
+
# Look for JSON-like patterns in the text using a more precise regex
|
| 948 |
+
# Match balanced braces
|
| 949 |
+
import re
|
| 950 |
|
| 951 |
+
# Try to find JSON objects with proper brace matching
|
| 952 |
+
brace_count = 0
|
| 953 |
+
start_pos = -1
|
| 954 |
+
|
| 955 |
+
for i, char in enumerate(text):
|
| 956 |
+
if char == '{':
|
| 957 |
+
if brace_count == 0:
|
| 958 |
+
start_pos = i
|
| 959 |
+
brace_count += 1
|
| 960 |
+
elif char == '}':
|
| 961 |
+
brace_count -= 1
|
| 962 |
+
if brace_count == 0 and start_pos >= 0:
|
| 963 |
+
# Found a complete JSON object
|
| 964 |
+
json_candidate = text[start_pos:i+1]
|
| 965 |
+
try:
|
| 966 |
+
parsed = json.loads(json_candidate)
|
| 967 |
+
print(f"Found valid JSON: {parsed}")
|
| 968 |
+
return parsed
|
| 969 |
+
except json.JSONDecodeError:
|
| 970 |
+
continue
|
| 971 |
|
| 972 |
# If we're here, we couldn't find a valid JSON object
|
| 973 |
print("Could not extract valid JSON from text")
|
|
|
|
| 1031 |
# Extract tool arguments
|
| 1032 |
action_input = state.get("action_input", {})
|
| 1033 |
print(f"Python code action_input: {action_input}")
|
| 1034 |
+
print(f"Action input type: {type(action_input)}")
|
| 1035 |
|
| 1036 |
# Try different ways to extract the code
|
| 1037 |
code = ""
|
| 1038 |
if isinstance(action_input, dict):
|
| 1039 |
code = action_input.get("code", "")
|
| 1040 |
+
print(f"Extracted code from dict: {repr(code[:100])}")
|
| 1041 |
elif isinstance(action_input, str):
|
| 1042 |
+
# If action_input is a string, it might be the code directly
|
| 1043 |
code = action_input
|
| 1044 |
+
print(f"Using string as code: {repr(code[:100])}")
|
| 1045 |
|
| 1046 |
+
# Additional debugging: check if we got a JSON string instead of parsed JSON
|
| 1047 |
+
if not code and isinstance(action_input, str):
|
| 1048 |
+
try:
|
| 1049 |
+
import json
|
| 1050 |
+
parsed = json.loads(action_input)
|
| 1051 |
+
if isinstance(parsed, dict) and "code" in parsed:
|
| 1052 |
+
code = parsed["code"]
|
| 1053 |
+
print(f"Parsed JSON and extracted code: {repr(code[:100])}")
|
| 1054 |
+
except json.JSONDecodeError:
|
| 1055 |
+
print("Failed to parse action_input as JSON")
|
| 1056 |
+
|
| 1057 |
+
print(f"Final code to execute: {repr(code[:200])}")
|
| 1058 |
+
|
| 1059 |
+
# Additional validation: check for unmatched braces
|
| 1060 |
+
open_braces = code.count('{')
|
| 1061 |
+
close_braces = code.count('}')
|
| 1062 |
+
if open_braces != close_braces:
|
| 1063 |
+
result = f"Error: Code contains unmatched braces. Found {open_braces} '{{' and {close_braces} '}}'. Please check your code syntax."
|
| 1064 |
else:
|
| 1065 |
# Call the code execution function
|
| 1066 |
result = run_python_code(code)
|