Spaces:
Runtime error
Runtime error
File size: 9,061 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 | """
Language Context Manager for Multi-Language Chat Agent
This module manages programming language context for chat sessions,
including language switching, prompt templates, and validation.
"""
import logging
from typing import Optional
from sqlalchemy.exc import SQLAlchemyError
from ..models.language_context import LanguageContext
from ..models.base import db
logger = logging.getLogger(__name__)
class LanguageContextError(Exception):
"""Base exception for language context errors."""
pass
class LanguageContextManager:
"""
Manages programming language context for chat sessions using database persistence.
Handles language switching, prompt template generation, and validation
of supported programming languages with Python as the default.
"""
def __init__(self):
"""Initialize the Language Context Manager."""
pass
def validate_language(self, language: str) -> bool:
"""
Validate if a programming language is supported.
Args:
language: Programming language to validate
Returns:
bool: True if language is supported, False otherwise
"""
if not language:
return False
return LanguageContext.is_supported_language(language.lower().strip())
def get_context(self, session_id: str) -> LanguageContext:
"""
Get the language context for a session.
Args:
session_id: Unique session identifier
Returns:
LanguageContext: The language context object
Raises:
LanguageContextError: If context retrieval fails
"""
try:
context = LanguageContext.get_or_create_context(session_id)
return context
except SQLAlchemyError as e:
logger.error(f"Database error getting language context: {e}")
raise LanguageContextError(f"Failed to get language context: {e}")
def create_context(self, session_id: str, language: str = 'python') -> LanguageContext:
"""
Create a new language context for a session.
Args:
session_id: Unique session identifier
language: Programming language to set (default: python)
Returns:
LanguageContext: The created language context object
Raises:
LanguageContextError: If context creation fails
"""
try:
if not self.validate_language(language):
supported = LanguageContext.get_supported_languages()
raise LanguageContextError(f"Unsupported language: {language}. Supported: {', '.join(supported)}")
context = LanguageContext.create_context(session_id, language)
logger.info(f"Created language context for session {session_id} with language {language}")
return context
except SQLAlchemyError as e:
logger.error(f"Database error creating language context: {e}")
raise LanguageContextError(f"Failed to create language context: {e}")
def get_language(self, session_id: str) -> str:
"""
Get the current programming language for a session.
Args:
session_id: Unique session identifier
Returns:
str: Current programming language (defaults to Python)
"""
try:
context = self.get_context(session_id)
return context.language
except LanguageContextError:
logger.warning(f"Could not get language context for session {session_id}, using default")
return 'python'
def set_language(self, session_id: str, language: str) -> LanguageContext:
"""
Set the programming language for a session.
Args:
session_id: Unique session identifier
language: Programming language to set
Returns:
LanguageContext: The updated language context object
Raises:
LanguageContextError: If language setting fails
"""
try:
if not self.validate_language(language):
supported = LanguageContext.get_supported_languages()
raise LanguageContextError(f"Unsupported language: {language}. Supported: {', '.join(supported)}")
context = self.get_context(session_id)
context.set_language(language.lower().strip())
db.session.commit()
logger.info(f"Language set to {language} for session {session_id}")
return context
except SQLAlchemyError as e:
db.session.rollback()
logger.error(f"Database error setting language: {e}")
raise LanguageContextError(f"Failed to set language: {e}")
def get_language_prompt_template(self, language: Optional[str] = None, session_id: Optional[str] = None) -> str:
"""
Get the prompt template for a specific language or session.
Args:
language: Programming language (optional)
session_id: Session identifier (optional)
Returns:
str: Language-specific prompt template
"""
try:
if session_id:
context = self.get_context(session_id)
return context.get_prompt_template()
if language and self.validate_language(language):
normalized_language = language.lower().strip()
lang_config = LanguageContext.SUPPORTED_LANGUAGES.get(normalized_language, {})
return lang_config.get('prompt_template', '')
# Default to Python template
return LanguageContext.SUPPORTED_LANGUAGES['python']['prompt_template']
except LanguageContextError:
logger.warning("Could not get prompt template, using default")
return LanguageContext.SUPPORTED_LANGUAGES['python']['prompt_template']
def get_session_context_info(self, session_id: str) -> dict:
"""
Get complete context information for a session.
Args:
session_id: Unique session identifier
Returns:
dict: Session context including language, template, and metadata
"""
try:
context = self.get_context(session_id)
return {
'session_id': session_id,
'language': context.language,
'prompt_template': context.get_prompt_template(),
'syntax_highlighting': context.get_syntax_highlighting(),
'language_info': context.get_language_info(),
'updated_at': context.updated_at.isoformat()
}
except LanguageContextError as e:
logger.error(f"Error getting session context info: {e}")
return {
'session_id': session_id,
'language': 'python',
'error': str(e)
}
def remove_session_context(self, session_id: str) -> bool:
"""
Remove context for a session (cleanup).
Args:
session_id: Unique session identifier
Returns:
bool: True if session was removed, False if not found
"""
try:
context = db.session.query(LanguageContext).filter(
LanguageContext.session_id == session_id
).first()
if context:
db.session.delete(context)
db.session.commit()
logger.info(f"Removed context for session {session_id}")
return True
return False
except SQLAlchemyError as e:
db.session.rollback()
logger.error(f"Database error removing language context: {e}")
raise LanguageContextError(f"Failed to remove language context: {e}")
def get_supported_languages(self) -> list:
"""
Get the list of supported programming languages.
Returns:
list: List of supported language names
"""
return LanguageContext.get_supported_languages()
def get_language_display_names(self) -> dict:
"""
Get the mapping of language codes to display names.
Returns:
dict: Mapping of language codes to display names
"""
return LanguageContext.get_language_display_names() |