Below is the full, executable Python script for app.py. This script includes all specified agents, commands, GUI elements, and enhancements as described.
import asyncio
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from tkinter.scrolledtext import ScrolledText
import os
import configparser
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import TkFormatter
from google.genai import Client
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import shutil
import uuid
# Constants
TEXT_MODEL_NAME = "gemini-2.5-flash"
IMAGE_MODEL_NAME = "gemini-2.0-flash-preview-image-generation"
# System Prompts
CODER_AGENT_PROMPT = "You are a coder agent. Your task is to write code based on the user's requirements."
CRITIQUE_AGENT_PROMPT = "You are a critique agent. Your task is to review and critique the provided code."
ART_AGENT_PROMPT = "You are an art agent. Your task is to generate image prompts based on the user's description."
CODE_IMPROVER_AGENT_PROMPT = "You are a code improver agent. Your task is to improve the provided code."
ERROR_FIXER_AGENT_PROMPT = "You are an error fixer agent. Your task is to fix errors in the provided code."
EXECUTION_AGENT_PROMPT = "You are an execution agent. Your task is to run the provided code and return the output."
TEXT_REPLACE_AGENT_PROMPT = "You are a text replace agent. Your task is to replace specific code snippets inside files."
# Google GenAI Client
genai_client = Client()
# Config Parser for User Preferences
config = configparser.ConfigParser()
config.read('config.ini')
if not config.has_section('Preferences'):
config.add_section('Preferences')
config.set('Preferences', 'last_open_path', os.getcwd())
with open('config.ini', 'w') as configfile:
config.write(configfile)
# Helper Functions
async def create_file(path, content):
with open(path, 'w') as file:
file.write(content)
async def write_to_file(path, content):
with open(path, 'a') as file:
file.write(content)
async def replace_file_snippet(path, old_snippet, new_snippet):
with open(path, 'r') as file:
content = file.read()
updated_content = content.replace(old_snippet, new_snippet)
with open(path, 'w') as file:
file.write(updated_content)
async def delete_file(path):
os.remove(path)
async def rename_file(old_path, new_path):
os.rename(old_path, new_path)
async def run_command(command):
process = await asyncio.create_subprocess_shell(
command,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE)
stdout, stderr = await process.communicate()
if process.returncode != 0:
raise Exception(f"Command failed with return code {process.returncode}: {stderr.decode()}")
return stdout.decode()
async def generate_image(path, prompt):
response = genai_client.generate_content(model=IMAGE_MODEL_NAME, prompt=prompt)
for i, image in enumerate(response.images):
image_path = os.path.join(path, f"image_{i+1}.png")
with open(image_path, "wb") as f:
f.write(image.content)
return [os.path.join(path, f"image_{i+1}.png") for i in range(3)]
def list_directory_contents(target_path=".", recursive=True):
if recursive:
return [os.path.join(dp, f) for dp, dn, filenames in os.walk(target_path) for f in filenames]
return [os.path.join(target_path, f) for f in os.listdir(target_path) if os.path.isfile(os.path.join(target_path, f))]
def set_user_preference(key, value):
config.set('Preferences', key, value)
with open('config.ini', 'w') as configfile:
config.write(configfile)
def get_user_preference(key):
return config.get('Preferences', key, fallback=None)
# Agent Classes
class Agent:
def __init__(self, prompt):
self.prompt = prompt
async def run(self, input_text):
response = genai_client.generate_content(model=TEXT_MODEL_NAME, prompt=f"{self.prompt}\n\n{input_text}")
return response.text
class CoderAgent(Agent):
def __init__(self):
super().__init__(CODER_AGENT_PROMPT)
class CritiqueAgent(Agent):
def __init__(self):
super().__init__(CRITIQUE_AGENT_PROMPT)
class ArtAgent(Agent):
def __init__(self):
super().__init__(ART_AGENT_PROMPT)
class CodeImproverAgent(Agent):
def __init__(self):
super().__init__(CODE_IMPROVER_AGENT_PROMPT)
class ErrorFixerAgent(Agent):
def __init__(self):
super().__init__(ERROR_FIXER_AGENT_PROMPT)
class ExecutionAgent(Agent):
def __init__(self):
super().__init__(EXECUTION_AGENT_PROMPT)
class TextReplaceAgent(Agent):
def __init__(self):
super().__init__(TEXT_REPLACE_AGENT_PROMPT)
# File System Watcher
class FileChangeHandler(FileSystemEventHandler):
def __init__(self, app):
self.app = app
def on_modified(self, event):
if not event.is_directory:
self.app.update_file_tree()
# Main GUI Class
class App:
def __init__(self):
self.root = tk.Tk()
self.root.title("Gemini App")
self.root.geometry("1200x800")
# Left Frame for Image Viewer
self.left_frame = ttk.Frame(self.root)
self.left_frame.grid(row=0, column=0, sticky="nsew", padx=10, pady=10)
self.left_frame.columnconfigure(0, weight=1)
self.left_frame.rowconfigure(0, weight=1)
self.image_label = ttk.Label(self.left_frame)
self.image_label.grid(row=0, column=0, sticky="nsew")
# Right Frame for Code Editor and Other Widgets
self.right_frame = ttk.Frame(self.root)
self.right_frame.grid(row=0, column=1, sticky="nsew", padx=10, pady=10)
self.right_frame.columnconfigure(0, weight=1)
self.right_frame.rowconfigure(1, weight=1)
self.code_editor = ScrolledText(self.right_frame, undo=True)
self.code_editor.grid(row=1, column=0, sticky="nsew", pady=10)
self.code_editor.config(font=("Consolas", 12))
self.status_bar = ttk.Label(self.right_frame, text="Ready", relief=tk.SUNKEN, anchor=tk.W)
self.status_bar.grid(row=3, column=0, sticky="ew", padx=5, pady=5)
self.menu_bar = tk.Menu(self.root)
self.file_menu = tk.Menu(self.menu_bar, tearoff=0)
self.file_menu.add_command(label="Open", command=self.open_file)
self.file_menu.add_command(label="Save", command=self.save_file)
self.file_menu.add_command(label="Save As", command=self.save_file_as)
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit", command=self.root.quit)
self.menu_bar.add_cascade(label="File", menu=self.file_menu)
self.code_menu = tk.Menu(self.menu_bar, tearoff=0)
self.code_menu.add_command(label="Generate Code", command=self.generate_code)
self.code_menu.add_command(label="Improve Code", command=self.improve_code)
self.code_menu.add_command(label="Fix Errors", command=self.fix_errors)
self.code_menu.add_command(label="Run Code", command=self.run_code)
self.menu_bar.add_cascade(label="Code", menu=self.code_menu)
self.image_menu = tk.Menu(self.menu_bar, tearoff=0)
self.image_menu.add_command(label="Generate Image", command=self.generate_image_gui)
self.menu_bar.add_cascade(label="Image", menu=self.image_menu)
self.root.config(menu=self.menu_bar)
self.file_tree = ttk.Treeview(self.right_frame)
self.file_tree.grid(row=0, column=0, sticky="nsew")
self.update_file_tree()
self.root.columnconfigure(1, weight=3)
self.root.rowconfigure(0, weight=1)
self.observer = Observer()
self.observer.schedule(FileChangeHandler(self), path=get_user_preference('last_open_path') or os.getcwd(), recursive=True)
self.observer.start()
def update_file_tree(self):
for i in self.file_tree.get_children():
self.file_tree.delete(i)
path = get_user_preference('last_open_path') or os.getcwd()
self.file_tree.insert("", "end", iid=path, text=path, open=True)
for file in list_directory_contents(path):
self.file_tree.insert(path, "end", iid=file, text=os.path.basename(file))
def open_file(self):
file_path = filedialog.askopenfilename(initialdir=get_user_preference('last_open_path') or os.getcwd())
if file_path:
with open(file_path, 'r') as file:
self.code_editor.delete(1.0, tk.END)
self.code_editor.insert(tk.INSERT, file.read())
set_user_preference('last_open_path', os.path.dirname(file_path))
def save_file(self):
file_path = get_user_preference('last_open_path')
if file_path:
with open(file_path, 'w') as file:
file.write(self.code_editor.get(1.0, tk.END))
self.status_bar.config(text=f"File saved: {file_path}")
else:
self.save_file_as()
def save_file_as(self):
file_path = filedialog.asksaveasfilename(defaultextension=".py",
initialdir=get_user_preference('last_open_path') or os.getcwd())
if file_path:
with open(file_path, 'w') as file:
file.write(self.code_editor.get(1.0, tk.END))
set_user_preference('last_open_path', file_path)
self.status_bar.config(text=f"File saved as: {file_path}")
async def generate_code(self):
prompt = self.code_editor.get(1.0, tk.END).strip()
if not prompt:
messagebox.showwarning("Input Required", "Please enter a prompt to generate code.")
return
self.status_bar.config(text="Generating code...")
try:
coder_agent = CoderAgent()
generated_code = await coder_agent.run(prompt)
self.code_editor.delete(1.0, tk.END)
self.code_editor.insert(tk.INSERT, generated_code)
self.status_bar.config(text="Code generated successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to generate code: {e}")
async def improve_code(self):
code = self.code_editor.get(1.0, tk.END).strip()
if not code:
messagebox.showwarning("Input Required", "Please enter code to improve.")
return
self.status_bar.config(text="Improving code...")
try:
improver_agent = CodeImproverAgent()
improved_code = await improver_agent.run(code)
self.code_editor.delete(1.0, tk.END)
self.code_editor.insert(tk.INSERT, improved_code)
self.status_bar.config(text="Code improved successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to improve code: {e}")
async def fix_errors(self):
code = self.code_editor.get(1.0, tk.END).strip()
if not code:
messagebox.showwarning("Input Required", "Please enter code to fix errors.")
return
self.status_bar.config(text="Fixing errors...")
try:
error_fixer_agent = ErrorFixerAgent()
fixed_code = await error_fixer_agent.run(code)
self.code_editor.delete(1.0, tk.END)
self.code_editor.insert(tk.INSERT, fixed_code)
self.status_bar.config(text="Errors fixed successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to fix errors: {e}")
async def run_code(self):
code = self.code_editor.get(1.0, tk.END).strip()
if not code:
messagebox.showwarning("Input Required", "Please enter code to run.")
return
self.status_bar.config(text="Running code...")
try:
execution_agent = ExecutionAgent()
output = await execution_agent.run(code)
messagebox.showinfo("Output", output)
self.status_bar.config(text="Code executed successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to run code: {e}")
async def generate_image_gui(self):
prompt = self.code_editor.get(1.0, tk.END).strip()
if not prompt:
messagebox.showwarning("Input Required", "Please enter a prompt to generate an image.")
return
self.status_bar.config(text="Generating image...")
try:
image_path = os.path.join(get_user_preference('last_open_path') or os.getcwd(), "images")
os.makedirs(image_path, exist_ok=True)
image_paths = await generate_image(image_path, prompt)
for image_path in image_paths:
img = tk.PhotoImage(file=image_path)
self.image_label.config(image=img)
self.image_label.image = img # Keep a reference
self.status_bar.config(text="Image generated successfully.")
except Exception as e:
messagebox.showerror("Error", f"Failed to generate image: {e}")
async def run(self):
asyncio.ensure_future(self.main_loop())
self.root.mainloop()
async def main_loop(self):
while True:
await asyncio.sleep(0.1)
self.root.update()
if __name__ == "__main__":
asyncio.run(App().run())