from transformers import ( AutoTokenizer, AutoModelForSeq2SeqLM, AutoModelForCausalLM ) import torch FREE_MODELS = { "Flan-T5 Large": { "id": "google/flan-t5-large", "type": "seq2seq", }, "Mistral-7B Instruct": { "id": "mistralai/Mistral-7B-Instruct-v0.2", "type": "causal", }, "TinyLlama-1.1B Chat": { "id": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "type": "causal", }, "Phi-2": { "id": "microsoft/phi-2", "type": "causal", }, "Zephyr-7B Alpha": { "id": "HuggingFaceH4/zephyr-7b-alpha", "type": "causal", }, "Gemma-2B Instruct": { "id": "google/gemma-2b-it", "type": "causal", } } model_cache = {} def load_model(model_name): if model_name in model_cache: return model_cache[model_name] model_info = FREE_MODELS[model_name] tokenizer = AutoTokenizer.from_pretrained(model_info["id"]) if model_info["type"] == "seq2seq": model = AutoModelForSeq2SeqLM.from_pretrained(model_info["id"]) else: model = AutoModelForCausalLM.from_pretrained(model_info["id"]) model.eval() model_cache[model_name] = (tokenizer, model, model_info["type"]) return tokenizer, model, model_info["type"] def run_model(model_name, prompt): try: tokenizer, model, model_type = load_model(model_name) inputs = tokenizer(prompt, return_tensors="pt") with torch.no_grad(): if model_type == "seq2seq": outputs = model.generate(**inputs, max_new_tokens=256) else: outputs = model.generate(**inputs, max_new_tokens=256, pad_token_id=tokenizer.eos_token_id) return tokenizer.decode(outputs[0], skip_special_tokens=True) except Exception as e: return f"⚠️ Error: {str(e)}" def get_model_list(): return list(FREE_MODELS.keys())