Srishti280992 commited on
Commit
12e0cfc
·
verified ·
1 Parent(s): 3848364

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -52
app.py CHANGED
@@ -140,8 +140,8 @@ class AppModelStatus:
140
  class OptionalHFInferenceClient:
141
  """Small adapter around huggingface_hub.InferenceClient.
142
 
143
- This adapter is optional. If a model id is not configured, the app still
144
- works through WorldSmithAI's deterministic fallback generator.
145
  """
146
 
147
  def __init__(self, model_id: str, token: str | None = None) -> None:
@@ -149,8 +149,8 @@ class OptionalHFInferenceClient:
149
 
150
  from huggingface_hub import InferenceClient
151
 
152
- self.model_id = model_id
153
- self.client = InferenceClient(model=model_id, token=token)
154
 
155
  def generate(
156
  self,
@@ -160,27 +160,45 @@ class OptionalHFInferenceClient:
160
  temperature: float = 0.2,
161
  **_: Any,
162
  ) -> str:
163
- """Generate text using common InferenceClient methods."""
 
 
164
 
165
  if messages:
166
- chat_text = self._try_chat_completion(
 
 
 
 
 
 
 
 
 
167
  messages,
168
  max_new_tokens=max_new_tokens,
169
  temperature=temperature,
 
170
  )
171
- if chat_text:
172
- return chat_text
173
 
174
  if prompt:
175
- text_generation = self._try_text_generation(
176
  prompt,
177
  max_new_tokens=max_new_tokens,
178
  temperature=temperature,
 
179
  )
180
- if text_generation:
181
- return text_generation
182
-
183
- raise RuntimeError("InferenceClient did not return generated text")
 
 
 
 
 
184
 
185
  def _try_chat_completion(
186
  self,
@@ -188,34 +206,85 @@ class OptionalHFInferenceClient:
188
  *,
189
  max_new_tokens: int,
190
  temperature: float,
 
191
  ) -> str | None:
192
- """Try chat-style generation methods."""
193
 
194
- try:
195
- chat_completion = getattr(self.client, "chat_completion", None)
196
- if callable(chat_completion):
197
- response = chat_completion(
198
- messages=messages,
199
- max_tokens=max_new_tokens,
200
- temperature=temperature,
201
- )
202
- return _extract_model_text(response)
203
- except Exception:
204
- logger.debug("InferenceClient.chat_completion failed", exc_info=True)
205
 
206
  try:
207
- chat = getattr(self.client, "chat", None)
208
- completions = getattr(chat, "completions", None)
209
- create = getattr(completions, "create", None)
210
- if callable(create):
211
- response = create(
212
- messages=messages,
213
- max_tokens=max_new_tokens,
214
- temperature=temperature,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  )
216
- return _extract_model_text(response)
217
- except Exception:
218
- logger.debug("InferenceClient.chat.completions.create failed", exc_info=True)
219
 
220
  return None
221
 
@@ -225,21 +294,52 @@ class OptionalHFInferenceClient:
225
  *,
226
  max_new_tokens: int,
227
  temperature: float,
 
228
  ) -> str | None:
229
- """Try text-generation style methods."""
230
 
231
- try:
232
- text_generation = getattr(self.client, "text_generation", None)
233
- if callable(text_generation):
234
- response = text_generation(
235
- prompt,
236
- max_new_tokens=max_new_tokens,
237
- temperature=temperature,
238
- return_full_text=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  )
240
- return _extract_model_text(response)
241
- except Exception:
242
- logger.debug("InferenceClient.text_generation failed", exc_info=True)
243
 
244
  return None
245
 
@@ -326,17 +426,17 @@ def model_health_check_ui() -> str:
326
  )
327
 
328
  return (
329
- f"Model client is configured.\n\n"
330
  f"Model id: {MODEL_STATUS.model_id}\n\n"
331
- f"Raw response:\n{response}"
332
  )
333
  except Exception as exc:
334
  logger.exception("Model health check failed")
335
  return (
336
- f"Model client is configured but inference failed.\n\n"
337
  f"Model id: {MODEL_STATUS.model_id}\n\n"
338
  f"Error type: {exc.__class__.__name__}\n"
339
- f"Error: {exc}"
340
  )
341
 
342
 
@@ -978,6 +1078,14 @@ examples/
978
 
979
  return demo
980
 
 
 
 
 
 
 
 
 
981
 
982
  def _extract_model_text(response: Any) -> str | None:
983
  """Extract text from common model response shapes."""
 
140
  class OptionalHFInferenceClient:
141
  """Small adapter around huggingface_hub.InferenceClient.
142
 
143
+ This adapter tries both chat-completion and text-generation APIs and raises
144
+ detailed errors instead of hiding provider/model failures.
145
  """
146
 
147
  def __init__(self, model_id: str, token: str | None = None) -> None:
 
149
 
150
  from huggingface_hub import InferenceClient
151
 
152
+ self.model_id = model_id.strip().strip('"').strip("'").strip()
153
+ self.client = InferenceClient(model=self.model_id, token=token)
154
 
155
  def generate(
156
  self,
 
160
  temperature: float = 0.2,
161
  **_: Any,
162
  ) -> str:
163
+ """Generate text using Hugging Face chat or text-generation APIs."""
164
+
165
+ errors: list[str] = []
166
 
167
  if messages:
168
+ text = self._try_chat_completion(
169
+ messages,
170
+ max_new_tokens=max_new_tokens,
171
+ temperature=temperature,
172
+ errors=errors,
173
+ )
174
+ if text:
175
+ return text
176
+
177
+ text = self._try_openai_compatible_chat(
178
  messages,
179
  max_new_tokens=max_new_tokens,
180
  temperature=temperature,
181
+ errors=errors,
182
  )
183
+ if text:
184
+ return text
185
 
186
  if prompt:
187
+ text = self._try_text_generation(
188
  prompt,
189
  max_new_tokens=max_new_tokens,
190
  temperature=temperature,
191
+ errors=errors,
192
  )
193
+ if text:
194
+ return text
195
+
196
+ error_text = "\n".join(errors) if errors else "No inference method was attempted."
197
+ raise RuntimeError(
198
+ "InferenceClient did not return generated text.\n\n"
199
+ f"Model id: {self.model_id}\n\n"
200
+ f"Attempted methods and errors:\n{error_text}"
201
+ )
202
 
203
  def _try_chat_completion(
204
  self,
 
206
  *,
207
  max_new_tokens: int,
208
  temperature: float,
209
+ errors: list[str],
210
  ) -> str | None:
211
+ """Try InferenceClient.chat_completion()."""
212
 
213
+ chat_completion = getattr(self.client, "chat_completion", None)
214
+ if not callable(chat_completion):
215
+ errors.append("chat_completion: method not available on InferenceClient")
216
+ return None
 
 
 
 
 
 
 
217
 
218
  try:
219
+ response = chat_completion(
220
+ messages=messages,
221
+ max_tokens=max_new_tokens,
222
+ temperature=temperature,
223
+ )
224
+ text = _extract_model_text(response)
225
+ if text:
226
+ return text
227
+
228
+ errors.append(
229
+ "chat_completion: response had no extractable text. "
230
+ f"response_type={response.__class__.__name__}, response={_short_repr(response)}"
231
+ )
232
+ return None
233
+ except Exception as exc:
234
+ errors.append(f"chat_completion: {exc.__class__.__name__}: {exc}")
235
+ return None
236
+
237
+ def _try_openai_compatible_chat(
238
+ self,
239
+ messages: list[dict[str, str]],
240
+ *,
241
+ max_new_tokens: int,
242
+ temperature: float,
243
+ errors: list[str],
244
+ ) -> str | None:
245
+ """Try InferenceClient.chat.completions.create()."""
246
+
247
+ chat = getattr(self.client, "chat", None)
248
+ completions = getattr(chat, "completions", None)
249
+ create = getattr(completions, "create", None)
250
+
251
+ if not callable(create):
252
+ errors.append("chat.completions.create: method not available on InferenceClient")
253
+ return None
254
+
255
+ call_variants = (
256
+ {
257
+ "model": self.model_id,
258
+ "messages": messages,
259
+ "max_tokens": max_new_tokens,
260
+ "temperature": temperature,
261
+ },
262
+ {
263
+ "messages": messages,
264
+ "max_tokens": max_new_tokens,
265
+ "temperature": temperature,
266
+ },
267
+ )
268
+
269
+ for kwargs in call_variants:
270
+ try:
271
+ response = create(**kwargs)
272
+ text = _extract_model_text(response)
273
+ if text:
274
+ return text
275
+
276
+ errors.append(
277
+ "chat.completions.create: response had no extractable text. "
278
+ f"kwargs_keys={list(kwargs.keys())}, "
279
+ f"response_type={response.__class__.__name__}, "
280
+ f"response={_short_repr(response)}"
281
+ )
282
+ except Exception as exc:
283
+ errors.append(
284
+ "chat.completions.create: "
285
+ f"kwargs_keys={list(kwargs.keys())}, "
286
+ f"{exc.__class__.__name__}: {exc}"
287
  )
 
 
 
288
 
289
  return None
290
 
 
294
  *,
295
  max_new_tokens: int,
296
  temperature: float,
297
+ errors: list[str],
298
  ) -> str | None:
299
+ """Try InferenceClient.text_generation()."""
300
 
301
+ text_generation = getattr(self.client, "text_generation", None)
302
+ if not callable(text_generation):
303
+ errors.append("text_generation: method not available on InferenceClient")
304
+ return None
305
+
306
+ call_variants = (
307
+ {
308
+ "prompt": prompt,
309
+ "max_new_tokens": max_new_tokens,
310
+ "temperature": temperature,
311
+ "return_full_text": False,
312
+ },
313
+ {
314
+ "prompt": prompt,
315
+ "max_new_tokens": max_new_tokens,
316
+ "return_full_text": False,
317
+ },
318
+ {
319
+ "prompt": prompt,
320
+ "max_new_tokens": max_new_tokens,
321
+ },
322
+ )
323
+
324
+ for kwargs in call_variants:
325
+ try:
326
+ response = text_generation(**kwargs)
327
+ text = _extract_model_text(response)
328
+ if text:
329
+ return text
330
+
331
+ errors.append(
332
+ "text_generation: response had no extractable text. "
333
+ f"kwargs_keys={list(kwargs.keys())}, "
334
+ f"response_type={response.__class__.__name__}, "
335
+ f"response={_short_repr(response)}"
336
+ )
337
+ except Exception as exc:
338
+ errors.append(
339
+ "text_generation: "
340
+ f"kwargs_keys={list(kwargs.keys())}, "
341
+ f"{exc.__class__.__name__}: {exc}"
342
  )
 
 
 
343
 
344
  return None
345
 
 
426
  )
427
 
428
  return (
429
+ "Model client is configured and returned text.\n\n"
430
  f"Model id: {MODEL_STATUS.model_id}\n\n"
431
+ f"Response:\n{response}"
432
  )
433
  except Exception as exc:
434
  logger.exception("Model health check failed")
435
  return (
436
+ "Model client is configured but inference failed.\n\n"
437
  f"Model id: {MODEL_STATUS.model_id}\n\n"
438
  f"Error type: {exc.__class__.__name__}\n"
439
+ f"Error:\n{exc}"
440
  )
441
 
442
 
 
1078
 
1079
  return demo
1080
 
1081
+ def _short_repr(value: Any, *, max_chars: int = 1200) -> str:
1082
+ """Return a bounded repr for diagnostics."""
1083
+
1084
+ text = repr(value)
1085
+ if len(text) <= max_chars:
1086
+ return text
1087
+ return text[: max_chars - 3] + "..."
1088
+
1089
 
1090
  def _extract_model_text(response: Any) -> str | None:
1091
  """Extract text from common model response shapes."""