chouchouvs commited on
Commit
0d9a1da
·
verified ·
1 Parent(s): 61f5c08

Update ccpu_parser/llm_client.py

Browse files
Files changed (1) hide show
  1. ccpu_parser/llm_client.py +101 -300
ccpu_parser/llm_client.py CHANGED
@@ -2,351 +2,152 @@
2
  ccpu_parser.llm_client
3
  ----------------------
4
 
5
- Ce module encapsule *tous* les appels au LLM pour l'outil CCPU.
6
-
7
- Rôle global :
8
- - Lire la configuration LLM (provider, modèle, clés API) depuis les variables d'environnement.
9
- - Exposer une fonction unique et simple : `call_llm(prompt: str) -> str`.
10
- - Gérer les appels HTTP vers Hugging Face Inference API **ou** DeepInfra (API OpenAI-compatible).
11
- - Fournir un niveau de logs suffisant pour comprendre facilement ce qui se passe côté Space.
12
-
13
- Fonctions exposées :
14
- - `call_llm(prompt: str) -> str` :
15
- - Point d'entrée unique pour le reste de l'application (e.g. `extract_ccpu_from_pdf`).
16
- - Sélectionne le provider (huggingface / deepinfra) selon la config.
17
- - Logge le provider, le modèle et l'URL cible.
18
- - Retourne la sortie texte brute du LLM (que le post-traitement exploitera).
19
-
20
- Fonctions internes :
21
- - `_call_huggingface_text_generation(prompt: str) -> str` :
22
- - Appelle l'API Inference de Hugging Face pour un modèle text-generation.
23
- - Gère les paramètres `max_new_tokens`, `temperature`, etc.
24
- - Parse la réponse JSON standard `[{"generated_text": "..."}]`.
25
-
26
- - `_call_deepinfra_chat(prompt: str) -> str` :
27
- - Appelle l'API OpenAI-compatible de DeepInfra (`/v1/openai/chat/completions`).
28
- - Envoie le prompt complet en un seul message "user".
29
- - Récupère `choices[0].message.content`.
30
-
31
- Les deux fonctions internes lèvent des `requests.HTTPError` en cas d'erreur HTTP,
32
- et `RuntimeError` en cas de réponse vide ou inattendue. `call_llm` capture ces erreurs,
33
- logge les détails et relance une erreur claire pour le reste de l'appli.
34
  """
35
 
36
  from __future__ import annotations
37
 
38
- import json
39
- import logging
40
  import os
41
- from typing import Any, Dict, List
42
 
43
  import requests
44
 
45
- logger = logging.getLogger("ccpu_parser")
46
-
47
- # ---------------------------------------------------------------------------
48
- # Configuration LLM via variables d'environnement
49
- # ---------------------------------------------------------------------------
50
-
51
- # Provider possible : "huggingface" (par défaut) ou "deepinfra"
52
- LLM_PROVIDER: str = os.getenv("CCPU_LLM_PROVIDER", "deepinfra").strip().lower()
53
-
54
- # Modèle principal (utilisé au moins comme fallback pour les deux providers)
55
- DEFAULT_MODEL_ID: str = os.getenv(
56
- "CCPU_LLM_MODEL_ID",
57
- "NousResearch/Hermes-3-Llama-3.1-70B",
58
- ).strip()
59
-
60
- # Hugging Face Inference
61
- HF_API_URL: str = os.getenv(
62
- "CCPU_LLM_HF_API_URL",
63
- "https://api-inference.huggingface.co/models",
64
- ).rstrip("/")
65
- HF_MODEL_ID: str = DEFAULT_MODEL_ID
66
- HF_API_TOKEN: str | None = (
67
- os.getenv("HF_API_TOKEN") or os.getenv("HUGGINGFACEHUB_API_TOKEN")
68
- )
69
 
70
- # DeepInfra (API OpenAI-compatible)
71
- # ⚠️ Important : on considère CCPU_LLM_DEEPINFRA_API_URL comme *base_url*
72
- # ex: https://api.deepinfra.com/v1/openai
73
- DEEPINFRA_BASE_URL: str = os.getenv(
74
- "CCPU_LLM_DEEPINFRA_API_URL",
75
- "https://api.deepinfra.com/v1/openai",
76
- ).rstrip("/")
77
- DEEPINFRA_MODEL_ID: str = os.getenv(
78
- "CCPU_LLM_DEEPINFRA_MODEL_ID",
79
- DEFAULT_MODEL_ID,
80
- ).strip()
81
- DEEPINFRA_API_KEY: str | None = os.getenv("DEEPINFRA_API_KEY")
82
 
83
- # Paramètres génériques
84
- LLM_TIMEOUT_S: float = float(os.getenv("CCPU_LLM_TIMEOUT", "120"))
85
- LLM_MAX_TOKENS: int = int(os.getenv("CCPU_LLM_MAX_TOKENS", "2048"))
86
- LLM_TEMPERATURE: float = float(os.getenv("CCPU_LLM_TEMPERATURE", "0.1"))
87
 
 
 
88
 
89
- # ---------------------------------------------------------------------------
90
- # Fonctions internes : appels HTTP réels
91
- # ---------------------------------------------------------------------------
92
 
93
-
94
- def _call_huggingface_text_generation(prompt: str) -> str:
95
  """
96
- Appel à l'API Inference de Hugging Face pour un modèle text-generation.
97
-
98
- Entrée :
99
- - prompt : texte complet (incluant instructions système, schéma, exemples...).
100
-
101
- Sortie :
102
- - Texte généré par le modèle (string), sans le prompt initial si `return_full_text=False`.
103
 
104
- Exceptions :
105
- - `requests.HTTPError` en cas de code HTTP != 200.
106
- - `RuntimeError` si la réponse est vide ou mal formée.
107
  """
108
- model_id = HF_MODEL_ID
109
- url = f"{HF_API_URL}/{model_id}"
110
-
111
- headers: Dict[str, str] = {"Accept": "application/json"}
112
- if HF_API_TOKEN:
113
- headers["Authorization"] = f"Bearer {HF_API_TOKEN}"
114
-
115
- payload: Dict[str, Any] = {
116
- "inputs": prompt,
117
- "parameters": {
118
- "max_new_tokens": LLM_MAX_TOKENS,
119
- "temperature": LLM_TEMPERATURE,
120
- "return_full_text": False,
121
- },
122
- }
123
-
124
- logger.info(
125
- "Calling LLM (HuggingFace Inference) model=%s url=%s max_new_tokens=%s temp=%s",
126
- model_id,
127
- url,
128
- LLM_MAX_TOKENS,
129
- LLM_TEMPERATURE,
130
- )
131
-
132
- resp = requests.post(
133
- url,
134
- headers=headers,
135
- json=payload,
136
- timeout=LLM_TIMEOUT_S,
137
- )
138
-
139
- try:
140
- resp.raise_for_status()
141
- except requests.HTTPError as exc:
142
- body_preview = resp.text[:800] if resp.text else "<empty>"
143
- logger.error(
144
- "HTTPError from HuggingFace Inference: status=%s url=%s body=%s",
145
- resp.status_code,
146
- url,
147
- body_preview,
148
  )
149
- raise
150
 
151
- try:
152
- data = resp.json()
153
- except json.JSONDecodeError as exc:
154
- logger.error(
155
- "Invalid JSON from HuggingFace Inference: %s (raw=%r)", exc, resp.text[:800]
156
- )
157
- raise RuntimeError("Invalid JSON response from HuggingFace Inference") from exc
158
-
159
- generated_text: str | None = None
160
-
161
- if isinstance(data, list) and data:
162
- item = data[0]
163
- if isinstance(item, dict):
164
- generated_text = item.get("generated_text")
165
- elif isinstance(data, dict):
166
- generated_text = data.get("generated_text")
167
 
168
- if not generated_text:
169
- logger.error("Empty or unexpected response structure from HuggingFace: %r", data)
170
- raise RuntimeError("Empty response from HuggingFace Inference")
171
-
172
- logger.debug("Raw LLM output (HuggingFace) truncated: %r", generated_text[:5000])
173
- return str(generated_text)
174
-
175
-
176
- def _call_deepinfra_chat(prompt: str) -> str:
177
  """
178
- Appel à l'API OpenAI-compatible de DeepInfra.
179
-
180
- - base_url attendue : https://api.deepinfra.com/v1/openai
181
- - endpoint réel : {base_url}/chat/completions
182
 
183
- Entrée :
184
- - prompt : texte complet (incluant toutes les instructions).
185
-
186
- Sortie :
187
- - Contenu textuel de `choices[0].message.content`.
188
 
189
  Exceptions :
190
- - `RuntimeError` si la clé API n'est pas définie ou si la réponse est vide.
191
- - `requests.HTTPError` pour les erreurs HTTP.
192
  """
193
- if not DEEPINFRA_API_KEY:
194
- raise RuntimeError(
195
- "DEEPINFRA_API_KEY is not set in environment; cannot call DeepInfra."
196
- )
197
 
198
- model_id = DEEPINFRA_MODEL_ID
199
- url = f"{DEEPINFRA_BASE_URL}/chat/completions"
200
 
201
- headers = {
202
- "Authorization": f"Bearer {DEEPINFRA_API_KEY}",
203
- "Content-Type": "application/json",
204
- }
205
 
206
  payload: Dict[str, Any] = {
207
  "model": model_id,
208
  "messages": [
209
  {
210
- "role": "system",
211
- "content": (
212
- "You are a precise extraction engine specialized in parsing "
213
- "chemical CCPU / material specification tables. "
214
- "Follow exactly the constraints defined in the user message."
215
- ),
216
- },
217
- {"role": "user", "content": prompt},
 
 
 
 
 
 
218
  ],
219
- "max_tokens": LLM_MAX_TOKENS,
220
- "temperature": LLM_TEMPERATURE,
 
 
 
 
 
 
 
 
221
  }
222
 
223
  logger.info(
224
- "Calling LLM (DeepInfra) model=%s url=%s max_tokens=%s temp=%s",
225
  model_id,
226
- url,
227
- LLM_MAX_TOKENS,
228
- LLM_TEMPERATURE,
229
- )
230
-
231
- resp = requests.post(
232
- url,
233
- headers=headers,
234
- json=payload,
235
- timeout=LLM_TIMEOUT_S,
236
  )
237
 
238
  try:
239
- resp.raise_for_status()
240
- except requests.HTTPError as exc:
241
- body_preview = resp.text[:800] if resp.text else "<empty>"
 
 
 
 
 
 
 
 
242
  logger.error(
243
- "HTTPError from DeepInfra: status=%s url=%s model=%s body=%s",
244
  resp.status_code,
245
- url,
246
- model_id,
247
- body_preview,
248
  )
249
- raise
250
 
 
251
  try:
252
- data = resp.json()
253
- except json.JSONDecodeError as exc:
254
- logger.error(
255
- "Invalid JSON from DeepInfra: %s (raw=%r)", exc, resp.text[:800]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  )
257
- raise RuntimeError("Invalid JSON response from DeepInfra") from exc
258
-
259
- choices: List[Dict[str, Any]] | None = data.get("choices") # type: ignore[assignment]
260
- if not choices:
261
- logger.error("DeepInfra returned no choices: %r", data)
262
- raise RuntimeError("Empty response from DeepInfra (no choices)")
263
-
264
- message = choices[0].get("message") or {}
265
- content = message.get("content")
266
- if not content:
267
- logger.error("DeepInfra first choice has no content: %r", choices[0])
268
- raise RuntimeError("Empty response from DeepInfra (no content)")
269
-
270
- logger.debug("Raw LLM output (DeepInfra) truncated: %r", content[:5000])
271
- return str(content)
272
 
273
-
274
- # ---------------------------------------------------------------------------
275
- # API publique : call_llm
276
- # ---------------------------------------------------------------------------
277
-
278
-
279
- def call_llm(prompt: str) -> str:
280
- """
281
- Point d'entrée unique pour appeler le LLM.
282
-
283
- Paramètres
284
- ----------
285
- prompt : str
286
- Prompt complet généré par `prompting.py` (incluant système, schémas et exemples).
287
-
288
- Retour
289
- ------
290
- str
291
- Réponse textuelle brute du modèle (sans transformation).
292
-
293
- Comportement
294
- ------------
295
- - Sélectionne le provider en fonction de `CCPU_LLM_PROVIDER`.
296
- - Logge le provider, le modèle choisi et un résumé des paramètres.
297
- - Gère les erreurs HTTP pour retourner des messages explicites, notamment :
298
- * 401 : problème de token.
299
- * 404 : endpoint introuvable / modèle inconnu.
300
- * 410 : endpoint supprimé / modèle plus dispo (HF).
301
- """
302
- provider = LLM_PROVIDER
303
  logger.info(
304
- "call_llm invoked with provider=%s length_prompt=%s",
305
- provider,
306
- len(prompt),
307
  )
308
-
309
- try:
310
- if provider == "deepinfra":
311
- return _call_deepinfra_chat(prompt)
312
- else:
313
- return _call_huggingface_text_generation(prompt)
314
-
315
- except requests.HTTPError as exc:
316
- resp = exc.response
317
- status_code = resp.status_code if resp is not None else None
318
- provider_label = provider or "unknown"
319
-
320
- logger.error(
321
- "HTTPError while calling LLM provider=%s status=%s error=%s",
322
- provider_label,
323
- status_code,
324
- exc,
325
- )
326
-
327
- if status_code == 401:
328
- raise RuntimeError(
329
- f"Erreur d'authentification LLM (provider={provider_label}) : "
330
- f"vérifie la clé API / token."
331
- ) from exc
332
- if status_code == 404:
333
- raise RuntimeError(
334
- f"Endpoint LLM introuvable (404) pour provider={provider_label}. "
335
- f"Vérifie l'URL (base={DEEPINFRA_BASE_URL}) et le nom du modèle "
336
- f"(actuel='{DEEPINFRA_MODEL_ID}')."
337
- ) from exc
338
- if status_code == 410:
339
- raise RuntimeError(
340
- f"Endpoint LLM supprimé ou désactivé (410) pour provider={provider_label}. "
341
- f"Le modèle configuré n'est plus disponible via cette API. "
342
- f"Change CCPU_LLM_MODEL_ID ou CCPU_LLM_PROVIDER dans ta configuration."
343
- ) from exc
344
-
345
- raise RuntimeError(
346
- f"Erreur HTTP lors de l'appel LLM (provider={provider_label}, "
347
- f"status={status_code}) : {exc}"
348
- ) from exc
349
-
350
- except Exception as exc:
351
- logger.exception("Unexpected error while calling LLM: %s", exc)
352
- raise
 
2
  ccpu_parser.llm_client
3
  ----------------------
4
 
5
+ Responsabilité :
6
+ - Appeler le modèle multimodal hébergé sur DeepInfra via l'API OpenAI-compatible.
7
+ - Envoyer une image encodée en base64 + un prompt texte.
8
+ - Activer le JSON mode pour obtenir en sortie un JSON valide.
9
+
10
+ Fonctions fournies :
11
+ - call_vision_llm_to_json(image_jpeg: bytes, prompt: str) -> str
12
+ Envoie l'image + le prompt, renvoie le texte brut de la complétion (censé être un JSON).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  """
14
 
15
  from __future__ import annotations
16
 
17
+ import base64
 
18
  import os
19
+ from typing import Any, Dict
20
 
21
  import requests
22
 
23
+ from .utils import logger
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ DEEPINFRA_API_URL = "https://api.deepinfra.com/v1/openai/chat/completions"
26
+ DEFAULT_MODEL_ID = "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8"
 
 
 
 
 
 
 
 
 
 
27
 
 
 
 
 
28
 
29
+ class LLMClientError(RuntimeError):
30
+ """Erreur générique lors de l'appel au LLM DeepInfra."""
31
 
 
 
 
32
 
33
+ def _get_deepinfra_token() -> str:
 
34
  """
35
+ Récupère le token DeepInfra depuis les variables d'environnement.
 
 
 
 
 
 
36
 
37
+ Utilise d'abord CCPU_LLM_API_KEY si présent, sinon DEEPINFRA_API_KEY.
 
 
38
  """
39
+ token = os.getenv("CCPU_LLM_API_KEY") or os.getenv("DEEPINFRA_API_KEY")
40
+ if not token:
41
+ raise LLMClientError(
42
+ "Aucune clé API DeepInfra trouvée. "
43
+ "Définis CCPU_LLM_API_KEY ou DEEPINFRA_API_KEY dans les secrets Hugging Face."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  )
45
+ return token
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ def call_vision_llm_to_json(image_jpeg: bytes, prompt: str) -> str:
 
 
 
 
 
 
 
 
49
  """
50
+ Appelle le modèle vision DeepInfra (Llama-4 Maverick) avec :
51
+ - une image JPEG encodée en base64,
52
+ - un prompt texte détaillant le schéma JSON attendu.
 
53
 
54
+ Renvoie :
55
+ - Le texte brut de la complétion (normalement un JSON valide grâce au JSON mode).
 
 
 
56
 
57
  Exceptions :
58
+ - LLMClientError en cas d'erreur HTTP ou de format de réponse inattendu.
 
59
  """
60
+ if not image_jpeg:
61
+ raise ValueError("call_vision_llm_to_json: image_jpeg vide")
 
 
62
 
63
+ token = _get_deepinfra_token()
64
+ model_id = os.getenv("CCPU_LLM_MODEL_ID", DEFAULT_MODEL_ID)
65
 
66
+ b64_image = base64.b64encode(image_jpeg).decode("ascii")
 
 
 
67
 
68
  payload: Dict[str, Any] = {
69
  "model": model_id,
70
  "messages": [
71
  {
72
+ "role": "user",
73
+ "content": [
74
+ {
75
+ "type": "image_url",
76
+ "image_url": {
77
+ "url": f"data:image/jpeg;base64,{b64_image}"
78
+ },
79
+ },
80
+ {
81
+ "type": "text",
82
+ "text": prompt,
83
+ },
84
+ ],
85
+ }
86
  ],
87
+ # On laisse un peu de marge mais ce JSON est compact.
88
+ "max_tokens": 2048,
89
+ "temperature": 0.1,
90
+ # JSON mode DeepInfra (OpenAI-compatible).
91
+ "response_format": {"type": "json_object"},
92
+ }
93
+
94
+ headers = {
95
+ "Authorization": f"Bearer {token}",
96
+ "Content-Type": "application/json",
97
  }
98
 
99
  logger.info(
100
+ "llm_client: appel vision DeepInfra model=%s (image=%d octets, prompt_len=%d)",
101
  model_id,
102
+ len(image_jpeg),
103
+ len(prompt),
 
 
 
 
 
 
 
 
104
  )
105
 
106
  try:
107
+ resp = requests.post(
108
+ DEEPINFRA_API_URL,
109
+ headers=headers,
110
+ json=payload,
111
+ timeout=120,
112
+ )
113
+ except Exception as exc: # pragma: no cover
114
+ logger.error("llm_client: requête HTTP vers DeepInfra échouée : %s", exc)
115
+ raise LLMClientError(f"Erreur réseau vers DeepInfra: {exc}") from exc
116
+
117
+ if resp.status_code >= 400:
118
  logger.error(
119
+ "llm_client: DeepInfra HTTP %d – payload d'erreur: %s",
120
  resp.status_code,
121
+ resp.text[:1000],
 
 
122
  )
123
+ raise LLMClientError(f"DeepInfra renvoie une erreur HTTP {resp.status_code}")
124
 
125
+ data = resp.json()
126
  try:
127
+ choice = data["choices"][0]
128
+ message = choice["message"]
129
+ content = message["content"]
130
+ except Exception as exc: # pragma: no cover
131
+ logger.error("llm_client: format de réponse inattendu: %s", data)
132
+ raise LLMClientError(f"Format de réponse DeepInfra inattendu: {exc}") from exc
133
+
134
+ # Selon l'API, content peut être une chaîne ou une liste de blocs.
135
+ if isinstance(content, str):
136
+ text = content
137
+ elif isinstance(content, list):
138
+ # Concatène tous les segments texte éventuels
139
+ text_parts = []
140
+ for part in content:
141
+ if isinstance(part, dict) and part.get("type") == "text":
142
+ text_parts.append(part.get("text", ""))
143
+ text = "".join(text_parts)
144
+ else:
145
+ raise LLMClientError(
146
+ f"llm_client: type de content inattendu ({type(content)!r}) dans la réponse"
147
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149
  logger.info(
150
+ "llm_client: réponse DeepInfra reçue (len=%d caractères)", len(text)
 
 
151
  )
152
+ logger.debug("llm_client: extrait de la réponse (1k chars max): %s", text[:1000])
153
+ return text