code_editor.py
1 #!/usr/bin/env python3 2 3 from langchain_community.llms import Ollama 4 import sys 5 import os 6 7 llm = Ollama(model="gpt-oss:120b", base_url="http://192.222.50.154:11434") 8 9 def edit_file(filepath, prompt): 10 if not os.path.exists(filepath): 11 print(f"File {filepath} not found") 12 return 13 14 with open(filepath, 'r') as f: 15 content = f.read() 16 17 full_prompt = f"""Edit this code file. Return ONLY the complete modified code, no explanations: 18 19 Current code: 20 {content} 21 22 Request: {prompt}""" 23 24 response = llm.invoke(full_prompt) 25 26 # Backup original 27 backup_path = f"{filepath}.backup" 28 with open(backup_path, 'w') as f: 29 f.write(content) 30 31 # Write new code 32 with open(filepath, 'w') as f: 33 f.write(response) 34 35 print(f"File {filepath} updated. Backup saved as {backup_path}") 36 37 def create_file(filepath, prompt): 38 full_prompt = f"Create a {filepath} file. Return ONLY the code, no explanations:\n\n{prompt}" 39 response = llm.invoke(full_prompt) 40 41 with open(filepath, 'w') as f: 42 f.write(response) 43 44 print(f"File {filepath} created") 45 46 if __name__ == "__main__": 47 if len(sys.argv) < 3: 48 print("Usage:") 49 print(" python code_editor.py edit <filepath> <prompt>") 50 print(" python code_editor.py create <filepath> <prompt>") 51 sys.exit(1) 52 53 action = sys.argv[1] 54 filepath = sys.argv[2] 55 prompt = " ".join(sys.argv[3:]) 56 57 if action == "edit": 58 edit_file(filepath, prompt) 59 elif action == "create": 60 create_file(filepath, prompt) 61 else: 62 print("Action must be 'edit' or 'create'")