From 92f9b933533e68b1ae7637f1bc1e2caac983268a Mon Sep 17 00:00:00 2001 From: martin legrand Date: Fri, 11 Apr 2025 12:44:55 +0200 Subject: [PATCH] fix : language_bash_attempt error --- prompts/base/planner_agent.txt | 3 +- sources/agents/planner_agent.py | 9 +- sources/router.py | 4 + sources/tools/BashInterpreter.py | 2 +- sources/tools/JavaInterpreter.py | 184 +++++++++++++++++++++++++++++++ 5 files changed, 194 insertions(+), 8 deletions(-) create mode 100644 sources/tools/JavaInterpreter.py diff --git a/prompts/base/planner_agent.txt b/prompts/base/planner_agent.txt index b32e6d7..33366cf 100644 --- a/prompts/base/planner_agent.txt +++ b/prompts/base/planner_agent.txt @@ -76,4 +76,5 @@ Rules: - Tell agent to execute without question. - Only use web agent for finding necessary informations. - If a task might require user email (eg: api services), do not write plan instead ask for user email. -- Do not search for tutorial. \ No newline at end of file +- Do not search for tutorial. +- Make sure json is within ```json tag \ No newline at end of file diff --git a/sources/agents/planner_agent.py b/sources/agents/planner_agent.py index 82731aa..0767e01 100644 --- a/sources/agents/planner_agent.py +++ b/sources/agents/planner_agent.py @@ -80,9 +80,10 @@ class PlannerAgent(Agent): """ return prompt - def show_plan(self, json_plan: dict) -> None: - agents_tasks = self.parse_agent_tasks(json_plan) + def show_plan(self, answer: dict) -> None: + agents_tasks = self.parse_agent_tasks(answer) if agents_tasks == (None, None): + pretty_print(answer, color="warning") pretty_print("Failed to make a plan. This can happen with (too) small LLM. Clarify your request and insist on it making a plan.", color="failure") return pretty_print("\nā–‚ā–˜ P L A N ā–ā–‚", color="status") @@ -97,10 +98,6 @@ class PlannerAgent(Agent): animate_thinking("Thinking...", color="status") self.memory.push('user', prompt) answer, _ = self.llm_request() - for line in answer.split('\n'): - if "```json" in line: - break - pretty_print(line, color="output") self.show_plan(answer) ok_str = input("Is the plan ok? (y/n): ") if ok_str == 'y': diff --git a/sources/router.py b/sources/router.py index 25e9383..56a2890 100644 --- a/sources/router.py +++ b/sources/router.py @@ -100,6 +100,10 @@ class AgentRouter: ("could you check if the presentation.pdf file exists in my downloads?", "LOW"), ("search my drive for a file called vacation_photos_2023.jpg.", "LOW"), ("help me organize my desktop files into folders by type.", "LOW"), + ("make a blackjack in golang", "LOW"), + ("write a python script to ping a website", "LOW"), + ("write a simple Java program to print 'Hello World'", "LOW"), + ("write a Java program to calculate the area of a circle", "LOW"), ("write a Python function to sort a list of dictionaries by key", "LOW"), ("can you search for startup in tokyo?", "LOW"), ("find the latest updates on quantum computing on the web", "LOW"), diff --git a/sources/tools/BashInterpreter.py b/sources/tools/BashInterpreter.py index 584b017..2bc2c32 100644 --- a/sources/tools/BashInterpreter.py +++ b/sources/tools/BashInterpreter.py @@ -44,7 +44,7 @@ class BashInterpreter(Tools): command = command.replace('\n', '') if self.safe_mode and is_unsafe(commands): return "Unsafe command detected, execution aborted." - if self.language_bash_attempt(command) and allow_language_exec_bash == False: + if self.language_bash_attempt(command) and self.allow_language_exec_bash == False: continue try: process = subprocess.Popen( diff --git a/sources/tools/JavaInterpreter.py b/sources/tools/JavaInterpreter.py new file mode 100644 index 0000000..a6bbc0a --- /dev/null +++ b/sources/tools/JavaInterpreter.py @@ -0,0 +1,184 @@ +import subprocess +import os +import tempfile +import re + +if __name__ == "__main__": + from tools import Tools +else: + from sources.tools.tools import Tools + +class JavaInterpreter(Tools): + """ + This class is a tool to allow execution of Java code. + """ + def __init__(self): + super().__init__() + self.tag = "java" + + def execute(self, codes: str, safety=False) -> str: + """ + Execute Java code by compiling and running it. + """ + output = "" + code = '\n'.join(codes) if isinstance(codes, list) else codes + + if safety and input("Execute code? y/n ") != "y": + return "Code rejected by user." + + with tempfile.TemporaryDirectory() as tmpdirname: + source_file = os.path.join(tmpdirname, "Main.java") + class_dir = tmpdirname + with open(source_file, 'w') as f: + f.write(code) + + try: + compile_command = ["javac", "-d", class_dir, source_file] + compile_result = subprocess.run( + compile_command, + capture_output=True, + text=True, + timeout=10 + ) + + if compile_result.returncode != 0: + return f"Compilation failed: {compile_result.stderr}" + + run_command = ["java", "-cp", class_dir, "Main"] + run_result = subprocess.run( + run_command, + capture_output=True, + text=True, + timeout=10 + ) + + if run_result.returncode != 0: + return f"Execution failed: {run_result.stderr}" + output = run_result.stdout + + except subprocess.TimeoutExpired as e: + return f"Execution timed out: {str(e)}" + except FileNotFoundError: + return "Error: 'java' or 'javac' not found. Ensure Java is installed and in PATH." + except Exception as e: + return f"Code execution failed: {str(e)}" + + return output + + def interpreter_feedback(self, output: str) -> str: + """ + Provide feedback based on the output of the code execution. + """ + if self.execution_failure_check(output): + feedback = f"[failure] Error in execution:\n{output}" + else: + feedback = "[success] Execution success, code output:\n" + output + return feedback + + def execution_failure_check(self, feedback: str) -> bool: + """ + Check if the code execution failed. + """ + error_patterns = [ + r"error", + r"failed", + r"exception", + r"invalid", + r"syntax", + r"cannot", + r"stack trace", + r"unresolved", + r"not found" + ] + combined_pattern = "|".join(error_patterns) + if re.search(combined_pattern, feedback, re.IGNORECASE): + return True + return False + +if __name__ == "__main__": + codes = [ +""" +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +public class Main extends JPanel { + private double[][] vertices = { + {-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}, // Back face + {-1, -1, 1}, {1, -1, 1}, {1, 1, 1}, {-1, 1, 1} // Front face + }; + private int[][] edges = { + {0, 1}, {1, 2}, {2, 3}, {3, 0}, // Back face + {4, 5}, {5, 6}, {6, 7}, {7, 4}, // Front face + {0, 4}, {1, 5}, {2, 6}, {3, 7} // Connecting edges + }; + private double angleX = 0, angleY = 0; + private final double scale = 100; + private final double distance = 5; + + public Main() { + Timer timer = new Timer(50, new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + angleX += 0.03; + angleY += 0.05; + repaint(); + } + }); + timer.start(); + } + + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2d = (Graphics2D) g; + g2d.setColor(Color.BLACK); + g2d.fillRect(0, 0, getWidth(), getHeight()); + g2d.setColor(Color.WHITE); + + double[][] projected = new double[vertices.length][2]; + for (int i = 0; i < vertices.length; i++) { + double x = vertices[i][0]; + double y = vertices[i][1]; + double z = vertices[i][2]; + + // Rotate around X-axis + double y1 = y * Math.cos(angleX) - z * Math.sin(angleX); + double z1 = y * Math.sin(angleX) + z * Math.cos(angleX); + + // Rotate around Y-axis + double x1 = x * Math.cos(angleY) + z1 * Math.sin(angleY); + double z2 = -x * Math.sin(angleY) + z1 * Math.cos(angleY); + + // Perspective projection + double factor = distance / (distance + z2); + double px = x1 * factor * scale; + double py = y1 * factor * scale; + + projected[i][0] = px + getWidth() / 2; + projected[i][1] = py + getHeight() / 2; + } + + // Draw edges + for (int[] edge : edges) { + int x1 = (int) projected[edge[0]][0]; + int y1 = (int) projected[edge[0]][1]; + int x2 = (int) projected[edge[1]][0]; + int y2 = (int) projected[edge[1]][1]; + g2d.drawLine(x1, y1, x2, y2); + } + } + + public static void main(String[] args) { + JFrame frame = new JFrame("Rotating 3D Cube"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(400, 400); + frame.add(new Main()); + frame.setVisible(true); + } +} +""" + ] + j = JavaInterpreter() + print(j.execute(codes)) \ No newline at end of file