"""Coder Agent - Main AI Brain for Myanmar Coding Assistant""" import json import time from typing import Dict, List, Optional, Any from pathlib import Path class CoderAgent: """Expert Myanmar AI coding agent with advanced knowledge""" SYSTEM_PROMPTS = [ "You are an expert programmer with advanced knowledge in: Python, JavaScript, TypeScript, Java, C++, Go, Rust, etc.", "You are a senior security reviewer. Analyze code for vulnerabilities and provide secure version with Myanmar explanation.", "You are a testing expert. Generate comprehensive unit tests for the given function using pytest.", "You are a GUI and game development expert. Provide complete, runnable code with Myanmar explanations.", "You are an expert Myanmar AI coding agent. Answer in Myanmar language and provide code examples when needed.", ] def __init__( self, model: str = "gpt-4", temperature: float = 0.7, max_tokens: int = 2048, knowledge_dir: Optional[str] = None, ): self.model = model self.temperature = temperature self.max_tokens = max_tokens self.knowledge_dir = Path(knowledge_dir) if knowledge_dir else None self.conversation_history: List[Dict[str, str]] = [] self.session_id = self._generate_session_id() def _generate_session_id(self) -> str: """Generate unique session ID""" return f"session_{int(time.time())}_{id(self)}" def set_system_prompt(self, prompt: str) -> None: """Set custom system prompt""" self.system_prompt = prompt def generate_response( self, instruction: str, context: Optional[Dict[str, Any]] = None ) -> Dict[str, Any]: """Generate code response for the given instruction""" self.conversation_history.append({"role": "user", "content": instruction}) response = { "session_id": self.session_id, "instruction": instruction, "response": self._generate_code_response(instruction, context), "timestamp": time.time(), "model": self.model, } self.conversation_history.append( {"role": "assistant", "content": response["response"]} ) return response def _generate_code_response( self, instruction: str, context: Optional[Dict[str, Any]] ) -> str: """Internal method to generate code response""" if self.knowledge_dir: knowledge_content = self._check_knowledge_base(instruction) if knowledge_content: return knowledge_content return self._get_fallback_response(instruction) def _check_knowledge_base(self, instruction: str) -> Optional[str]: """Check local knowledge base for relevant content""" if not self.knowledge_dir: return None keywords = self._extract_keywords(instruction) for keyword in keywords: kb_file = self.knowledge_dir / f"{keyword}_skills.md" if kb_file.exists(): return self._parse_markdown_file(kb_file) return None def _extract_keywords(self, text: str) -> List[str]: """Extract keywords from instruction""" common_langs = ["python", "javascript", "typescript", "java", "go", "rust", "sql"] return [w for w in common_langs if w in text.lower()] def _parse_markdown_file(self, file_path: Path) -> str: """Parse markdown file and extract content""" content = file_path.read_text(encoding="utf-8") lines = content.split("\n") return "\n".join(lines[:20]) def _get_fallback_response(self, instruction: str) -> str: """Get fallback response based on instruction""" instruction_lower = instruction.lower() if "python" in instruction_lower: return self._get_python_response(instruction) elif "javascript" in instruction_lower or "js" in instruction_lower: return self._get_javascript_response(instruction) elif "sql" in instruction_lower: return self._get_sql_response(instruction) else: return self._get_general_response(instruction) def _get_python_response(self, instruction: str) -> str: """Generate Python response""" return "# Python Code\n# TODO: Implement based on instruction" def _get_javascript_response(self, instruction: str) -> str: """Generate JavaScript response""" return "// JavaScript Code\n// TODO: Implement based on instruction" def _get_sql_response(self, instruction: str) -> str: """Generate SQL response""" return "-- SQL Query\n-- TODO: Implement based on instruction" def _get_general_response(self, instruction: str) -> str: """Generate general response""" return "# Code\n# TODO: Implement based on instruction" def get_trajectory(self) -> Dict[str, Any]: """Get conversation trajectory for training""" return { "session_id": self.session_id, "history": self.conversation_history, "timestamp": time.time(), } def save_trajectory(self, path: str) -> None: """Save conversation trajectory to file""" trajectory = self.get_trajectory() file_path = Path(path) / f"session_{int(time.time())}.jsonl" file_path.parent.mkdir(parents=True, exist_ok=True) with open(file_path, "w", encoding="utf-8") as f: f.write(json.dumps(trajectory, ensure_ascii=False) + "\n") def reset(self) -> None: """Reset agent state""" self.conversation_history = [] self.session_id = self._generate_session_id()