Raffaele Terribile
commited on
Aggiorna l'importazione del modello per utilizzare TransformersModel e rimuove la classe SimpleLocalModel
Browse files
app.py
CHANGED
|
@@ -20,7 +20,7 @@ import pandas as pd
|
|
| 20 |
# - Fallback multipli: locale -> remoto -> fisso
|
| 21 |
# =============================================================================
|
| 22 |
|
| 23 |
-
from smolagents import CodeAgent, InferenceClientModel, VisitWebpageTool, PythonInterpreterTool, WebSearchTool, WikipediaSearchTool, FinalAnswerTool, Tool, tool
|
| 24 |
# Importazioni per modelli locali (SOLUZIONE per errore "generate"):
|
| 25 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
| 26 |
from litellm import LiteLLM
|
|
@@ -42,123 +42,13 @@ def invert_sentence(sentence: str) -> str:
|
|
| 42 |
"""
|
| 43 |
return sentence[::-1]
|
| 44 |
|
| 45 |
-
# Wrapper semplificato per modelli locali
|
| 46 |
-
# NUOVO APPROCCIO: Questa classe risolve il problema dell'errore "generate"
|
| 47 |
-
# creando un'interfaccia compatibile tra Transformers pipeline e smolagents
|
| 48 |
-
class SimpleLocalModel:
|
| 49 |
-
"""Wrapper semplice per modelli Transformers locali."""
|
| 50 |
-
|
| 51 |
-
def __init__(self, model_name="gpt2"):
|
| 52 |
-
self.model_name = model_name
|
| 53 |
-
self.pipeline = None
|
| 54 |
-
self._load_model()
|
| 55 |
-
|
| 56 |
-
def _load_model(self):
|
| 57 |
-
"""Carica il modello locale."""
|
| 58 |
-
try:
|
| 59 |
-
print(f"Caricamento modello locale: {self.model_name}")
|
| 60 |
-
self.pipeline = pipeline(
|
| 61 |
-
"text-generation",
|
| 62 |
-
model=self.model_name,
|
| 63 |
-
# device=-1, # Usa CPU
|
| 64 |
-
return_full_text=False # Restituisce solo il testo generato
|
| 65 |
-
)
|
| 66 |
-
print(f"✅ Modello {self.model_name} caricato")
|
| 67 |
-
except Exception as e:
|
| 68 |
-
print(f"❌ Errore caricamento modello: {e}")
|
| 69 |
-
raise
|
| 70 |
-
|
| 71 |
-
def __call__(self, messages, **kwargs):
|
| 72 |
-
"""Genera risposta compatibile con smolagents."""
|
| 73 |
-
try:
|
| 74 |
-
# Estrai il prompt
|
| 75 |
-
if isinstance(messages, list) and messages:
|
| 76 |
-
prompt = messages[-1].get("content", "") if isinstance(messages[-1], dict) else str(messages[-1])
|
| 77 |
-
else:
|
| 78 |
-
prompt = str(messages)
|
| 79 |
-
|
| 80 |
-
if not prompt.strip():
|
| 81 |
-
return "Mi dispiace, non ho ricevuto una domanda."
|
| 82 |
-
|
| 83 |
-
# Genera risposta
|
| 84 |
-
result = self.pipeline(prompt, max_new_tokens=100, do_sample=True, temperature=0.7)
|
| 85 |
-
|
| 86 |
-
if result and len(result) > 0:
|
| 87 |
-
answer = result[0].get("generated_text", "").strip()
|
| 88 |
-
return answer if answer else "Non sono riuscito a generare una risposta."
|
| 89 |
-
else:
|
| 90 |
-
return "Errore nella generazione della risposta."
|
| 91 |
-
|
| 92 |
-
except Exception as e:
|
| 93 |
-
print(f"Errore generazione: {e}")
|
| 94 |
-
return f"Errore: {str(e)}"
|
| 95 |
-
|
| 96 |
# --- First Agent Definition ---
|
| 97 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 98 |
class FirstAgent:
|
| 99 |
### First Agent is the first attempt to develop an agent for the course. ###
|
| 100 |
def __init__(self):
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
# token = os.getenv(os.getenv("TOKEN_NAME"))
|
| 104 |
-
# os.environ["HF_TOKEN"] = token
|
| 105 |
-
# model = InferenceClientModel(
|
| 106 |
-
# token=token
|
| 107 |
-
# )
|
| 108 |
-
|
| 109 |
-
# CODICE ORIGINALE COMMENTATO (approccio con pipeline non compatibile):
|
| 110 |
-
# # Configurazione con fallback multipli
|
| 111 |
-
# model = None
|
| 112 |
-
# # Try 1: Modello locale via Transformers
|
| 113 |
-
# try:
|
| 114 |
-
# model_id = "microsoft/Phi-4-mini-reasoning"
|
| 115 |
-
# tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 116 |
-
# model = AutoModelForCausalLM.from_pretrained(model_id) # ~500MB
|
| 117 |
-
# model = pipeline(
|
| 118 |
-
# task="text-generation",
|
| 119 |
-
# tokenizer=tokenizer,
|
| 120 |
-
# model=model
|
| 121 |
-
# )
|
| 122 |
-
# print(f"Using local {model_id} model")
|
| 123 |
-
# except Exception as e:
|
| 124 |
-
# print(f"Local model failed: {e}")
|
| 125 |
-
# # Try 2: Modello remoto gratuito
|
| 126 |
-
# try:
|
| 127 |
-
# model = LiteLLM(
|
| 128 |
-
# model_id="groq/mixtral-8x7b-32768" # Gratuito con registrazione
|
| 129 |
-
# )
|
| 130 |
-
# print("Using Groq remote model")
|
| 131 |
-
# except Exception as ex:
|
| 132 |
-
# print(f"Remote model failed: {ex}")
|
| 133 |
-
# raise Exception("No working model configuration found")
|
| 134 |
-
|
| 135 |
-
# NUOVO CODICE FUNZIONANTE:
|
| 136 |
-
# Configurazione con fallback per modelli locali
|
| 137 |
-
model = None
|
| 138 |
-
|
| 139 |
-
# Try 1: Modello locale semplificato
|
| 140 |
-
try:
|
| 141 |
-
print("🔄 Tentativo 1: Modello locale GPT-2")
|
| 142 |
-
model = SimpleLocalModel("microsoft/Phi-4-mini-reasoning")
|
| 143 |
-
print("✅ Usando modello locale GPT-2")
|
| 144 |
-
except Exception as e:
|
| 145 |
-
print(f"❌ Modello locale fallito: {e}")
|
| 146 |
-
|
| 147 |
-
# Try 2: Modello remoto (se disponibile)
|
| 148 |
-
try:
|
| 149 |
-
print("🔄 Tentativo 2: Modello remoto Groq")
|
| 150 |
-
model = LiteLLM(model="groq/mixtral-8x7b-32768")
|
| 151 |
-
print("✅ Usando modello remoto Groq")
|
| 152 |
-
except Exception as ex:
|
| 153 |
-
print(f"❌ Modello remoto fallito: {ex}")
|
| 154 |
-
|
| 155 |
-
# Try 3: Fallback finale - risposta fissa
|
| 156 |
-
class FallbackModel:
|
| 157 |
-
def __call__(self, messages, **kwargs):
|
| 158 |
-
return "Sono un agente semplificato. Il modello AI non è disponibile al momento."
|
| 159 |
-
|
| 160 |
-
model = FallbackModel()
|
| 161 |
-
print("⚠️ Usando modello di fallback")
|
| 162 |
|
| 163 |
# Inizializza l'agente
|
| 164 |
self.agent = CodeAgent(
|
|
|
|
| 20 |
# - Fallback multipli: locale -> remoto -> fisso
|
| 21 |
# =============================================================================
|
| 22 |
|
| 23 |
+
from smolagents import CodeAgent, TransformersModel, InferenceClientModel, VisitWebpageTool, PythonInterpreterTool, WebSearchTool, WikipediaSearchTool, FinalAnswerTool, Tool, tool
|
| 24 |
# Importazioni per modelli locali (SOLUZIONE per errore "generate"):
|
| 25 |
from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer
|
| 26 |
from litellm import LiteLLM
|
|
|
|
| 42 |
"""
|
| 43 |
return sentence[::-1]
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
# --- First Agent Definition ---
|
| 46 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 47 |
class FirstAgent:
|
| 48 |
### First Agent is the first attempt to develop an agent for the course. ###
|
| 49 |
def __init__(self):
|
| 50 |
+
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"
|
| 51 |
+
model = TransformersModel(model_id=model_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
# Inizializza l'agente
|
| 54 |
self.agent = CodeAgent(
|