|
| 1 | +import os |
| 2 | +import json |
| 3 | +from typing import List, Optional, Dict, Any |
| 4 | +from enum import Enum |
| 5 | + |
| 6 | + |
| 7 | +class APIProvider(Enum): |
| 8 | + CLAUDE = "claude" |
| 9 | + OPENAI = "openai" |
| 10 | + |
| 11 | + |
| 12 | +class CommandInterpreter: |
| 13 | + def __init__( |
| 14 | + self, |
| 15 | + api_key: str, |
| 16 | + provider: str = "openai", |
| 17 | + model: Optional[str] = None |
| 18 | + ): |
| 19 | + self.api_key = api_key |
| 20 | + self.provider = APIProvider(provider.lower()) |
| 21 | + |
| 22 | + if model: |
| 23 | + self.model = model |
| 24 | + else: |
| 25 | + self.model = "gpt-4" if self.provider == APIProvider.OPENAI else "claude-3-5-sonnet-20241022" |
| 26 | + |
| 27 | + self._initialize_client() |
| 28 | + |
| 29 | + def _initialize_client(self): |
| 30 | + if self.provider == APIProvider.OPENAI: |
| 31 | + try: |
| 32 | + from openai import OpenAI |
| 33 | + self.client = OpenAI(api_key=self.api_key) |
| 34 | + except ImportError: |
| 35 | + raise ImportError("OpenAI package not installed. Run: pip install openai") |
| 36 | + elif self.provider == APIProvider.CLAUDE: |
| 37 | + try: |
| 38 | + from anthropic import Anthropic |
| 39 | + self.client = Anthropic(api_key=self.api_key) |
| 40 | + except ImportError: |
| 41 | + raise ImportError("Anthropic package not installed. Run: pip install anthropic") |
| 42 | + |
| 43 | + def _get_system_prompt(self) -> str: |
| 44 | + return """You are a Linux system command expert. Convert natural language requests into safe, validated bash commands. |
| 45 | +
|
| 46 | +Rules: |
| 47 | +1. Return ONLY a JSON array of commands |
| 48 | +2. Each command must be a safe, executable bash command |
| 49 | +3. Commands should be atomic and sequential |
| 50 | +4. Avoid destructive operations without explicit user confirmation |
| 51 | +5. Use package managers appropriate for Debian/Ubuntu systems (apt) |
| 52 | +6. Include necessary privilege escalation (sudo) when required |
| 53 | +7. Validate command syntax before returning |
| 54 | +
|
| 55 | +Format: |
| 56 | +{"commands": ["command1", "command2", ...]} |
| 57 | +
|
| 58 | +Example request: "install docker with nvidia support" |
| 59 | +Example response: {"commands": ["sudo apt update", "sudo apt install -y docker.io", "sudo apt install -y nvidia-docker2", "sudo systemctl restart docker"]}""" |
| 60 | + |
| 61 | + def _call_openai(self, user_input: str) -> List[str]: |
| 62 | + try: |
| 63 | + response = self.client.chat.completions.create( |
| 64 | + model=self.model, |
| 65 | + messages=[ |
| 66 | + {"role": "system", "content": self._get_system_prompt()}, |
| 67 | + {"role": "user", "content": user_input} |
| 68 | + ], |
| 69 | + temperature=0.3, |
| 70 | + max_tokens=1000 |
| 71 | + ) |
| 72 | + |
| 73 | + content = response.choices[0].message.content.strip() |
| 74 | + return self._parse_commands(content) |
| 75 | + except Exception as e: |
| 76 | + raise RuntimeError(f"OpenAI API call failed: {str(e)}") |
| 77 | + |
| 78 | + def _call_claude(self, user_input: str) -> List[str]: |
| 79 | + try: |
| 80 | + response = self.client.messages.create( |
| 81 | + model=self.model, |
| 82 | + max_tokens=1000, |
| 83 | + temperature=0.3, |
| 84 | + system=self._get_system_prompt(), |
| 85 | + messages=[ |
| 86 | + {"role": "user", "content": user_input} |
| 87 | + ] |
| 88 | + ) |
| 89 | + |
| 90 | + content = response.content[0].text.strip() |
| 91 | + return self._parse_commands(content) |
| 92 | + except Exception as e: |
| 93 | + raise RuntimeError(f"Claude API call failed: {str(e)}") |
| 94 | + |
| 95 | + def _parse_commands(self, content: str) -> List[str]: |
| 96 | + try: |
| 97 | + if content.startswith("```json"): |
| 98 | + content = content.split("```json")[1].split("```")[0].strip() |
| 99 | + elif content.startswith("```"): |
| 100 | + content = content.split("```")[1].split("```")[0].strip() |
| 101 | + |
| 102 | + data = json.loads(content) |
| 103 | + commands = data.get("commands", []) |
| 104 | + |
| 105 | + if not isinstance(commands, list): |
| 106 | + raise ValueError("Commands must be a list") |
| 107 | + |
| 108 | + return [cmd for cmd in commands if cmd and isinstance(cmd, str)] |
| 109 | + except (json.JSONDecodeError, ValueError) as e: |
| 110 | + raise ValueError(f"Failed to parse LLM response: {str(e)}") |
| 111 | + |
| 112 | + def _validate_commands(self, commands: List[str]) -> List[str]: |
| 113 | + dangerous_patterns = [ |
| 114 | + "rm -rf /", |
| 115 | + "dd if=", |
| 116 | + "mkfs.", |
| 117 | + "> /dev/sda", |
| 118 | + "fork bomb", |
| 119 | + ":(){ :|:& };:", |
| 120 | + ] |
| 121 | + |
| 122 | + validated = [] |
| 123 | + for cmd in commands: |
| 124 | + cmd_lower = cmd.lower() |
| 125 | + if any(pattern in cmd_lower for pattern in dangerous_patterns): |
| 126 | + continue |
| 127 | + validated.append(cmd) |
| 128 | + |
| 129 | + return validated |
| 130 | + |
| 131 | + def parse(self, user_input: str, validate: bool = True) -> List[str]: |
| 132 | + if not user_input or not user_input.strip(): |
| 133 | + raise ValueError("User input cannot be empty") |
| 134 | + |
| 135 | + if self.provider == APIProvider.OPENAI: |
| 136 | + commands = self._call_openai(user_input) |
| 137 | + elif self.provider == APIProvider.CLAUDE: |
| 138 | + commands = self._call_claude(user_input) |
| 139 | + else: |
| 140 | + raise ValueError(f"Unsupported provider: {self.provider}") |
| 141 | + |
| 142 | + if validate: |
| 143 | + commands = self._validate_commands(commands) |
| 144 | + |
| 145 | + return commands |
| 146 | + |
| 147 | + def parse_with_context( |
| 148 | + self, |
| 149 | + user_input: str, |
| 150 | + system_info: Optional[Dict[str, Any]] = None, |
| 151 | + validate: bool = True |
| 152 | + ) -> List[str]: |
| 153 | + context = "" |
| 154 | + if system_info: |
| 155 | + context = f"\n\nSystem context: {json.dumps(system_info)}" |
| 156 | + |
| 157 | + enriched_input = user_input + context |
| 158 | + return self.parse(enriched_input, validate=validate) |
0 commit comments