File size: 5,757 Bytes
a7d7463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()