-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
561 lines (455 loc) · 15.2 KB
/
agent.py
File metadata and controls
561 lines (455 loc) · 15.2 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
"""
Multi-Language Code Generator Agent
Supports: Python, JavaScript, Java, C++, C, SQL
Uses Self-Consistency Prompting for high-quality code generation
"""
import os
import logging
from typing import Dict, Any, List
from datetime import datetime
from llama_cpp import Llama
# ============================================================================
# LOGGING
# ============================================================================
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('agent.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
# ============================================================================
# CONFIGURATION
# ============================================================================
MODEL_PATH = "./models/qwen2.5-coder-7b-instruct-q5_k_m.gguf"
MODEL_PARAMS = {
"model_path": MODEL_PATH,
"n_ctx": 4096,
"n_threads": 8,
"n_gpu_layers": 0,
"verbose": False
}
NUM_SAMPLES = 9
TEMPERATURES = [0.1, 0.2, 0.3, 0.4, 0.5, 0.5, 0.7, 0.9, 0.9]
# ============================================================================
# LANGUAGE-SPECIFIC CONFIGURATIONS
# ============================================================================
LANGUAGE_CONFIGS = {
"python": {
"name": "Python",
"extension": ".py",
"comment": "#",
"syntax_check": "import ast; ast.parse(code)"
},
"javascript": {
"name": "JavaScript",
"extension": ".js",
"comment": "//",
"syntax_check": "basic"
},
"java": {
"name": "Java",
"extension": ".java",
"comment": "//",
"syntax_check": "basic"
},
"cpp": {
"name": "C++",
"extension": ".cpp",
"comment": "//",
"syntax_check": "basic"
},
"c": {
"name": "C",
"extension": ".c",
"comment": "//",
"syntax_check": "basic"
},
"sql": {
"name": "SQL",
"extension": ".sql",
"comment": "--",
"syntax_check": "basic"
}
}
# ============================================================================
# SYSTEM PROMPTS FOR EACH LANGUAGE
# ============================================================================
SYSTEM_PROMPTS = {
"python": """You are an expert Python programmer. Generate complete, working Python code.
STRICT RULES:
- Output ONLY executable Python code
- NO explanations, NO markdown (```), NO text
- Start with 'def', 'class', or 'import'
- Write complete functions with proper logic
- NO placeholders like "TODO" or "pass"
- Use type hints when possible
EXAMPLES:
Prompt: count vowels in string
Output:
def count_vowels(text: str) -> int:
vowels = "aeiouAEIOU"
return sum(1 for c in text if c in vowels)
Prompt: check if number is prime
Output:
def is_prime(n: int) -> bool:
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(n**0.5) + 1, 2):
if n % i == 0:
return False
return True""",
"javascript": """You are an expert JavaScript programmer. Generate complete, working JavaScript code.
STRICT RULES:
- Output ONLY executable JavaScript code
- NO explanations, NO markdown, NO text
- Start with 'function', 'const', 'class', or 'var'
- Write complete functions with proper logic
- NO placeholders or incomplete code
- Use modern ES6+ syntax
EXAMPLES:
Prompt: count vowels in string
Output:
function countVowels(text) {
const vowels = "aeiouAEIOU";
return [...text].filter(c => vowels.includes(c)).length;
}
Prompt: check if number is prime
Output:
function isPrime(n) {
if (n < 2) return false;
if (n === 2) return true;
if (n % 2 === 0) return false;
for (let i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i === 0) return false;
}
return true;
}""",
"java": """You are an expert Java programmer. Generate complete, working Java code.
STRICT RULES:
- Output ONLY executable Java code
- NO explanations, NO markdown, NO text
- Include proper class structure
- Follow Java naming conventions
- NO placeholders or incomplete code
EXAMPLES:
Prompt: count vowels in string
Output:
public class VowelCounter {
public static int countVowels(String text) {
int count = 0;
String vowels = "aeiouAEIOU";
for (char c : text.toCharArray()) {
if (vowels.indexOf(c) != -1) count++;
}
return count;
}
}
Prompt: check if number is prime
Output:
public class PrimeChecker {
public static boolean isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i <= Math.sqrt(n); i += 2) {
if (n % i == 0) return false;
}
return true;
}
}""",
"cpp": """You are an expert C++ programmer. Generate complete, working C++ code.
STRICT RULES:
- Output ONLY executable C++ code
- NO explanations, NO markdown, NO text
- Include necessary headers (#include)
- Write complete functions with proper logic
- NO placeholders or incomplete code
EXAMPLES:
Prompt: count vowels in string
Output:
#include <string>
#include <cctype>
using namespace std;
int countVowels(const string& text) {
int count = 0;
string vowels = "aeiouAEIOU";
for (char c : text) {
if (vowels.find(c) != string::npos) count++;
}
return count;
}
Prompt: check if number is prime
Output:
#include <cmath>
using namespace std;
bool isPrime(int n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
for (int i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0) return false;
}
return true;
}""",
"c": """You are an expert C programmer. Generate complete, working C code.
STRICT RULES:
- Output ONLY executable C code
- NO explanations, NO markdown, NO text
- Include necessary headers (#include)
- Write complete functions with proper logic
- NO placeholders or incomplete code
EXAMPLES:
Prompt: count vowels in string
Output:
#include <stdio.h>
#include <string.h>
int countVowels(const char* text) {
int count = 0;
const char* vowels = "aeiouAEIOU";
for (int i = 0; text[i]; i++) {
if (strchr(vowels, text[i])) count++;
}
return count;
}
Prompt: check if number is prime
Output:
#include <math.h>
int isPrime(int n) {
if (n < 2) return 0;
if (n == 2) return 1;
if (n % 2 == 0) return 0;
for (int i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0) return 0;
}
return 1;
}""",
"sql": """You are an expert SQL specialist. Generate complete, working SQL queries.
STRICT RULES:
- Output ONLY executable SQL code
- NO explanations, NO markdown, NO text
- Write complete queries with proper syntax
- NO placeholders or incomplete code
- Follow SQL best practices
EXAMPLES:
Prompt: select all users
Output:
SELECT * FROM users
WHERE status = 'active'
ORDER BY created_at DESC
LIMIT 100;
Prompt: count records by category
Output:
SELECT
category,
COUNT(*) as count,
AVG(price) as avg_price
FROM products
GROUP BY category
ORDER BY count DESC;"""
}
# ============================================================================
# LOCAL LLM WITH SELF-CONSISTENCY
# ============================================================================
class LocalLLM:
"""Interface to Qwen2.5-Coder-7B with Self-Consistency"""
def __init__(self, model_path: str = MODEL_PATH):
"""Initialize the local model"""
logger.info(f"Loading model from {model_path}...")
if not os.path.exists(model_path):
logger.warning(f"Model not found at {model_path}")
logger.info("Using fallback mode - will generate template code")
self.llm = None
return
try:
self.llm = Llama(**MODEL_PARAMS)
logger.info("✅ Model loaded successfully!")
except Exception as e:
logger.error(f"Error loading model: {e}")
self.llm = None
def generate_with_self_consistency(
self,
prompt: str,
language: str,
num_samples: int = NUM_SAMPLES
) -> str:
"""Generate code using self-consistency prompting"""
logger.info(f"Generating {num_samples} {language} solutions...")
if not self.llm:
logger.warning("LLM not available, using fallback")
return self._fallback_code(prompt, language)
solutions = []
system_prompt = SYSTEM_PROMPTS.get(language, SYSTEM_PROMPTS["python"])
for i in range(num_samples):
temp = TEMPERATURES[i % len(TEMPERATURES)]
full_prompt = f"""{system_prompt}
Prompt: {prompt}
Output:"""
try:
response = self.llm(
full_prompt,
max_tokens=1500,
temperature=temp,
top_p=0.9,
repeat_penalty=1.15,
echo=False,
stop=["Prompt:", "\n\n\n\n"]
)
code = self._extract_code(response['choices'][0]['text'].strip(), language)
if code:
score = self._score_code(code, prompt, language)
solutions.append({
'code': code,
'score': score,
'sample': i + 1
})
logger.info(f"Sample {i+1} generated (score: {score:.2f})")
except Exception as e:
logger.warning(f"Sample {i+1} failed: {e}")
continue
if not solutions:
logger.warning("All samples failed, using fallback")
return self._fallback_code(prompt, language)
best = max(solutions, key=lambda x: x['score'])
logger.info(f"Best solution: Sample {best['sample']} (score: {best['score']:.2f})")
return best['code']
def _extract_code(self, response: str, language: str) -> str:
"""Extract valid code from response"""
if not response:
return ""
# Remove markdown
for marker in ["```python", "```javascript", "```java", "```cpp", "```c", "```sql", "```"]:
if marker in response:
start = response.find(marker) + len(marker)
end = response.find("```", start)
if end != -1:
response = response[start:end].strip()
lines = response.split('\n')
code_lines = []
found_code = False
for line in lines:
if not found_code:
if any(line.strip().startswith(kw) for kw in ['def ', 'class ', 'function', 'import ', 'from ', 'public ', '#include', 'SELECT', 'CREATE']):
found_code = True
else:
continue
code_lines.append(line)
code = '\n'.join(code_lines).strip()
if not code or len(code) < 15:
return ""
bad_patterns = ['TODO', 'FIXME', 'placeholder', 'implement', 'pass #']
if any(p.lower() in code.lower() for p in bad_patterns):
return ""
if language == "python":
try:
import ast
ast.parse(code)
return code
except SyntaxError:
return ""
return code
def _score_code(self, code: str, prompt: str, language: str) -> float:
"""Score code quality"""
score = 0.0
length = len(code)
if 50 < length < 1000:
score += 2.0
elif 30 < length < 1500:
score += 1.0
if 'def ' in code or 'function' in code or 'class ' in code:
score += 3.0
if 'return ' in code:
score += 2.0
if '"""' in code or "'''" in code or '//' in code or '--' in code:
score += 1.0
logic_keywords = ['if ', 'for ', 'while ', 'try:', 'with ', 'SELECT', 'WHERE']
if any(kw in code for kw in logic_keywords):
score += 2.0
for pattern in ['TODO', 'FIXME', 'pass\n', '...']:
if pattern in code:
score -= 5.0
prompt_words = [w for w in prompt.lower().split() if len(w) > 3]
code_lower = code.lower()
matches = sum(1 for word in prompt_words if word in code_lower)
score += matches * 0.5
return max(0.0, score)
def _fallback_code(self, prompt: str, language: str) -> str:
"""Generate fallback code based on language templates"""
templates = {
"python": f'''# {prompt}
def main():
"""Main function"""
# Implementation here
pass
if __name__ == "__main__":
main()''',
"javascript": f'''// {prompt}
function main() {{
// Implementation here
return result;
}}
main();''',
"java": f'''// {prompt}
public class Solution {{
public static void main(String[] args) {{
// Implementation here
}}
}}''',
"cpp": f'''// {prompt}
#include <iostream>
using namespace std;
int main() {{
// Implementation here
return 0;
}}''',
"c": f'''// {prompt}
#include <stdio.h>
int main() {{
// Implementation here
return 0;
}}''',
"sql": f'''-- {prompt}
SELECT * FROM table_name
WHERE condition = true
LIMIT 10;'''
}
return templates.get(language, templates["python"])
# ============================================================================
# CODE GENERATOR AGENT
# ============================================================================
class CodeGeneratorAgent:
"""Multi-language code generator agent"""
def __init__(self, model_path: str = MODEL_PATH):
"""Initialize the agent"""
logger.info("Initializing Code Generator Agent...")
self.llm = LocalLLM(model_path)
logger.info("✅ Agent ready!")
def generate_code(self, prompt: str, language: str = "python") -> Dict[str, Any]:
"""
Generate code for given prompt and language
Args:
prompt: Description of code to generate
language: Programming language (python, javascript, java, cpp, c, sql)
Returns:
Dictionary with generated code and metadata
"""
if language not in LANGUAGE_CONFIGS:
logger.error(f"Unsupported language: {language}")
language = "python"
logger.info(f"🚀 Generating {language} code")
logger.info(f"📝 Prompt: {prompt[:100]}...")
code = self.llm.generate_with_self_consistency(prompt, language)
logger.info(f"✅ Code generation complete")
return {
"code": code,
"language": language,
"prompt": prompt,
"timestamp": datetime.now().isoformat(),
"status": "success"
}