Describe what you want in an intent file; the compiler uses Claude to write the code.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-compiler.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-compiler.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-compiler.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add context files - the header files of intent compilation 114b162 1 year, 1 month ago History
compiler.py · 7.7 KB · 239 lines
1#!/usr/bin/env python3
2"""
3AI Compiler - Proof of Concept
4
5The compiler that understands intent.
6Compiles natural language problem descriptions to executable code.
7
8Usage:
9 python ai_compiler.py compile intent/hello_world.intent.md
10 python ai_compiler.py run hello_world
11"""
12
13import os
14import sys
15import json
16import subprocess
17from pathlib import Path
18from anthropic import Anthropic
19
20
21class AICompiler:
22 """
23 The intelligent compiler.
24
25 Traditional compiler: Checks syntax mechanically
26 AI Compiler: Understands intent, generates optimal implementation
27 """
28
29 def __init__(self, api_key=None):
30 self.api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
31 if not self.api_key:
32 raise ValueError(
33 "ANTHROPIC_API_KEY not found. Set it as environment variable:\n"
34 "export ANTHROPIC_API_KEY='your-api-key'"
35 )
36 self.client = Anthropic(api_key=self.api_key)
37 self.model = "claude-sonnet-4-5-20250929"
38
39 # Directories
40 self.intent_dir = Path("intent")
41 self.output_dir = Path("compiled")
42 self.output_dir.mkdir(exist_ok=True)
43
44 def compile(self, intent_file: str):
45 """
46 Compile intent description to executable code.
47
48 This is the core innovation:
49 - Read intent (problem description)
50 - Use AI to generate optimal implementation
51 - Validate and save
52
53 Like GCC, but understands natural language.
54 """
55 intent_path = Path(intent_file)
56
57 if not intent_path.exists():
58 print(f"Error: Intent file not found: {intent_path}")
59 return False
60
61 print(f"[AI Compiler] Reading intent: {intent_path}")
62 intent_content = intent_path.read_text()
63
64 print(f"[AI Compiler] Understanding problem description...")
65
66 # This is the "compilation" step
67 # Instead of checking syntax, we're understanding intent
68 prompt = f"""You are an AI compiler. Your job is to compile natural language problem descriptions into executable Python code.
69
70The user has provided this problem description:
71
72{intent_content}
73
74Generate a complete, working Python program that solves this problem.
75
76Requirements:
771. The code should be clean, well-structured, and production-ready
782. Include error handling for edge cases mentioned in the intent
793. Follow Python best practices
804. Make it user-friendly
815. The code should be self-contained (no external dependencies beyond standard library)
82
83Generate ONLY the Python code, no explanations. Start with #!/usr/bin/env python3"""
84
85 try:
86 response = self.client.messages.create(
87 model=self.model,
88 max_tokens=4000,
89 messages=[{
90 "role": "user",
91 "content": prompt
92 }]
93 )
94
95 generated_code = response.content[0].text
96
97 # Extract just the code if there's any wrapper text
98 if "```python" in generated_code:
99 generated_code = generated_code.split("```python")[1].split("```")[0].strip()
100 elif "```" in generated_code:
101 generated_code = generated_code.split("```")[1].split("```")[0].strip()
102
103 # Ensure shebang
104 if not generated_code.startswith("#!/usr/bin/env python3"):
105 generated_code = "#!/usr/bin/env python3\n" + generated_code
106
107 # Save compiled output
108 output_name = intent_path.stem # e.g., "hello_world"
109 output_path = self.output_dir / f"{output_name}.py"
110
111 print(f"[AI Compiler] Generating optimal implementation...")
112 output_path.write_text(generated_code)
113
114 # Make executable
115 os.chmod(output_path, 0o755)
116
117 print(f"[AI Compiler] ✓ Compilation successful!")
118 print(f"[AI Compiler] Output: {output_path}")
119
120 # Save metadata
121 metadata = {
122 "intent_file": str(intent_path),
123 "output_file": str(output_path),
124 "model": self.model,
125 "compiled_at": self._get_timestamp()
126 }
127
128 metadata_path = self.output_dir / f"{output_name}.meta.json"
129 metadata_path.write_text(json.dumps(metadata, indent=2))
130
131 print(f"[AI Compiler] Metadata: {metadata_path}")
132 print()
133 print("To run:")
134 print(f" python ai_compiler.py run {output_name}")
135 print(f" # or directly:")
136 print(f" python {output_path}")
137
138 return True
139
140 except Exception as e:
141 print(f"[AI Compiler] ✗ Compilation failed: {e}")
142 return False
143
144 def run(self, program_name: str):
145 """Execute compiled program."""
146 output_path = self.output_dir / f"{program_name}.py"
147
148 if not output_path.exists():
149 print(f"[AI Compiler] Error: Program not found: {output_path}")
150 print(f"[AI Compiler] Did you compile it first?")
151 print(f" python ai_compiler.py compile intent/{program_name}.intent.md")
152 return False
153
154 print(f"[AI Compiler] Executing: {output_path}")
155 print("-" * 60)
156
157 # Execute the compiled program
158 result = subprocess.run([sys.executable, str(output_path)])
159
160 print("-" * 60)
161 print(f"[AI Compiler] Program exited with code: {result.returncode}")
162
163 return result.returncode == 0
164
165 def list_programs(self):
166 """List all compiled programs."""
167 compiled_files = list(self.output_dir.glob("*.py"))
168
169 if not compiled_files:
170 print("[AI Compiler] No compiled programs found.")
171 print("[AI Compiler] Compile an intent file first:")
172 print(" python ai_compiler.py compile intent/hello_world.intent.md")
173 return
174
175 print("[AI Compiler] Compiled programs:")
176 for f in compiled_files:
177 # Read metadata if available
178 meta_path = f.with_suffix(".meta.json")
179 if meta_path.exists():
180 meta = json.loads(meta_path.read_text())
181 print(f" {f.stem:20} (from {Path(meta['intent_file']).name})")
182 else:
183 print(f" {f.stem}")
184
185 def _get_timestamp(self):
186 """Get current timestamp."""
187 from datetime import datetime
188 return datetime.now().isoformat()
189
190
191def main():
192 """Main entry point."""
193 if len(sys.argv) < 2:
194 print("AI Compiler - The compiler that understands intent")
195 print()
196 print("Usage:")
197 print(" python ai_compiler.py compile <intent_file>")
198 print(" python ai_compiler.py run <program_name>")
199 print(" python ai_compiler.py list")
200 print()
201 print("Example:")
202 print(" python ai_compiler.py compile intent/hello_world.intent.md")
203 print(" python ai_compiler.py run hello_world")
204 print()
205 print("Environment:")
206 print(" ANTHROPIC_API_KEY must be set")
207 return 1
208
209 command = sys.argv[1]
210 compiler = AICompiler()
211
212 if command == "compile":
213 if len(sys.argv) < 3:
214 print("Usage: python ai_compiler.py compile <intent_file>")
215 return 1
216 intent_file = sys.argv[2]
217 success = compiler.compile(intent_file)
218 return 0 if success else 1
219
220 elif command == "run":
221 if len(sys.argv) < 3:
222 print("Usage: python ai_compiler.py run <program_name>")
223 return 1
224 program_name = sys.argv[2]
225 success = compiler.run(program_name)
226 return 0 if success else 1
227
228 elif command == "list":
229 compiler.list_programs()
230 return 0
231
232 else:
233 print(f"Unknown command: {command}")
234 print("Valid commands: compile, run, list")
235 return 1
236
237
238if __name__ == "__main__":
239 sys.exit(main())