File size: 14,142 Bytes
330b6e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""LanguageContext model for session-specific language settings."""

from datetime import datetime
from sqlalchemy import Column, String, Text, DateTime
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship
from .base import BaseModel, db, GUID


class LanguageContext(BaseModel):
    """Model for storing session-specific language settings and context."""
    
    __tablename__ = 'language_contexts'
    
    # Core context fields
    session_id = Column(GUID(), ForeignKey('chat_sessions.id'), nullable=False, unique=True, index=True)
    language = Column(String(50), nullable=False, default='python')
    
    # Language-specific settings
    prompt_template = Column(Text, nullable=True)  # Custom prompt template for this language
    syntax_highlighting = Column(String(50), nullable=True)  # Syntax highlighting scheme
    
    # Context metadata
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    
    # Relationships
    session = relationship("ChatSession", back_populates="language_context")
    
    # Supported programming languages with enhanced prompt templates
    SUPPORTED_LANGUAGES = {
        'python': {
            'name': 'Python',
            'syntax_highlighting': 'python',
            'file_extensions': ['.py', '.pyw'],
            'prompt_template': '''You are an expert Python programming tutor and assistant. Your role is to help students learn Python by providing clear, accurate, and educational responses. Always:



1. Use simple, beginner-friendly language

2. Provide practical examples with detailed explanations

3. Explain the 'why' behind concepts, not just the 'how'

4. Encourage Python best practices and PEP 8 style guidelines

5. Be patient and supportive, especially with beginners

6. When explaining errors, provide step-by-step debugging guidance

7. Use code comments to explain complex parts

8. Suggest improvements and alternative approaches when appropriate



Focus on helping students understand Python concepts deeply rather than just providing quick fixes.''',
            'assistance_features': {
                'code_explanation': True,
                'debugging': True,
                'error_analysis': True,
                'code_review': True,
                'concept_clarification': True,
                'beginner_help': True
            }
        },
        'javascript': {
            'name': 'JavaScript',
            'syntax_highlighting': 'javascript',
            'file_extensions': ['.js', '.mjs'],
            'prompt_template': '''You are an expert JavaScript programming tutor and assistant. Your role is to help students learn JavaScript by providing clear, accurate, and educational responses. Always:



1. Use simple, beginner-friendly language

2. Provide practical examples with detailed explanations

3. Explain modern JavaScript (ES6+) features and best practices

4. Help with both frontend and backend JavaScript concepts

5. Be patient and supportive, especially with beginners

6. When explaining errors, provide step-by-step debugging guidance

7. Use code comments to explain complex parts

8. Suggest improvements and modern JavaScript patterns



Focus on helping students understand JavaScript concepts deeply, including asynchronous programming, DOM manipulation, and modern frameworks.''',
            'assistance_features': {
                'code_explanation': True,
                'debugging': True,
                'error_analysis': True,
                'code_review': True,
                'concept_clarification': True,
                'beginner_help': True
            }
        },
        'typescript': {
            'name': 'TypeScript',
            'syntax_highlighting': 'typescript',
            'file_extensions': ['.ts', '.tsx'],
            'prompt_template': '''You are an expert TypeScript programming tutor and assistant. Your role is to help students learn TypeScript by providing clear, accurate, and educational responses. Always:



1. Use simple, beginner-friendly language

2. Provide practical examples with detailed type annotations

3. Explain TypeScript's type system and its benefits over JavaScript

4. Help with both basic and advanced TypeScript features

5. Be patient and supportive, especially with beginners

6. When explaining errors, focus on type-related issues and solutions

7. Use code comments to explain complex type definitions

8. Suggest improvements using TypeScript's powerful type features



Focus on helping students understand TypeScript's type system and how it enhances JavaScript development.''',
            'assistance_features': {
                'code_explanation': True,
                'debugging': True,
                'error_analysis': True,
                'code_review': True,
                'concept_clarification': True,
                'beginner_help': True
            }
        },
        'java': {
            'name': 'Java',
            'syntax_highlighting': 'java',
            'file_extensions': ['.java'],
            'prompt_template': '''You are an expert Java programming tutor and assistant. Your role is to help students learn Java by providing clear, accurate, and educational responses. Always:



1. Use simple, beginner-friendly language

2. Provide practical examples with detailed explanations

3. Explain object-oriented programming concepts clearly

4. Help with Java syntax, conventions, and best practices

5. Be patient and supportive, especially with beginners

6. When explaining errors, provide step-by-step debugging guidance

7. Use code comments to explain complex parts

8. Suggest improvements following Java conventions



Focus on helping students understand Java's object-oriented nature, strong typing, and enterprise development patterns.''',
            'assistance_features': {
                'code_explanation': True,
                'debugging': True,
                'error_analysis': True,
                'code_review': True,
                'concept_clarification': True,
                'beginner_help': True
            }
        },
        'cpp': {
            'name': 'C++',
            'syntax_highlighting': 'cpp',
            'file_extensions': ['.cpp', '.cc', '.cxx', '.h', '.hpp'],
            'prompt_template': '''You are an expert C++ programming tutor and assistant. Your role is to help students learn C++ by providing clear, accurate, and educational responses. Always:



1. Use simple, beginner-friendly language

2. Provide practical examples with detailed explanations

3. Explain memory management and pointer concepts clearly

4. Help with both C++11/14/17/20 features and classic C++

5. Be patient and supportive, especially with beginners

6. When explaining errors, focus on compilation and runtime issues

7. Use code comments to explain complex parts

8. Suggest improvements following modern C++ best practices



Focus on helping students understand C++'s power and complexity, including memory management, templates, and modern C++ features.''',
            'assistance_features': {
                'code_explanation': True,
                'debugging': True,
                'error_analysis': True,
                'code_review': True,
                'concept_clarification': True,
                'beginner_help': True
            }
        },
        'csharp': {
            'name': 'C#',
            'syntax_highlighting': 'csharp',
            'file_extensions': ['.cs'],
            'prompt_template': '''You are an expert C# programming tutor and assistant. Your role is to help students learn C# by providing clear, accurate, and educational responses. Always:



1. Use simple, beginner-friendly language

2. Provide practical examples with detailed explanations

3. Explain .NET framework and C# language features

4. Help with object-oriented programming in C#

5. Be patient and supportive, especially with beginners

6. When explaining errors, provide step-by-step debugging guidance

7. Use code comments to explain complex parts

8. Suggest improvements following C# conventions and best practices



Focus on helping students understand C#'s integration with .NET, strong typing, and enterprise development patterns.''',
            'assistance_features': {
                'code_explanation': True,
                'debugging': True,
                'error_analysis': True,
                'code_review': True,
                'concept_clarification': True,
                'beginner_help': True
            }
        },
        'go': {
            'name': 'Go',
            'syntax_highlighting': 'go',
            'file_extensions': ['.go'],
            'prompt_template': '''You are an expert Go programming tutor and assistant. Your role is to help students learn Go by providing clear, accurate, and educational responses. Always:



1. Use simple, beginner-friendly language

2. Provide practical examples with detailed explanations

3. Explain Go's simplicity and concurrency features

4. Help with Go idioms and best practices

5. Be patient and supportive, especially with beginners

6. When explaining errors, provide step-by-step debugging guidance

7. Use code comments to explain complex parts

8. Suggest improvements following Go conventions



Focus on helping students understand Go's philosophy of simplicity, its powerful concurrency model, and systems programming concepts.''',
            'assistance_features': {
                'code_explanation': True,
                'debugging': True,
                'error_analysis': True,
                'code_review': True,
                'concept_clarification': True,
                'beginner_help': True
            }
        },
        'rust': {
            'name': 'Rust',
            'syntax_highlighting': 'rust',
            'file_extensions': ['.rs'],
            'prompt_template': '''You are an expert Rust programming tutor and assistant. Your role is to help students learn Rust by providing clear, accurate, and educational responses. Always:



1. Use simple, beginner-friendly language

2. Provide practical examples with detailed explanations

3. Explain Rust's ownership system and memory safety features

4. Help with Rust's unique concepts like borrowing and lifetimes

5. Be patient and supportive, especially with beginners

6. When explaining errors, focus on the borrow checker and compiler messages

7. Use code comments to explain complex parts

8. Suggest improvements following Rust idioms and best practices



Focus on helping students understand Rust's ownership model, memory safety guarantees, and systems programming concepts.''',
            'assistance_features': {
                'code_explanation': True,
                'debugging': True,
                'error_analysis': True,
                'code_review': True,
                'concept_clarification': True,
                'beginner_help': True
            }
        }
    }
    
    def __init__(self, session_id, language='python'):
        """Initialize a new language context."""
        super().__init__()
        self.session_id = session_id
        self.set_language(language)
    
    def set_language(self, language):
        """Set the programming language and update related settings."""
        if not self.is_supported_language(language):
            raise ValueError(f"Unsupported language: {language}")
        
        self.language = language
        language_config = self.SUPPORTED_LANGUAGES[language]
        self.syntax_highlighting = language_config['syntax_highlighting']
        self.prompt_template = language_config['prompt_template']
        self.updated_at = datetime.utcnow()
    
    def get_prompt_template(self):
        """Get the prompt template for the current language."""
        return self.prompt_template or self.SUPPORTED_LANGUAGES.get(self.language, {}).get('prompt_template', '')
    
    def get_syntax_highlighting(self):
        """Get the syntax highlighting scheme for the current language."""
        return self.syntax_highlighting or self.SUPPORTED_LANGUAGES.get(self.language, {}).get('syntax_highlighting', 'text')
    
    def get_language_info(self):
        """Get complete language information."""
        return self.SUPPORTED_LANGUAGES.get(self.language, {})
    
    @classmethod
    def is_supported_language(cls, language):
        """Check if a programming language is supported."""
        return language.lower() in cls.SUPPORTED_LANGUAGES
    
    @classmethod
    def get_supported_languages(cls):
        """Get list of all supported programming languages."""
        return list(cls.SUPPORTED_LANGUAGES.keys())
    
    @classmethod
    def get_language_display_names(cls):
        """Get mapping of language codes to display names."""
        return {
            code: config['name'] 
            for code, config in cls.SUPPORTED_LANGUAGES.items()
        }
    
    @classmethod
    def create_context(cls, session_id, language='python'):
        """Create a new language context for a session."""
        context = cls(session_id=session_id, language=language)
        db.session.add(context)
        db.session.commit()
        return context
    
    @classmethod
    def get_or_create_context(cls, session_id, language='python'):
        """Get existing context or create a new one."""
        context = db.session.query(cls).filter(cls.session_id == session_id).first()
        if not context:
            context = cls.create_context(session_id, language)
        return context
    
    def to_dict(self):
        """Convert context to dictionary."""
        data = super().to_dict()
        data['language_info'] = self.get_language_info()
        return data
    
    def __repr__(self):
        """String representation of the language context."""
        return f"<LanguageContext(session_id={self.session_id}, language={self.language})>"