Jayashree Sridhar commited on
Commit ·
292f6f6
1
Parent(s): 005cc1a
refactore the code files to use TinyGPT2Model
Browse filesFiles changed (4)
123456789101112"""Mistral LLM Tools for CrewAI (modular class version)"""from models.mistral_model import MistralModelclass LLMTools:def __init__(self, config=None):self.config = configself.model = MistralModel()def mistral_chat(self, prompt: str, context: dict = None) -> str:"""Chat with Mistral AI for intelligent responses."""12345678910111213"""Mistral LLM Tools for CrewAI (modular class version)"""#from models.mistral_model import MistralModelfrom models.tinygpt2_model import TinyGPT2Modelclass LLMTools:def __init__(self, config=None):self.config = configself.model =TinyGPT2Model()def mistral_chat(self, prompt: str, context: dict = None) -> str:"""Chat with Mistral AI for intelligent responses."""
4 unmodified lines56789101136 unmodified lines484950515253544 unmodified linesimport asyncioimport soundfile as sfimport tempfile # Added the import for tempfile!from models.mistral_model import MistralModelclass MultilingualVoiceProcessor:def __init__(self, model_name="openai/whisper-base", device=None):36 unmodified linesreturn {"text": text, "language": detected_lang}def detect_emotion(self, text: str) -> dict:model = MistralModel()prompt = f"""Analyze the emotional state in this text: "{text}"Identify:4 unmodified lines5678910111236 unmodified lines495051525354554 unmodified linesimport asyncioimport soundfile as sfimport tempfile # Added the import for tempfile!#from models.mistral_model import MistralModelfrom models.tinygpt2_model import TinyGPT2Modelclass MultilingualVoiceProcessor:def __init__(self, model_name="openai/whisper-base", device=None):36 unmodified linesreturn {"text": text, "language": detected_lang}def detect_emotion(self, text: str) -> dict:model = TinyGPT2Model()prompt = f"""Analyze the emotional state in this text: "{text}"Identify:
2 unmodified lines34567895 unmodified lines151617181920114 unmodified lines1351361371381391401412 unmodified lines"""import numpy as npimport asynciofrom models.mistral_model import MistralModelimport whisperimport numpy as npfrom gtts import gTTS5 unmodified linesimport speech_recognition as srfrom transformers import pipelineimport whisper# class MultilingualVoiceProcessor:# """Handles multilingual STT and TTS"""114 unmodified linesdef detect_emotion(self, text: str) -> dict:"""Detect emotional state from text using LLM."""model = MistralModel()prompt = f"""Analyze the emotional state in this text: "{text}"Identify:2 unmodified lines34567895 unmodified lines15161718192021114 unmodified lines1361371381391401411422 unmodified lines"""import numpy as npimport asyncio#from models.mistral_model import MistralModelimport whisperimport numpy as npfrom gtts import gTTS5 unmodified linesimport speech_recognition as srfrom transformers import pipelineimport whisperfrom models.tinygpt2_model import TinyGPT2Model# class MultilingualVoiceProcessor:# """Handles multilingual STT and TTS"""114 unmodified linesdef detect_emotion(self, text: str) -> dict:"""Detect emotional state from text using LLM."""model = TinyGPT2Model()prompt = f"""Analyze the emotional state in this text: "{text}"Identify:
11 unmodified lines1213141516171 unmodified line19202122232425262728293015 unmodified lines4647484950514 unmodified lines565758596061626364656667686970717273741 unmodified line767778798081828384855 unmodified lines9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311 unmodified line1331341351361371381391401411421431441451461471481491501511521531541552 unmodified lines1581591601611621631641651661671682 unmodified lines1711721731741751761771781791801811821831841851861871881891902 unmodified lines1931941951961971981994 unmodified lines20420520620720820921021121221321421521621711 unmodified lines# Lazy importsif TYPE_CHECKING:from .mistral_model import MistralModel, MistralConfig, MistralPromptFormatter# Public API__all__ = [1 unmodified line"MistralModel","MistralConfig","MistralPromptFormatter",# Model management"load_model","get_model_info","clear_model_cache",# Constants"AVAILABLE_MODELS","MODEL_REQUIREMENTS",15 unmodified lines"size": "7B","context_length": 32768,"languages": ["multilingual"]}}4 unmodified lines"vram": "8GB (GPU) or 16GB (CPU)","disk": "15GB","compute": "GPU recommended"}}# Default configurationDEFAULT_MODEL_CONFIG = {"max_length": 2048,"temperature": 0.7,"top_p": 0.95,"top_k": 50,"do_sample": True,"num_return_sequences": 1,"device": "cuda" if torch.cuda.is_available() else "cpu","torch_dtype": torch.float16 if torch.cuda.is_available() else torch.float32,"load_in_8bit": False,"cache_dir": ".cache/models"}1 unmodified line# Model instance cache_model_cache: Dict[str, Any] = {}def load_model(model_name: str = "mistral-7b-instruct", config: Optional[Dict[str, Any]] = None):"""Load a model with caching supportArgs:model_name: Name of the model to loadconfig: Optional configuration override5 unmodified linescache_key = f"{model_name}_{str(config)}"if cache_key in _model_cache:return _model_cache[cache_key]# Import here to avoid circular importsfrom .mistral_model import MistralModel, MistralConfig# Get model infomodel_info = AVAILABLE_MODELS.get(model_name)if not model_info:raise ValueError(f"Unknown model: {model_name}")# Merge configurationsmodel_config = DEFAULT_MODEL_CONFIG.copy()if config:model_config.update(config)# Create config objectmistral_config = MistralConfig(model_id=model_info["model_id"],**model_config)# Load modelmodel = MistralModel(mistral_config)# Cache it_model_cache[cache_key] = modelreturn modeldef get_model_info(model_name: str) -> Optional[Dict[str, Any]]:"""Get information about a modelArgs:model_name: Name of the modelReturns:Model information dictionary or None"""1 unmodified lineif info:# Add requirementsrequirements = MODEL_REQUIREMENTS.get(model_name, {})info["requirements"] = requirements# Add loading statuscache_keys = [k for k in _model_cache.keys() if k.startswith(model_name)]info["is_loaded"] = len(cache_keys) > 0return infodef clear_model_cache(model_name: Optional[str] = None):"""Clear model cache to free memoryArgs:model_name: Specific model to clear, or None for all"""global _model_cacheif model_name:# Clear specific modelkeys_to_remove = [k for k in _model_cache.keys() if k.startswith(model_name)]2 unmodified lineselse:# Clear all_model_cache.clear()# Force garbage collectionimport gcgc.collect()# Clear GPU cache if using CUDAif torch.cuda.is_available():torch.cuda.empty_cache()2 unmodified linesdef estimate_memory_usage(model_name: str) -> Dict[str, Any]:"""Estimate memory usage for a modelArgs:model_name: Name of the modelReturns:Memory estimation dictionary"""model_info = AVAILABLE_MODELS.get(model_name)if not model_info:return {}size = model_info.get("size", "7B")size_gb = float(size.replace("B", ""))estimates = {"model_size_gb": size_gb,"fp32_memory_gb": size_gb * 4, # 4 bytes per parameter2 unmodified lines"recommended_ram_gb": size_gb * 2.5,"recommended_vram_gb": size_gb * 1.5}return estimatesdef get_device_info() -> Dict[str, Any]:4 unmodified lines"current_device": torch.cuda.current_device() if torch.cuda.is_available() else None,"device_name": torch.cuda.get_device_name() if torch.cuda.is_available() else "CPU"}if torch.cuda.is_available():info["gpu_memory"] = {"allocated": torch.cuda.memory_allocated() / 1024**3, # GB"reserved": torch.cuda.memory_reserved() / 1024**3, # GB"total": torch.cuda.get_device_properties(0).total_memory / 1024**3 # GB}return info# Module initialization11 unmodified lines121314151617181 unmodified line2021222324252627282930313215 unmodified lines484950515253545556575859604 unmodified lines656667686970717273747576777879808182838485868788891 unmodified line9192939495969798991005 unmodified lines1061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441 unmodified line1461471481491501511521531541551561571581591601611621631641651661671681692 unmodified lines1721731741751761771781791801811822 unmodified lines1851861871881891901911921931941951961971981992002012022032042052062072082092 unmodified lines2122132142152162172184 unmodified lines22322422522622722822923023123223323423523611 unmodified lines# Lazy importsif TYPE_CHECKING:from .mistral_model import MistralModel, MistralConfig, MistralPromptFormatterfrom .tiny_gpt2_model import TinyGPT2Model# Public API__all__ = [1 unmodified line"MistralModel","MistralConfig","MistralPromptFormatter","TinyGPT2Model",# Model management"load_model","get_model_info","clear_model_cache",# Constants"AVAILABLE_MODELS","MODEL_REQUIREMENTS",15 unmodified lines"size": "7B","context_length": 32768,"languages": ["multilingual"]},"tiny-gpt2": {"model_id": "sshleifer/tiny-gpt2","type": "tiny","size": "small","context_length": 256,"languages": ["en"]}}4 unmodified lines"vram": "8GB (GPU) or 16GB (CPU)","disk": "15GB","compute": "GPU recommended"},"tiny-gpt2": {"ram": "≤1GB","vram": "CPU only","disk": "<1GB","compute": "CPU"}}# Default configuration: Set to CPU/float32DEFAULT_MODEL_CONFIG = {"max_length": 256,"temperature": 0.7,"top_p": 0.95,"top_k": 50,"do_sample": True,"num_return_sequences": 1,"device": "cpu","torch_dtype": torch.float32,"load_in_8bit": False,"cache_dir": ".cache/models"}1 unmodified line# Model instance cache_model_cache: Dict[str, Any] = {}def load_model(model_name: str = "tiny-gpt2", config: Optional[Dict[str, Any]] = None):"""Load a model with caching supportArgs:model_name: Name of the model to loadconfig: Optional configuration override5 unmodified linescache_key = f"{model_name}_{str(config)}"if cache_key in _model_cache:return _model_cache[cache_key]# Import here to avoid circular importsif model_name == "tiny-gpt2":from .tiny_gpt2_model import TinyGPT2Model# No config needed for TinyGPT2, ignore config for nowmodel = TinyGPT2Model()elif model_name in ["mistral-7b-instruct", "mistral-7b"]:from .mistral_model import MistralModel, MistralConfigmodel_info = AVAILABLE_MODELS.get(model_name)if not model_info:raise ValueError(f"Unknown model: {model_name}")model_config = DEFAULT_MODEL_CONFIG.copy()if config:model_config.update(config)mistral_config = MistralConfig(model_id=model_info["model_id"],**model_config)model = MistralModel(mistral_config)else:raise ValueError(f"Unknown model: {model_name}")# Cache it_model_cache[cache_key] = modelreturn modeldef get_model_info(model_name: str) -> Optional[Dict[str, Any]]:"""Get information about a modelArgs:model_name: Name of the modelReturns:Model information dictionary or None"""1 unmodified lineif info:# Add requirementsrequirements = MODEL_REQUIREMENTS.get(model_name, {})info = info.copy() # avoid mutating global dict!info["requirements"] = requirements# Add loading statuscache_keys = [k for k in _model_cache.keys() if k.startswith(model_name)]info["is_loaded"] = len(cache_keys) > 0return infodef clear_model_cache(model_name: Optional[str] = None):"""Clear model cache to free memoryArgs:model_name: Specific model to clear, or None for all"""global _model_cacheif model_name:# Clear specific modelkeys_to_remove = [k for k in _model_cache.keys() if k.startswith(model_name)]2 unmodified lineselse:# Clear all_model_cache.clear()# Force garbage collectionimport gcgc.collect()# Clear GPU cache if using CUDAif torch.cuda.is_available():torch.cuda.empty_cache()2 unmodified linesdef estimate_memory_usage(model_name: str) -> Dict[str, Any]:"""Estimate memory usage for a modelArgs:model_name: Name of the modelReturns:Memory estimation dictionary"""model_info = AVAILABLE_MODELS.get(model_name)if not model_info:return {}size = model_info.get("size", "7B")if size.endswith("B"):size_gb = float(size.replace("B", "")) # e.g. "7B"elif size == "small":size_gb = 0.02 # Arbitrary tiny model size in GBelse:size_gb = 0.1 # catchallestimates = {"model_size_gb": size_gb,"fp32_memory_gb": size_gb * 4, # 4 bytes per parameter2 unmodified lines"recommended_ram_gb": size_gb * 2.5,"recommended_vram_gb": size_gb * 1.5}return estimatesdef get_device_info() -> Dict[str, Any]:4 unmodified lines"current_device": torch.cuda.current_device() if torch.cuda.is_available() else None,"device_name": torch.cuda.get_device_name() if torch.cuda.is_available() else "CPU"}if torch.cuda.is_available():info["gpu_memory"] = {"allocated": torch.cuda.memory_allocated() / 1024**3, # GB"reserved": torch.cuda.memory_reserved() / 1024**3, # GB"total": torch.cuda.get_device_properties(0).total_memory / 1024**3 # GB}return info# Module initialization
agents/tools/llm_tools.py+3-2
agents/tools/voice_tools.py+3-2
agents/tools/voice_tools_openaiwhisper.py+3-2
models/_init_.py+65-46