-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
91 lines (73 loc) · 2.89 KB
/
app.py
File metadata and controls
91 lines (73 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import os
import gradio as gr
from dotenv import load_dotenv
from openai import OpenAI
import shutil
import subprocess
load_dotenv()
client = OpenAI()
SYSTEM_PROMPT = """
You are a helpful assistant that converts natural language instructions into terminal commands.
Return ONLY the command itself without any explanations, backticks, or formatting.
Target System: Linux/Unix (Bash).
For dangerous commands (rm -rf, del, shutdown, format, dd, mkfs, etc.), prefix the command with ⚠️ warning icon.
Example: ⚠️ rm -rf /tmp/*
If the user asks a question that can be answered with a terminal command, provide the command.
Only reject requests that cannot be solved with terminal commands (jokes, stories, personal advice, etc.).
If the request cannot be solved with a terminal command, respond with: "Error: Not a valid terminal command request"
"""
def is_valid_command(command):
# Remove warning icon if present
clean_cmd = command.replace("⚠️", "").strip()
# Get the base command (first word)
base_cmd = clean_cmd.split()[0] if clean_cmd else ""
# Check if command exists in system
return shutil.which(base_cmd) is not None or base_cmd in ['cd', 'echo', 'export', 'alias', 'source']
def run_command_in_docker(command):
# Remove warning icon
clean_cmd = command.replace("⚠️", "").strip()
try:
result = subprocess.run(
["docker", "run", "--rm", "ubuntu:latest", "bash", "-c", clean_cmd],
capture_output=True,
text=True,
timeout=10
)
if result.returncode == 0:
return "✓ Command is valid"
else:
return f"Error: Command failed in Docker"
except FileNotFoundError:
return "⚠️ Docker not available - command not tested"
except subprocess.TimeoutExpired:
return "Error: Command timeout"
except Exception as e:
return f"Error: {str(e)}"
def generate_command(user_input):
try:
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_input}
],
temperature=0
)
command = response.choices[0].message.content.strip()
# Validate command
if not is_valid_command(command):
return f"Error: Invalid or unknown command generated"
# Test command in Docker
validation_result = run_command_in_docker(command)
return f"{command}\n\n{validation_result}"
except Exception as e:
return f"Error: {str(e)}"
# ממשק Gradio
demo = gr.Interface(
fn=generate_command,
inputs=gr.Textbox(label="מה תרצה לבצע?"),
outputs=gr.Code(label="פקודת CLI"),
title="Natural Language to CLI Agent"
)
if __name__ == "__main__":
demo.launch()