Lasdw commited on
Commit
28e126d
·
1 Parent(s): 70be945

Fix issue with python tool syntax errors

Browse files
Files changed (1) hide show
  1. agent.py +26 -44
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
- return f"Error: Code contains potentially unsafe import: {line}"
71
 
72
  try:
73
  # Capture stdout to get print output
@@ -132,33 +132,20 @@ def run_python_code(code: str):
132
  # Capture stdout
133
  captured_output = io.StringIO()
134
 
135
- # Execute the code with timeout simulation (not perfect but better than nothing)
136
  with redirect_stdout(captured_output):
137
- # Split code into lines and execute
138
  lines = code.strip().split('\n')
139
- last_line = None
140
-
141
- for i, line in enumerate(lines):
142
- line = line.strip()
143
- if not line or line.startswith('#'):
144
- continue
145
-
146
- # Check if this is the last meaningful line
147
- is_last = i == len(lines) - 1
148
-
149
- # Execute the line
150
- if is_last and not any(keyword in line for keyword in ['print', 'for', 'while', 'if', 'def', 'class', 'try', 'with']):
151
- # If it's the last line and looks like an expression, store it
152
- try:
153
- # Try to evaluate as expression first
154
- result = eval(line, restricted_globals, local_scope)
155
- local_scope['_last_result'] = result
156
- print(f"Result: {result}")
157
- except:
158
- # If that fails, execute as statement
159
- exec(line, restricted_globals, local_scope)
160
- else:
161
- exec(line, restricted_globals, local_scope)
162
 
163
  # Get the captured output
164
  output = captured_output.getvalue()
@@ -166,11 +153,19 @@ def run_python_code(code: str):
166
  if output.strip():
167
  return output.strip()
168
  else:
169
- # If no output but we have a last result, show it
170
- if '_last_result' in local_scope:
171
- return f"Result: {local_scope['_last_result']}"
172
- else:
173
- return "Code executed successfully with no output."
 
 
 
 
 
 
 
 
174
 
175
  except SyntaxError as e:
176
  return f"Syntax Error: {str(e)}"
@@ -1043,19 +1038,6 @@ def python_code_node(state: AgentState) -> Dict[str, Any]:
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('}')
 
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
 
132
  # Capture stdout
133
  captured_output = io.StringIO()
134
 
135
+ # Execute the entire code block at once
136
  with redirect_stdout(captured_output):
137
+ # Try to evaluate as expression first (for simple expressions)
138
  lines = code.strip().split('\n')
139
+ if len(lines) == 1 and not any(keyword in code for keyword in ['=', 'import', 'from', 'def', 'class', 'if', 'for', 'while', 'try', 'with']):
140
+ try:
141
+ result = eval(code, restricted_globals, local_scope)
142
+ print(f"Result: {result}")
143
+ except:
144
+ # If eval fails, use exec
145
+ exec(code, restricted_globals, local_scope)
146
+ else:
147
+ # For multi-line code, execute the entire block
148
+ exec(code, restricted_globals, local_scope)
 
 
 
 
 
 
 
 
 
 
 
 
 
149
 
150
  # Get the captured output
151
  output = captured_output.getvalue()
 
153
  if output.strip():
154
  return output.strip()
155
  else:
156
+ # If no output, check if there's a result from the last expression
157
+ lines = code.strip().split('\n')
158
+ last_line = lines[-1].strip() if lines else ""
159
+
160
+ # If the last line looks like an expression, try to evaluate it
161
+ if last_line and not any(keyword in last_line for keyword in ['=', 'import', 'from', 'def', 'class', 'if', 'for', 'while', 'try', 'with', 'print']):
162
+ try:
163
+ result = eval(last_line, restricted_globals, local_scope)
164
+ return f"Result: {result}"
165
+ except:
166
+ pass
167
+
168
+ return "Code executed successfully with no output."
169
 
170
  except SyntaxError as e:
171
  return f"Syntax Error: {str(e)}"
 
1038
  code = action_input
1039
  print(f"Using string as code: {repr(code[:100])}")
1040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1041
  # Additional validation: check for unmatched braces
1042
  open_braces = code.count('{')
1043
  close_braces = code.count('}')