amogaddy commited on
Commit
aa8f481
Β·
verified Β·
1 Parent(s): 01c9829

Sync aggiornamento

Browse files
Files changed (1) hide show
  1. brain.py +19 -5
brain.py CHANGED
@@ -119,15 +119,21 @@ class Brain:
119
 
120
  log.info("Brain pronto. ModalitΓ : %s", "LLM+KB" if self._hf else "KB+Web")
121
 
122
- async def ask(self, question: str) -> tuple[str, str]:
123
  """
124
  Returns (answer, status).
125
- status: "local" | "searched" | "archived" | "unknown" | "error" | "llm"
 
126
  """
 
 
 
 
127
  self._last_doc_id = None
128
  log.info("Domanda: %r", question)
129
 
130
  # ── 1. Ricerca KB locale ───────────────────────────────────────────────
 
131
  try:
132
  results = _rerank(self.kb.search(question, n_results=12), question)
133
  except Exception as e:
@@ -141,27 +147,31 @@ class Brain:
141
  best = results[0]
142
  best_context = best["answer"]
143
  best_source = best["metadata"].get("source", "")
 
144
  log.info("Match KB locale (score=%.3f)", results[0]["score"])
145
 
146
- # Se c'Γ¨ un LLM, usa il contesto KB per generare una risposta migliore
147
  if self._hf:
 
148
  return await self._llm_answer(question, best_context, best_source, status="llm")
149
 
150
  answer = _extract_sentences(best_context, question)
151
  if best_source and best_source != "grammatica_italiana":
152
  answer += f"\n\n*Fonte: {best_source}*"
 
153
  return answer, "local"
154
 
155
  # ── 2. Ricerca web ─────────────────────────────────────────────────────
156
- log.info("Nessun match locale β€” ricerca web...")
157
  try:
158
  web_results = await asyncio.to_thread(search_and_extract, question)
159
  except Exception as e:
160
  err = GenerAIError(ErrorCode.BRAIN_ASK_FAILED, f"Ricerca web fallita: {fmt_exc(e)}", cause=e)
161
  err.log(log)
 
162
  return err.user_message(), "error"
163
 
164
  if not web_results:
 
165
  log.warning("Nessun risultato web per: %r", question)
166
  return (
167
  "Non ho trovato informazioni su questo argomento nel mio database nΓ© sul web. "
@@ -169,18 +179,22 @@ class Brain:
169
  "unknown",
170
  )
171
 
 
172
  combined = "\n\n---\n\n".join(f"[{r['title']}]\n{r['text']}" for r in web_results)
173
  sources = ", ".join(r["url"] for r in web_results if r.get("url"))
174
 
175
- # ── 3. Genera risposta (LLM o estrazione testuale) ─────────────────────
176
  if self._hf:
 
177
  answer, status = await self._llm_answer(question, combined, sources, status="llm")
178
  else:
 
179
  answer = _extract_sentences(combined, question)
180
  if sources:
181
  answer += f"\n\n*Fonte: {sources}*"
182
  status = "searched"
183
 
 
184
  return answer, status
185
 
186
  async def _llm_answer(
 
119
 
120
  log.info("Brain pronto. ModalitΓ : %s", "LLM+KB" if self._hf else "KB+Web")
121
 
122
+ async def ask(self, question: str, on_status=None) -> tuple[str, str]:
123
  """
124
  Returns (answer, status).
125
+ on_status: callable opzionale async(msg: str) per aggiornamenti in tempo reale.
126
+ status: "local" | "searched" | "unknown" | "error" | "llm"
127
  """
128
+ async def emit(msg: str):
129
+ if on_status:
130
+ await on_status(msg)
131
+
132
  self._last_doc_id = None
133
  log.info("Domanda: %r", question)
134
 
135
  # ── 1. Ricerca KB locale ───────────────────────────────────────────────
136
+ await emit("πŸ” Cerco nella memoria locale...")
137
  try:
138
  results = _rerank(self.kb.search(question, n_results=12), question)
139
  except Exception as e:
 
147
  best = results[0]
148
  best_context = best["answer"]
149
  best_source = best["metadata"].get("source", "")
150
+ await emit(f"βœ… Trovato in memoria locale (score: {results[0]['score']:.2f})")
151
  log.info("Match KB locale (score=%.3f)", results[0]["score"])
152
 
 
153
  if self._hf:
154
+ await emit("πŸ€– Genero risposta con LLM...")
155
  return await self._llm_answer(question, best_context, best_source, status="llm")
156
 
157
  answer = _extract_sentences(best_context, question)
158
  if best_source and best_source != "grammatica_italiana":
159
  answer += f"\n\n*Fonte: {best_source}*"
160
+ await emit("πŸ’¬ Risposta pronta!")
161
  return answer, "local"
162
 
163
  # ── 2. Ricerca web ─────────────────────────────────────────────────────
164
+ await emit("🌐 Non trovato in memoria β€” ricerca sul web...")
165
  try:
166
  web_results = await asyncio.to_thread(search_and_extract, question)
167
  except Exception as e:
168
  err = GenerAIError(ErrorCode.BRAIN_ASK_FAILED, f"Ricerca web fallita: {fmt_exc(e)}", cause=e)
169
  err.log(log)
170
+ await emit(f"❌ Errore ricerca web: {fmt_exc(e)}")
171
  return err.user_message(), "error"
172
 
173
  if not web_results:
174
+ await emit("⚠️ Nessun risultato trovato sul web")
175
  log.warning("Nessun risultato web per: %r", question)
176
  return (
177
  "Non ho trovato informazioni su questo argomento nel mio database nΓ© sul web. "
 
179
  "unknown",
180
  )
181
 
182
+ await emit(f"πŸ“„ Trovati {len(web_results)} risultati β€” estraggo il testo...")
183
  combined = "\n\n---\n\n".join(f"[{r['title']}]\n{r['text']}" for r in web_results)
184
  sources = ", ".join(r["url"] for r in web_results if r.get("url"))
185
 
186
+ # ── 3. Genera risposta ─────────────────────────────────────────────────
187
  if self._hf:
188
+ await emit("πŸ€– Genero risposta con LLM...")
189
  answer, status = await self._llm_answer(question, combined, sources, status="llm")
190
  else:
191
+ await emit("βœ‚οΈ Estraggo le frasi piΓΉ rilevanti...")
192
  answer = _extract_sentences(combined, question)
193
  if sources:
194
  answer += f"\n\n*Fonte: {sources}*"
195
  status = "searched"
196
 
197
+ await emit("πŸ’¬ Risposta pronta!")
198
  return answer, status
199
 
200
  async def _llm_answer(