daniel-simeone commited on
Commit ·
99c1869
1
Parent(s): 43951a2
add fallback models
Browse files
app.py
CHANGED
|
@@ -86,8 +86,13 @@ class MinimalistTheme(Base):
|
|
| 86 |
class RAGChatbot:
|
| 87 |
"""Chatbot with RAG capabilities."""
|
| 88 |
|
| 89 |
-
# Default
|
| 90 |
-
DEFAULT_CHAT_MODEL = "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
def __init__(
|
| 93 |
self,
|
|
@@ -104,8 +109,12 @@ class RAGChatbot:
|
|
| 104 |
vector_store_path: Path to saved vector store
|
| 105 |
"""
|
| 106 |
self.model_name = model_name if model_name else self.DEFAULT_CHAT_MODEL
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
-
# Initialize Inference API client
|
| 109 |
hf_token = os.environ.get("HF_TOKEN")
|
| 110 |
# Debug: report HF_TOKEN status (masked)
|
| 111 |
if not hf_token:
|
|
@@ -117,13 +126,10 @@ class RAGChatbot:
|
|
| 117 |
print(f"[DEBUG] HF_TOKEN: set (length={len(hf_token)}, masked={masked})")
|
| 118 |
print("HF_TOKEN found. Inference API ready.")
|
| 119 |
|
| 120 |
-
print(f"[DEBUG]
|
| 121 |
try:
|
| 122 |
-
self.inference_client = InferenceClient(
|
| 123 |
-
|
| 124 |
-
token=hf_token
|
| 125 |
-
)
|
| 126 |
-
print("[DEBUG] Inference API client initialized successfully (using chat_completion for this model)")
|
| 127 |
except Exception as e:
|
| 128 |
print(f"[DEBUG] Error initializing Inference API client: {type(e).__name__}: {e}")
|
| 129 |
self.inference_client = None
|
|
@@ -144,28 +150,39 @@ class RAGChatbot:
|
|
| 144 |
self.chat_history = []
|
| 145 |
|
| 146 |
def _generate_with_chat(self, user_content: str, max_new_tokens: int = 512) -> str:
|
| 147 |
-
"""Call the Inference API using
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
def generate_response(self, query: str, use_rag: bool = True, num_results: int = 5) -> str:
|
| 171 |
"""
|
|
@@ -217,8 +234,8 @@ Answer:"""
|
|
| 217 |
err_str = str(api_error).lower()
|
| 218 |
if "model_not_supported" in err_str or "not supported by any provider" in err_str:
|
| 219 |
return (
|
| 220 |
-
"
|
| 221 |
-
"
|
| 222 |
"https://huggingface.co/settings/inference-api."
|
| 223 |
)
|
| 224 |
# Fallback: return formatted chunks with note
|
|
|
|
| 86 |
class RAGChatbot:
|
| 87 |
"""Chatbot with RAG capabilities."""
|
| 88 |
|
| 89 |
+
# Default and fallback models (try in order until one is supported by your Inference API providers)
|
| 90 |
+
DEFAULT_CHAT_MODEL = "microsoft/phi-2"
|
| 91 |
+
FALLBACK_CHAT_MODELS = [
|
| 92 |
+
"HuggingFaceH4/zephyr-7b-beta",
|
| 93 |
+
"Qwen/Qwen2-7B-Instruct",
|
| 94 |
+
"google/gemma-2-2b-it",
|
| 95 |
+
]
|
| 96 |
|
| 97 |
def __init__(
|
| 98 |
self,
|
|
|
|
| 109 |
vector_store_path: Path to saved vector store
|
| 110 |
"""
|
| 111 |
self.model_name = model_name if model_name else self.DEFAULT_CHAT_MODEL
|
| 112 |
+
# Build list of models to try (primary first, then fallbacks not already primary)
|
| 113 |
+
self._models_to_try = [self.model_name] + [
|
| 114 |
+
m for m in self.FALLBACK_CHAT_MODELS if m != self.model_name
|
| 115 |
+
]
|
| 116 |
|
| 117 |
+
# Initialize Inference API client (no model in constructor so we can try multiple)
|
| 118 |
hf_token = os.environ.get("HF_TOKEN")
|
| 119 |
# Debug: report HF_TOKEN status (masked)
|
| 120 |
if not hf_token:
|
|
|
|
| 126 |
print(f"[DEBUG] HF_TOKEN: set (length={len(hf_token)}, masked={masked})")
|
| 127 |
print("HF_TOKEN found. Inference API ready.")
|
| 128 |
|
| 129 |
+
print(f"[DEBUG] Inference API client (models to try: {self._models_to_try})")
|
| 130 |
try:
|
| 131 |
+
self.inference_client = InferenceClient(token=hf_token)
|
| 132 |
+
print("[DEBUG] Inference API client initialized (model chosen per request with fallbacks)")
|
|
|
|
|
|
|
|
|
|
| 133 |
except Exception as e:
|
| 134 |
print(f"[DEBUG] Error initializing Inference API client: {type(e).__name__}: {e}")
|
| 135 |
self.inference_client = None
|
|
|
|
| 150 |
self.chat_history = []
|
| 151 |
|
| 152 |
def _generate_with_chat(self, user_content: str, max_new_tokens: int = 512) -> str:
|
| 153 |
+
"""Call the Inference API using chat_completion; try fallback models if current is not supported."""
|
| 154 |
+
last_error = None
|
| 155 |
+
for model in self._models_to_try:
|
| 156 |
+
print(f"[DEBUG] _generate_with_chat: trying model={model}, prompt_len={len(user_content)}, max_tokens={max_new_tokens}")
|
| 157 |
+
try:
|
| 158 |
+
response = self.inference_client.chat_completion(
|
| 159 |
+
model=model,
|
| 160 |
+
messages=[{"role": "user", "content": user_content}],
|
| 161 |
+
max_tokens=max_new_tokens,
|
| 162 |
+
temperature=0.7,
|
| 163 |
+
)
|
| 164 |
+
print(f"[DEBUG] chat_completion OK for model={model}, response type: {type(response).__name__}")
|
| 165 |
+
if response and response.choices and len(response.choices) > 0:
|
| 166 |
+
msg = response.choices[0].message
|
| 167 |
+
if hasattr(msg, "content") and msg.content:
|
| 168 |
+
# Remember this model for next time
|
| 169 |
+
self.model_name = model
|
| 170 |
+
self._models_to_try = [model] + [m for m in self._models_to_try if m != model]
|
| 171 |
+
return msg.content.strip()
|
| 172 |
+
print("[DEBUG] chat_completion returned empty or unexpected structure")
|
| 173 |
+
except Exception as e:
|
| 174 |
+
last_error = e
|
| 175 |
+
err_str = str(e).lower()
|
| 176 |
+
if "model_not_supported" in err_str or "not supported by any provider" in err_str:
|
| 177 |
+
print(f"[DEBUG] Model {model} not available, trying next fallback.")
|
| 178 |
+
continue
|
| 179 |
+
print(f"[DEBUG] _generate_with_chat exception for {model}: {type(e).__name__}: {e}")
|
| 180 |
+
import traceback
|
| 181 |
+
traceback.print_exc()
|
| 182 |
+
raise
|
| 183 |
+
if last_error is not None:
|
| 184 |
+
raise last_error
|
| 185 |
+
return ""
|
| 186 |
|
| 187 |
def generate_response(self, query: str, use_rag: bool = True, num_results: int = 5) -> str:
|
| 188 |
"""
|
|
|
|
| 234 |
err_str = str(api_error).lower()
|
| 235 |
if "model_not_supported" in err_str or "not supported by any provider" in err_str:
|
| 236 |
return (
|
| 237 |
+
"None of the configured chat models are available with your Inference API providers. "
|
| 238 |
+
"Enable a provider for at least one supported model (e.g. Phi-2, Zephyr, Qwen) at "
|
| 239 |
"https://huggingface.co/settings/inference-api."
|
| 240 |
)
|
| 241 |
# Fallback: return formatted chunks with note
|