SwarajPatil/Python_code_fixer
1
1from smolagents import CodeAgent, tool, HfApiModel, agents2import subprocess3import yaml4from Gradio_UI import GradioUI5 6@tool7def check_syntax(code: str) -> str:8 """9 Checks for syntax errors in Python code.10 11 Args:12 code: The Python code to analyze.13 """14 try:15 compile(code, "<string>", "exec")16 return "No syntax errors found."17 except SyntaxError as e:18 return f"Syntax Error: {e}"19 20@tool21def run_code(code: str) -> str:22 """Executes Python code and returns output or errors.23 24 Args:25 code: The Python code to analyze.26 """27 try:28 result = subprocess.run(["python", "-c", code], capture_output=True, text=True, timeout=5)29 return result.stdout if result.stdout else result.stderr30 except Exception as e:31 return f" Execution Error: {str(e)}"32 33@tool34def explain_error(error_message: str) -> str:35 """Uses AI to explain Python error messages and suggest fixes.36 37 Args:38 error_message: Erron massage to explain and suggest a fix.39 """40 return agent.llm.complete(41 prompt=f"Explain this Python error and suggest a fix:\n{error_message}"42 )43 44with open("prompts.yaml", 'r') as stream:45 prompt_templates = yaml.safe_load(stream)46 47agent= CodeAgent(tools=[check_syntax, run_code, explain_error], model=HfApiModel())48 49GradioUI(agent).launch()