Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,22 @@
|
|
| 1 |
"""
|
| 2 |
RAG Chat API - Gustave Eiffel Hackathon 2026
|
| 3 |
=============================================
|
| 4 |
-
|
| 5 |
Version améliorée :
|
| 6 |
- Chunking fixe conservé
|
| 7 |
- Recherche vectorielle conservée
|
|
|
|
|
|
|
| 8 |
- Query rewriting conditionnel par LLM
|
| 9 |
- Expansion déterministe des acronymes actuariels
|
| 10 |
- Seuil de distance adaptatif
|
| 11 |
- Top-K maximum pour limiter tokens, coût et CO2
|
| 12 |
-
|
| 13 |
Architecture:
|
| 14 |
User Query
|
| 15 |
→ Optional LLM Query Rewriting
|
| 16 |
→ Deterministic Query Expansion
|
| 17 |
→ Embedding
|
| 18 |
-
→ Vector Search
|
|
|
|
| 19 |
→ Adaptive Distance Filtering
|
| 20 |
→ Context Retrieval
|
| 21 |
→ LLM Generation
|
|
@@ -25,7 +26,11 @@ Architecture:
|
|
| 25 |
import os
|
| 26 |
import json
|
| 27 |
import logging
|
|
|
|
|
|
|
| 28 |
import time
|
|
|
|
|
|
|
| 29 |
from pathlib import Path
|
| 30 |
from typing import Optional
|
| 31 |
|
|
@@ -77,10 +82,29 @@ TOP_K_RESULTS = 3
|
|
| 77 |
# Retrieval Configuration
|
| 78 |
# ---------------------------------------------------------------------------
|
| 79 |
|
| 80 |
-
# Nombre de candidats récupérés
|
| 81 |
-
# On
|
| 82 |
RETRIEVAL_CANDIDATES = 8
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
# Seuil de distance par défaut.
|
| 85 |
# Plus le seuil est bas, plus on est strict.
|
| 86 |
DISTANCE_THRESHOLD = 0.60
|
|
@@ -89,7 +113,7 @@ DISTANCE_THRESHOLD = 0.60
|
|
| 89 |
# 2 réduit les tokens / coût / CO2 par rapport à 3.
|
| 90 |
MAX_CONTEXT_CHUNKS = 2
|
| 91 |
|
| 92 |
-
# Si True, quand aucun chunk ne passe
|
| 93 |
# on envoie quand même le meilleur chunk.
|
| 94 |
# Ici on garde False pour éviter les mauvais contextes.
|
| 95 |
FALLBACK_TO_BEST_CHUNK = False
|
|
@@ -166,6 +190,20 @@ collection = chroma_client.get_or_create_collection(
|
|
| 166 |
logger.info(f"ChromaDB collection '{COLLECTION_NAME}' ready. Documents: {collection.count()}")
|
| 167 |
logger.info(f"LLM configured: {LLM_MODEL_NAME} via {LLM_ENDPOINT_URL}")
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
# ---------------------------------------------------------------------------
|
| 171 |
# Helper Functions
|
|
@@ -304,6 +342,297 @@ def add_documents_to_vectorstore(documents: list[dict]) -> int:
|
|
| 304 |
return len(documents)
|
| 305 |
|
| 306 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
# ---------------------------------------------------------------------------
|
| 308 |
# Query Rewriting and Query Expansion
|
| 309 |
# ---------------------------------------------------------------------------
|
|
@@ -332,7 +661,6 @@ def clean_query_words(query: str) -> list[str]:
|
|
| 332 |
def should_rewrite_query(query: str) -> bool:
|
| 333 |
"""
|
| 334 |
Détermine si la question doit être reformulée par LLM.
|
| 335 |
-
|
| 336 |
On limite volontairement le rewriting aux questions courtes ou ambiguës
|
| 337 |
pour éviter d'ajouter un appel LLM inutile à chaque requête.
|
| 338 |
"""
|
|
@@ -363,7 +691,6 @@ def should_rewrite_query(query: str) -> bool:
|
|
| 363 |
def rewrite_query_with_llm(query: str) -> tuple[str, dict]:
|
| 364 |
"""
|
| 365 |
Reformule la question utilisateur pour améliorer la recherche vectorielle.
|
| 366 |
-
|
| 367 |
Important :
|
| 368 |
- La reformulation sert uniquement au retrieval.
|
| 369 |
- La question originale reste utilisée dans le prompt final.
|
|
@@ -385,7 +712,6 @@ def rewrite_query_with_llm(query: str) -> tuple[str, dict]:
|
|
| 385 |
|
| 386 |
rewrite_prompt = f"""
|
| 387 |
Tu reformules une question pour améliorer une recherche dans un corpus de mémoires d'actuariat.
|
| 388 |
-
|
| 389 |
Règles :
|
| 390 |
- Ne réponds pas à la question.
|
| 391 |
- Ne rajoute pas d'information inventée.
|
|
@@ -401,10 +727,8 @@ Règles :
|
|
| 401 |
- Retourne une seule question reformulée, en français.
|
| 402 |
- Maximum 25 mots.
|
| 403 |
- Ne retourne pas de JSON.
|
| 404 |
-
|
| 405 |
Question originale :
|
| 406 |
{query}
|
| 407 |
-
|
| 408 |
Question reformulée :
|
| 409 |
""".strip()
|
| 410 |
|
|
@@ -451,7 +775,6 @@ Question reformulée :
|
|
| 451 |
def expand_query(query: str) -> str:
|
| 452 |
"""
|
| 453 |
Enrichit les acronymes actuariels pour améliorer la recherche vectorielle.
|
| 454 |
-
|
| 455 |
Important :
|
| 456 |
- Cela ne change pas la question envoyée au LLM final.
|
| 457 |
- Cela change seulement la requête utilisée pour chercher les chunks.
|
|
@@ -487,7 +810,6 @@ def build_retrieval_query(query: str) -> tuple[str, dict]:
|
|
| 487 |
Construit la requête utilisée pour le retrieval :
|
| 488 |
1. rewriting LLM conditionnel ;
|
| 489 |
2. expansion déterministe des acronymes.
|
| 490 |
-
|
| 491 |
On retourne aussi les informations de rewriting pour les métriques.
|
| 492 |
"""
|
| 493 |
rewritten_query, rewrite_info = rewrite_query_with_llm(query)
|
|
@@ -501,7 +823,6 @@ def build_retrieval_query(query: str) -> tuple[str, dict]:
|
|
| 501 |
def get_distance_threshold(query: str) -> float:
|
| 502 |
"""
|
| 503 |
Seuil adaptatif selon le type de question.
|
| 504 |
-
|
| 505 |
Idée :
|
| 506 |
- Requêtes très courtes ou acronymes : seuil plus permissif.
|
| 507 |
- Requêtes normales : seuil standard.
|
|
@@ -540,16 +861,13 @@ def retrieve_relevant_context(
|
|
| 540 |
top_k: int = TOP_K_RESULTS,
|
| 541 |
) -> tuple[list[dict], dict]:
|
| 542 |
"""
|
| 543 |
-
Retrieve relevant document chunks with
|
| 544 |
-
adaptive distance threshold.
|
| 545 |
-
|
| 546 |
Différence avec le code de base :
|
| 547 |
-
-
|
| 548 |
-
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
4. on garde seulement ceux dont la distance passe le seuil adaptatif.
|
| 553 |
"""
|
| 554 |
if collection.count() == 0:
|
| 555 |
return [], {
|
|
@@ -572,61 +890,72 @@ def retrieve_relevant_context(
|
|
| 572 |
|
| 573 |
max_contexts = min(top_k or TOP_K_RESULTS, MAX_CONTEXT_CHUNKS)
|
| 574 |
|
| 575 |
-
|
| 576 |
max(RETRIEVAL_CANDIDATES, max_contexts),
|
| 577 |
collection.count(),
|
| 578 |
)
|
| 579 |
|
| 580 |
-
|
| 581 |
query_embeddings=[query_embedding],
|
| 582 |
-
n_results=
|
| 583 |
include=["documents", "metadatas", "distances"],
|
| 584 |
)
|
| 585 |
|
| 586 |
-
|
| 587 |
|
| 588 |
-
for i in range(len(
|
| 589 |
-
distance =
|
| 590 |
-
metadata =
|
| 591 |
|
| 592 |
-
|
| 593 |
-
"text":
|
| 594 |
"source": metadata.get("source", "unknown"),
|
| 595 |
"chunk_index": metadata.get("chunk_index"),
|
| 596 |
"distance": distance,
|
| 597 |
"similarity_score": 1 - distance,
|
| 598 |
-
"
|
|
|
|
| 599 |
})
|
| 600 |
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 604 |
|
| 605 |
filtered_contexts = [
|
| 606 |
-
ctx for ctx in
|
| 607 |
-
if ctx
|
| 608 |
]
|
| 609 |
|
| 610 |
-
# Si aucun chunk ne passe
|
| 611 |
# soit garder le meilleur chunk selon FALLBACK_TO_BEST_CHUNK.
|
| 612 |
-
if not filtered_contexts and FALLBACK_TO_BEST_CHUNK and
|
| 613 |
logger.info(
|
| 614 |
-
f"No chunk passed
|
| 615 |
-
f"
|
| 616 |
)
|
| 617 |
-
filtered_contexts = [
|
| 618 |
|
| 619 |
selected_contexts = filtered_contexts[:max_contexts]
|
| 620 |
|
| 621 |
rewrite_info["effective_threshold"] = effective_threshold
|
| 622 |
-
rewrite_info["
|
|
|
|
|
|
|
|
|
|
| 623 |
rewrite_info["passed_threshold"] = len(filtered_contexts)
|
| 624 |
rewrite_info["selected_contexts"] = len(selected_contexts)
|
| 625 |
|
| 626 |
logger.info(
|
| 627 |
-
f"
|
| 628 |
-
f"
|
| 629 |
-
f"
|
|
|
|
|
|
|
| 630 |
f"selected={len(selected_contexts)}, "
|
| 631 |
f"threshold={effective_threshold}, "
|
| 632 |
f"rewrite_used={rewrite_info.get('query_rewrite_used')}, "
|
|
@@ -636,11 +965,9 @@ def retrieve_relevant_context(
|
|
| 636 |
|
| 637 |
return selected_contexts, rewrite_info
|
| 638 |
|
| 639 |
-
|
| 640 |
def build_rag_prompt(query: str, contexts: list[dict]) -> str:
|
| 641 |
"""
|
| 642 |
Construct the RAG prompt by combining retrieved context with the user question.
|
| 643 |
-
|
| 644 |
La distance n'est pas ajoutée dans le prompt pour économiser quelques tokens.
|
| 645 |
Elle reste disponible dans les sources retournées par l'API.
|
| 646 |
"""
|
|
@@ -762,6 +1089,11 @@ def rag_query(query: str, top_k: int = TOP_K_RESULTS) -> dict:
|
|
| 762 |
"source": ctx["source"],
|
| 763 |
"score": ctx["similarity_score"],
|
| 764 |
"distance": ctx["distance"],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 765 |
"passed_threshold": ctx["passed_threshold"],
|
| 766 |
"chunk_index": ctx.get("chunk_index"),
|
| 767 |
"ref_text": ctx["text"],
|
|
@@ -893,10 +1225,17 @@ async def health_check():
|
|
| 893 |
"documents_in_store": collection.count(),
|
| 894 |
"embedding_model": EMBEDDING_MODEL_NAME,
|
| 895 |
"llm_model": LLM_MODEL_NAME,
|
| 896 |
-
"retrieval_strategy": "
|
| 897 |
"query_rewrite_enabled": QUERY_REWRITE_ENABLED,
|
| 898 |
"query_rewrite_max_words": QUERY_REWRITE_MAX_WORDS,
|
| 899 |
"retrieval_candidates": RETRIEVAL_CANDIDATES,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 900 |
"default_distance_threshold": DISTANCE_THRESHOLD,
|
| 901 |
"max_context_chunks": MAX_CONTEXT_CHUNKS,
|
| 902 |
"fallback_to_best_chunk": FALLBACK_TO_BEST_CHUNK,
|
|
@@ -919,8 +1258,11 @@ def gradio_query(question: str) -> tuple[str, str, str, str, str]:
|
|
| 919 |
sources_text = "\n".join(
|
| 920 |
(
|
| 921 |
f" - {s['source']} "
|
| 922 |
-
f"(
|
| 923 |
-
f"
|
|
|
|
|
|
|
|
|
|
| 924 |
)
|
| 925 |
for s in result["sources"]
|
| 926 |
)
|
|
@@ -968,17 +1310,15 @@ def gradio_ingest(text: str, source_name: str) -> str:
|
|
| 968 |
with gr.Blocks(title="RAG Chat API - Gustave Eiffel Hackathon") as demo:
|
| 969 |
gr.Markdown("""
|
| 970 |
# 🗼 RAG Chat API - Gustave Eiffel Hackathon 2026
|
| 971 |
-
|
| 972 |
This application demonstrates a complete **Retrieval-Augmented Generation (RAG)** system.
|
| 973 |
-
|
| 974 |
**Current improvements:**
|
| 975 |
- Conditional LLM query rewriting for short or ambiguous questions
|
| 976 |
- Deterministic query expansion for actuarial acronyms such as BEL, SCR, GLM, MRH
|
|
|
|
|
|
|
| 977 |
- Vector search with adaptive distance threshold
|
| 978 |
- Fewer context chunks sent to the LLM to reduce tokens, cost and CO2
|
| 979 |
-
|
| 980 |
**API Endpoint:** Use `POST /query` with `{"query": "your question"}` for programmatic access.
|
| 981 |
-
|
| 982 |
---
|
| 983 |
""")
|
| 984 |
|
|
@@ -1040,18 +1380,14 @@ with gr.Blocks(title="RAG Chat API - Gustave Eiffel Hackathon") as demo:
|
|
| 1040 |
with gr.Tab("ℹ️ API Info"):
|
| 1041 |
gr.Markdown("""
|
| 1042 |
## API Endpoints
|
| 1043 |
-
|
| 1044 |
### POST /query
|
| 1045 |
-
|
| 1046 |
```json
|
| 1047 |
{
|
| 1048 |
"query": "BEL",
|
| 1049 |
"top_k": 3
|
| 1050 |
}
|
| 1051 |
```
|
| 1052 |
-
|
| 1053 |
**Response:**
|
| 1054 |
-
|
| 1055 |
```json
|
| 1056 |
{
|
| 1057 |
"answer": "...",
|
|
@@ -1066,18 +1402,14 @@ with gr.Blocks(title="RAG Chat API - Gustave Eiffel Hackathon") as demo:
|
|
| 1066 |
"rewritten_query": "Qu'est-ce que le Best Estimate Liability dans les mémoires d'actuariat ?"
|
| 1067 |
}
|
| 1068 |
```
|
| 1069 |
-
|
| 1070 |
### POST /ingest
|
| 1071 |
-
|
| 1072 |
```json
|
| 1073 |
{
|
| 1074 |
"text": "Your document text here...",
|
| 1075 |
"source": "document_name.txt"
|
| 1076 |
}
|
| 1077 |
```
|
| 1078 |
-
|
| 1079 |
### GET /health
|
| 1080 |
-
|
| 1081 |
Returns system health, document count and retrieval configuration.
|
| 1082 |
""")
|
| 1083 |
|
|
|
|
| 1 |
"""
|
| 2 |
RAG Chat API - Gustave Eiffel Hackathon 2026
|
| 3 |
=============================================
|
|
|
|
| 4 |
Version améliorée :
|
| 5 |
- Chunking fixe conservé
|
| 6 |
- Recherche vectorielle conservée
|
| 7 |
+
- Recherche BM25 locale ajoutée
|
| 8 |
+
- Reranking déterministe sobre ajouté
|
| 9 |
- Query rewriting conditionnel par LLM
|
| 10 |
- Expansion déterministe des acronymes actuariels
|
| 11 |
- Seuil de distance adaptatif
|
| 12 |
- Top-K maximum pour limiter tokens, coût et CO2
|
|
|
|
| 13 |
Architecture:
|
| 14 |
User Query
|
| 15 |
→ Optional LLM Query Rewriting
|
| 16 |
→ Deterministic Query Expansion
|
| 17 |
→ Embedding
|
| 18 |
+
→ Hybrid Vector + BM25 Search
|
| 19 |
+
→ Cheap Deterministic Reranking
|
| 20 |
→ Adaptive Distance Filtering
|
| 21 |
→ Context Retrieval
|
| 22 |
→ LLM Generation
|
|
|
|
| 26 |
import os
|
| 27 |
import json
|
| 28 |
import logging
|
| 29 |
+
import math
|
| 30 |
+
import re
|
| 31 |
import time
|
| 32 |
+
import unicodedata
|
| 33 |
+
from collections import Counter, defaultdict
|
| 34 |
from pathlib import Path
|
| 35 |
from typing import Optional
|
| 36 |
|
|
|
|
| 82 |
# Retrieval Configuration
|
| 83 |
# ---------------------------------------------------------------------------
|
| 84 |
|
| 85 |
+
# Nombre de candidats récupérés par la recherche vectorielle.
|
| 86 |
+
# On reste volontairement bas pour limiter la latence.
|
| 87 |
RETRIEVAL_CANDIDATES = 8
|
| 88 |
|
| 89 |
+
# Nombre de candidats récupérés par BM25.
|
| 90 |
+
# BM25 est local et ne consomme pas de tokens, mais on limite quand même
|
| 91 |
+
# pour garder un reranking rapide.
|
| 92 |
+
BM25_CANDIDATES = 8
|
| 93 |
+
|
| 94 |
+
# Nombre maximum de candidats hybrides rerankés après déduplication.
|
| 95 |
+
RERANK_CANDIDATES_LIMIT = 12
|
| 96 |
+
|
| 97 |
+
# Poids du reranker déterministe.
|
| 98 |
+
# Aucun modèle supplémentaire : coût API nul, CO2 quasi nul côté LLM.
|
| 99 |
+
RERANK_VECTOR_WEIGHT = 0.60
|
| 100 |
+
RERANK_BM25_WEIGHT = 0.30
|
| 101 |
+
RERANK_TERM_COVERAGE_WEIGHT = 0.10
|
| 102 |
+
|
| 103 |
+
# Seuil minimal du score reranké pour accepter un chunk lexicalement pertinent.
|
| 104 |
+
# Garde-fou contre les chunks récupérés par mots-clés trop faibles.
|
| 105 |
+
MIN_RERANK_SCORE = 0.12
|
| 106 |
+
MIN_TERM_COVERAGE = 0.15
|
| 107 |
+
|
| 108 |
# Seuil de distance par défaut.
|
| 109 |
# Plus le seuil est bas, plus on est strict.
|
| 110 |
DISTANCE_THRESHOLD = 0.60
|
|
|
|
| 113 |
# 2 réduit les tokens / coût / CO2 par rapport à 3.
|
| 114 |
MAX_CONTEXT_CHUNKS = 2
|
| 115 |
|
| 116 |
+
# Si True, quand aucun chunk ne passe les filtres hybrides,
|
| 117 |
# on envoie quand même le meilleur chunk.
|
| 118 |
# Ici on garde False pour éviter les mauvais contextes.
|
| 119 |
FALLBACK_TO_BEST_CHUNK = False
|
|
|
|
| 190 |
logger.info(f"ChromaDB collection '{COLLECTION_NAME}' ready. Documents: {collection.count()}")
|
| 191 |
logger.info(f"LLM configured: {LLM_MODEL_NAME} via {LLM_ENDPOINT_URL}")
|
| 192 |
|
| 193 |
+
# Cache global du BM25.
|
| 194 |
+
# Il est reconstruit seulement quand le nombre de chunks change.
|
| 195 |
+
BM25_INDEX_CACHE = {
|
| 196 |
+
"count": -1,
|
| 197 |
+
"ids": [],
|
| 198 |
+
"documents": [],
|
| 199 |
+
"metadatas": [],
|
| 200 |
+
"doc_tokens": [],
|
| 201 |
+
"doc_lengths": [],
|
| 202 |
+
"avgdl": 0.0,
|
| 203 |
+
"idf": {},
|
| 204 |
+
"inverted_index": {},
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
|
| 208 |
# ---------------------------------------------------------------------------
|
| 209 |
# Helper Functions
|
|
|
|
| 342 |
return len(documents)
|
| 343 |
|
| 344 |
|
| 345 |
+
|
| 346 |
+
# ---------------------------------------------------------------------------
|
| 347 |
+
# Lightweight BM25 + Deterministic Reranker
|
| 348 |
+
# ---------------------------------------------------------------------------
|
| 349 |
+
|
| 350 |
+
SEARCH_STOPWORDS = {
|
| 351 |
+
"a", "au", "aux", "avec", "ce", "ces", "cette", "dans", "de", "des",
|
| 352 |
+
"du", "elle", "en", "et", "est", "il", "ils", "je", "la", "le", "les",
|
| 353 |
+
"leur", "leurs", "mais", "ou", "où", "par", "pas", "pour", "que", "qui",
|
| 354 |
+
"sur", "un", "une", "se", "sa", "son", "ses", "the", "of", "and", "to",
|
| 355 |
+
"in", "is", "for", "on", "with", "what", "how", "why",
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def normalize_for_search(text: str) -> str:
|
| 360 |
+
"""
|
| 361 |
+
Normalise un texte pour la recherche lexicale :
|
| 362 |
+
- minuscules ;
|
| 363 |
+
- suppression des accents ;
|
| 364 |
+
- conservation des lettres/chiffres.
|
| 365 |
+
"""
|
| 366 |
+
text = unicodedata.normalize("NFKD", text.lower())
|
| 367 |
+
text = "".join(ch for ch in text if not unicodedata.combining(ch))
|
| 368 |
+
return text
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def tokenize_for_search(text: str) -> list[str]:
|
| 372 |
+
"""
|
| 373 |
+
Tokenisation sobre pour BM25 et le reranking.
|
| 374 |
+
Aucun modèle NLP externe n'est chargé.
|
| 375 |
+
"""
|
| 376 |
+
normalized = normalize_for_search(text)
|
| 377 |
+
tokens = re.findall(r"[a-z0-9]+", normalized)
|
| 378 |
+
|
| 379 |
+
return [
|
| 380 |
+
token for token in tokens
|
| 381 |
+
if token not in SEARCH_STOPWORDS and (len(token) >= 2 or token.isdigit())
|
| 382 |
+
]
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def build_bm25_index_if_needed() -> dict:
|
| 386 |
+
"""
|
| 387 |
+
Construit un index BM25 local à partir des chunks déjà présents dans ChromaDB.
|
| 388 |
+
Sobriété :
|
| 389 |
+
- aucun appel API ;
|
| 390 |
+
- aucun embedding supplémentaire ;
|
| 391 |
+
- reconstruction uniquement si le nombre de chunks change.
|
| 392 |
+
"""
|
| 393 |
+
current_count = collection.count()
|
| 394 |
+
|
| 395 |
+
if BM25_INDEX_CACHE["count"] == current_count:
|
| 396 |
+
return BM25_INDEX_CACHE
|
| 397 |
+
|
| 398 |
+
logger.info(f"Rebuilding BM25 index for {current_count} chunks.")
|
| 399 |
+
|
| 400 |
+
if current_count == 0:
|
| 401 |
+
BM25_INDEX_CACHE.update({
|
| 402 |
+
"count": 0,
|
| 403 |
+
"ids": [],
|
| 404 |
+
"documents": [],
|
| 405 |
+
"metadatas": [],
|
| 406 |
+
"doc_tokens": [],
|
| 407 |
+
"doc_lengths": [],
|
| 408 |
+
"avgdl": 0.0,
|
| 409 |
+
"idf": {},
|
| 410 |
+
"inverted_index": {},
|
| 411 |
+
})
|
| 412 |
+
return BM25_INDEX_CACHE
|
| 413 |
+
|
| 414 |
+
stored = collection.get(include=["documents", "metadatas"])
|
| 415 |
+
ids = stored.get("ids", [])
|
| 416 |
+
documents = stored.get("documents", []) or []
|
| 417 |
+
metadatas = stored.get("metadatas", []) or []
|
| 418 |
+
|
| 419 |
+
doc_tokens = [tokenize_for_search(doc or "") for doc in documents]
|
| 420 |
+
doc_lengths = [len(tokens) for tokens in doc_tokens]
|
| 421 |
+
avgdl = sum(doc_lengths) / max(len(doc_lengths), 1)
|
| 422 |
+
|
| 423 |
+
doc_freq = Counter()
|
| 424 |
+
inverted_index = defaultdict(list)
|
| 425 |
+
|
| 426 |
+
for doc_idx, tokens in enumerate(doc_tokens):
|
| 427 |
+
counts = Counter(tokens)
|
| 428 |
+
|
| 429 |
+
for term, freq in counts.items():
|
| 430 |
+
doc_freq[term] += 1
|
| 431 |
+
inverted_index[term].append((doc_idx, freq))
|
| 432 |
+
|
| 433 |
+
total_docs = len(documents)
|
| 434 |
+
idf = {
|
| 435 |
+
term: math.log(1 + (total_docs - freq + 0.5) / (freq + 0.5))
|
| 436 |
+
for term, freq in doc_freq.items()
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
BM25_INDEX_CACHE.update({
|
| 440 |
+
"count": current_count,
|
| 441 |
+
"ids": ids,
|
| 442 |
+
"documents": documents,
|
| 443 |
+
"metadatas": metadatas,
|
| 444 |
+
"doc_tokens": doc_tokens,
|
| 445 |
+
"doc_lengths": doc_lengths,
|
| 446 |
+
"avgdl": avgdl,
|
| 447 |
+
"idf": idf,
|
| 448 |
+
"inverted_index": dict(inverted_index),
|
| 449 |
+
})
|
| 450 |
+
|
| 451 |
+
return BM25_INDEX_CACHE
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def bm25_search(query: str, top_n: int = BM25_CANDIDATES) -> list[dict]:
|
| 455 |
+
"""
|
| 456 |
+
Recherche BM25 locale.
|
| 457 |
+
BM25 favorise les correspondances exactes de termes, utile pour :
|
| 458 |
+
BEL, SCR, TVOG, GLM, noms de méthodes, formules, etc.
|
| 459 |
+
"""
|
| 460 |
+
index = build_bm25_index_if_needed()
|
| 461 |
+
|
| 462 |
+
if index["count"] == 0:
|
| 463 |
+
return []
|
| 464 |
+
|
| 465 |
+
query_terms = tokenize_for_search(query)
|
| 466 |
+
|
| 467 |
+
if not query_terms:
|
| 468 |
+
return []
|
| 469 |
+
|
| 470 |
+
k1 = 1.2
|
| 471 |
+
b = 0.75
|
| 472 |
+
scores = defaultdict(float)
|
| 473 |
+
unique_terms = set(query_terms)
|
| 474 |
+
|
| 475 |
+
for term in unique_terms:
|
| 476 |
+
postings = index["inverted_index"].get(term, [])
|
| 477 |
+
term_idf = index["idf"].get(term, 0.0)
|
| 478 |
+
|
| 479 |
+
for doc_idx, freq in postings:
|
| 480 |
+
dl = index["doc_lengths"][doc_idx]
|
| 481 |
+
avgdl = index["avgdl"] or 1.0
|
| 482 |
+
denom = freq + k1 * (1 - b + b * dl / avgdl)
|
| 483 |
+
scores[doc_idx] += term_idf * (freq * (k1 + 1)) / max(denom, 1e-9)
|
| 484 |
+
|
| 485 |
+
ranked = sorted(scores.items(), key=lambda item: item[1], reverse=True)[:top_n]
|
| 486 |
+
|
| 487 |
+
results = []
|
| 488 |
+
for doc_idx, score in ranked:
|
| 489 |
+
metadata = index["metadatas"][doc_idx] or {}
|
| 490 |
+
results.append({
|
| 491 |
+
"id": index["ids"][doc_idx],
|
| 492 |
+
"text": index["documents"][doc_idx],
|
| 493 |
+
"source": metadata.get("source", "unknown"),
|
| 494 |
+
"chunk_index": metadata.get("chunk_index"),
|
| 495 |
+
"distance": None,
|
| 496 |
+
"similarity_score": 0.0,
|
| 497 |
+
"bm25_score": score,
|
| 498 |
+
"retrieval_methods": {"bm25"},
|
| 499 |
+
})
|
| 500 |
+
|
| 501 |
+
return results
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def minmax_normalize(values: list[float]) -> list[float]:
|
| 505 |
+
"""
|
| 506 |
+
Normalisation simple entre 0 et 1 pour fusionner des scores hétérogènes.
|
| 507 |
+
"""
|
| 508 |
+
if not values:
|
| 509 |
+
return []
|
| 510 |
+
|
| 511 |
+
min_value = min(values)
|
| 512 |
+
max_value = max(values)
|
| 513 |
+
|
| 514 |
+
if max_value <= min_value:
|
| 515 |
+
return [1.0 if max_value > 0 else 0.0 for _ in values]
|
| 516 |
+
|
| 517 |
+
return [
|
| 518 |
+
(value - min_value) / (max_value - min_value)
|
| 519 |
+
for value in values
|
| 520 |
+
]
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def term_coverage_score(query: str, text: str) -> float:
|
| 524 |
+
"""
|
| 525 |
+
Part des termes importants de la requête retrouvés dans le chunk.
|
| 526 |
+
Sert de petit garde-fou lexical dans le reranking.
|
| 527 |
+
"""
|
| 528 |
+
query_terms = set(tokenize_for_search(query))
|
| 529 |
+
|
| 530 |
+
if not query_terms:
|
| 531 |
+
return 0.0
|
| 532 |
+
|
| 533 |
+
text_terms = set(tokenize_for_search(text))
|
| 534 |
+
return len(query_terms & text_terms) / len(query_terms)
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def merge_candidates(vector_candidates: list[dict], bm25_candidates: list[dict]) -> list[dict]:
|
| 538 |
+
"""
|
| 539 |
+
Fusionne les candidats vectoriels et BM25 sans doublons.
|
| 540 |
+
Clé principale : source + chunk_index.
|
| 541 |
+
Fallback : hash du texte si les métadonnées sont absentes.
|
| 542 |
+
"""
|
| 543 |
+
merged = {}
|
| 544 |
+
|
| 545 |
+
for candidate in vector_candidates + bm25_candidates:
|
| 546 |
+
key = (
|
| 547 |
+
candidate.get("source"),
|
| 548 |
+
candidate.get("chunk_index"),
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
if key[1] is None:
|
| 552 |
+
key = (candidate.get("source"), hash(candidate.get("text", "")))
|
| 553 |
+
|
| 554 |
+
if key not in merged:
|
| 555 |
+
merged[key] = {
|
| 556 |
+
**candidate,
|
| 557 |
+
"bm25_score": candidate.get("bm25_score", 0.0),
|
| 558 |
+
"retrieval_methods": set(candidate.get("retrieval_methods", set())),
|
| 559 |
+
}
|
| 560 |
+
else:
|
| 561 |
+
existing = merged[key]
|
| 562 |
+
|
| 563 |
+
if candidate.get("distance") is not None:
|
| 564 |
+
existing["distance"] = candidate["distance"]
|
| 565 |
+
existing["similarity_score"] = candidate.get("similarity_score", existing.get("similarity_score", 0.0))
|
| 566 |
+
|
| 567 |
+
existing["bm25_score"] = max(
|
| 568 |
+
existing.get("bm25_score", 0.0),
|
| 569 |
+
candidate.get("bm25_score", 0.0),
|
| 570 |
+
)
|
| 571 |
+
existing["retrieval_methods"].update(candidate.get("retrieval_methods", set()))
|
| 572 |
+
|
| 573 |
+
return list(merged.values())
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def rerank_candidates(candidates: list[dict], query: str, effective_threshold: float) -> list[dict]:
|
| 577 |
+
"""
|
| 578 |
+
Reranker déterministe et sobre.
|
| 579 |
+
Il ne charge aucun cross-encoder et ne fait aucun appel LLM.
|
| 580 |
+
Score final = vectoriel + BM25 + couverture lexicale.
|
| 581 |
+
"""
|
| 582 |
+
if not candidates:
|
| 583 |
+
return []
|
| 584 |
+
|
| 585 |
+
vector_scores = [
|
| 586 |
+
max(0.0, candidate.get("similarity_score", 0.0) or 0.0)
|
| 587 |
+
for candidate in candidates
|
| 588 |
+
]
|
| 589 |
+
bm25_scores = [
|
| 590 |
+
max(0.0, candidate.get("bm25_score", 0.0) or 0.0)
|
| 591 |
+
for candidate in candidates
|
| 592 |
+
]
|
| 593 |
+
coverage_scores = [
|
| 594 |
+
term_coverage_score(query, candidate.get("text", ""))
|
| 595 |
+
for candidate in candidates
|
| 596 |
+
]
|
| 597 |
+
|
| 598 |
+
vector_norm = minmax_normalize(vector_scores)
|
| 599 |
+
bm25_norm = minmax_normalize(bm25_scores)
|
| 600 |
+
|
| 601 |
+
reranked = []
|
| 602 |
+
for idx, candidate in enumerate(candidates):
|
| 603 |
+
rerank_score = (
|
| 604 |
+
RERANK_VECTOR_WEIGHT * vector_norm[idx]
|
| 605 |
+
+ RERANK_BM25_WEIGHT * bm25_norm[idx]
|
| 606 |
+
+ RERANK_TERM_COVERAGE_WEIGHT * coverage_scores[idx]
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
distance = candidate.get("distance")
|
| 610 |
+
vector_passed = distance is not None and distance <= effective_threshold
|
| 611 |
+
lexical_passed = (
|
| 612 |
+
bm25_norm[idx] > 0
|
| 613 |
+
and coverage_scores[idx] >= MIN_TERM_COVERAGE
|
| 614 |
+
and rerank_score >= MIN_RERANK_SCORE
|
| 615 |
+
)
|
| 616 |
+
|
| 617 |
+
candidate["rerank_score"] = rerank_score
|
| 618 |
+
candidate["bm25_normalized_score"] = bm25_norm[idx]
|
| 619 |
+
candidate["term_coverage"] = coverage_scores[idx]
|
| 620 |
+
candidate["passed_threshold"] = vector_passed or lexical_passed
|
| 621 |
+
candidate["retrieval_method"] = "+".join(sorted(candidate.get("retrieval_methods", [])))
|
| 622 |
+
|
| 623 |
+
# Valeurs de compatibilité pour l'affichage/API.
|
| 624 |
+
if candidate.get("distance") is None:
|
| 625 |
+
candidate["distance"] = 1.0
|
| 626 |
+
if candidate.get("similarity_score") is None:
|
| 627 |
+
candidate["similarity_score"] = 0.0
|
| 628 |
+
|
| 629 |
+
reranked.append(candidate)
|
| 630 |
+
|
| 631 |
+
reranked.sort(key=lambda x: x["rerank_score"], reverse=True)
|
| 632 |
+
|
| 633 |
+
return reranked[:RERANK_CANDIDATES_LIMIT]
|
| 634 |
+
|
| 635 |
+
|
| 636 |
# ---------------------------------------------------------------------------
|
| 637 |
# Query Rewriting and Query Expansion
|
| 638 |
# ---------------------------------------------------------------------------
|
|
|
|
| 661 |
def should_rewrite_query(query: str) -> bool:
|
| 662 |
"""
|
| 663 |
Détermine si la question doit être reformulée par LLM.
|
|
|
|
| 664 |
On limite volontairement le rewriting aux questions courtes ou ambiguës
|
| 665 |
pour éviter d'ajouter un appel LLM inutile à chaque requête.
|
| 666 |
"""
|
|
|
|
| 691 |
def rewrite_query_with_llm(query: str) -> tuple[str, dict]:
|
| 692 |
"""
|
| 693 |
Reformule la question utilisateur pour améliorer la recherche vectorielle.
|
|
|
|
| 694 |
Important :
|
| 695 |
- La reformulation sert uniquement au retrieval.
|
| 696 |
- La question originale reste utilisée dans le prompt final.
|
|
|
|
| 712 |
|
| 713 |
rewrite_prompt = f"""
|
| 714 |
Tu reformules une question pour améliorer une recherche dans un corpus de mémoires d'actuariat.
|
|
|
|
| 715 |
Règles :
|
| 716 |
- Ne réponds pas à la question.
|
| 717 |
- Ne rajoute pas d'information inventée.
|
|
|
|
| 727 |
- Retourne une seule question reformulée, en français.
|
| 728 |
- Maximum 25 mots.
|
| 729 |
- Ne retourne pas de JSON.
|
|
|
|
| 730 |
Question originale :
|
| 731 |
{query}
|
|
|
|
| 732 |
Question reformulée :
|
| 733 |
""".strip()
|
| 734 |
|
|
|
|
| 775 |
def expand_query(query: str) -> str:
|
| 776 |
"""
|
| 777 |
Enrichit les acronymes actuariels pour améliorer la recherche vectorielle.
|
|
|
|
| 778 |
Important :
|
| 779 |
- Cela ne change pas la question envoyée au LLM final.
|
| 780 |
- Cela change seulement la requête utilisée pour chercher les chunks.
|
|
|
|
| 810 |
Construit la requête utilisée pour le retrieval :
|
| 811 |
1. rewriting LLM conditionnel ;
|
| 812 |
2. expansion déterministe des acronymes.
|
|
|
|
| 813 |
On retourne aussi les informations de rewriting pour les métriques.
|
| 814 |
"""
|
| 815 |
rewritten_query, rewrite_info = rewrite_query_with_llm(query)
|
|
|
|
| 823 |
def get_distance_threshold(query: str) -> float:
|
| 824 |
"""
|
| 825 |
Seuil adaptatif selon le type de question.
|
|
|
|
| 826 |
Idée :
|
| 827 |
- Requêtes très courtes ou acronymes : seuil plus permissif.
|
| 828 |
- Requêtes normales : seuil standard.
|
|
|
|
| 861 |
top_k: int = TOP_K_RESULTS,
|
| 862 |
) -> tuple[list[dict], dict]:
|
| 863 |
"""
|
| 864 |
+
Retrieve relevant document chunks with hybrid retrieval and cheap reranking.
|
|
|
|
|
|
|
| 865 |
Différence avec le code de base :
|
| 866 |
+
- recherche vectorielle conservée ;
|
| 867 |
+
- recherche BM25 locale ajoutée ;
|
| 868 |
+
- fusion des candidats ;
|
| 869 |
+
- reranking déterministe sans modèle supplémentaire ;
|
| 870 |
+
- filtrage par seuil adaptatif.
|
|
|
|
| 871 |
"""
|
| 872 |
if collection.count() == 0:
|
| 873 |
return [], {
|
|
|
|
| 890 |
|
| 891 |
max_contexts = min(top_k or TOP_K_RESULTS, MAX_CONTEXT_CHUNKS)
|
| 892 |
|
| 893 |
+
vector_candidate_count = min(
|
| 894 |
max(RETRIEVAL_CANDIDATES, max_contexts),
|
| 895 |
collection.count(),
|
| 896 |
)
|
| 897 |
|
| 898 |
+
vector_results = collection.query(
|
| 899 |
query_embeddings=[query_embedding],
|
| 900 |
+
n_results=vector_candidate_count,
|
| 901 |
include=["documents", "metadatas", "distances"],
|
| 902 |
)
|
| 903 |
|
| 904 |
+
vector_candidates = []
|
| 905 |
|
| 906 |
+
for i in range(len(vector_results["documents"][0])):
|
| 907 |
+
distance = vector_results["distances"][0][i]
|
| 908 |
+
metadata = vector_results["metadatas"][0][i] or {}
|
| 909 |
|
| 910 |
+
vector_candidates.append({
|
| 911 |
+
"text": vector_results["documents"][0][i],
|
| 912 |
"source": metadata.get("source", "unknown"),
|
| 913 |
"chunk_index": metadata.get("chunk_index"),
|
| 914 |
"distance": distance,
|
| 915 |
"similarity_score": 1 - distance,
|
| 916 |
+
"bm25_score": 0.0,
|
| 917 |
+
"retrieval_methods": {"vector"},
|
| 918 |
})
|
| 919 |
|
| 920 |
+
bm25_candidates = bm25_search(retrieval_query, top_n=BM25_CANDIDATES)
|
| 921 |
+
|
| 922 |
+
merged_candidates = merge_candidates(vector_candidates, bm25_candidates)
|
| 923 |
+
reranked_candidates = rerank_candidates(
|
| 924 |
+
merged_candidates,
|
| 925 |
+
query=retrieval_query,
|
| 926 |
+
effective_threshold=effective_threshold,
|
| 927 |
+
)
|
| 928 |
|
| 929 |
filtered_contexts = [
|
| 930 |
+
ctx for ctx in reranked_candidates
|
| 931 |
+
if ctx.get("passed_threshold")
|
| 932 |
]
|
| 933 |
|
| 934 |
+
# Si aucun chunk ne passe les filtres hybrides, on peut soit ne rien envoyer au LLM,
|
| 935 |
# soit garder le meilleur chunk selon FALLBACK_TO_BEST_CHUNK.
|
| 936 |
+
if not filtered_contexts and FALLBACK_TO_BEST_CHUNK and reranked_candidates:
|
| 937 |
logger.info(
|
| 938 |
+
f"No chunk passed hybrid filters. Falling back to best reranked chunk "
|
| 939 |
+
f"with rerank_score={reranked_candidates[0]['rerank_score']:.4f}."
|
| 940 |
)
|
| 941 |
+
filtered_contexts = [reranked_candidates[0]]
|
| 942 |
|
| 943 |
selected_contexts = filtered_contexts[:max_contexts]
|
| 944 |
|
| 945 |
rewrite_info["effective_threshold"] = effective_threshold
|
| 946 |
+
rewrite_info["vector_candidates"] = len(vector_candidates)
|
| 947 |
+
rewrite_info["bm25_candidates"] = len(bm25_candidates)
|
| 948 |
+
rewrite_info["merged_candidates"] = len(merged_candidates)
|
| 949 |
+
rewrite_info["reranked_candidates"] = len(reranked_candidates)
|
| 950 |
rewrite_info["passed_threshold"] = len(filtered_contexts)
|
| 951 |
rewrite_info["selected_contexts"] = len(selected_contexts)
|
| 952 |
|
| 953 |
logger.info(
|
| 954 |
+
f"Hybrid retrieval with cheap reranking: "
|
| 955 |
+
f"vector={len(vector_candidates)}, "
|
| 956 |
+
f"bm25={len(bm25_candidates)}, "
|
| 957 |
+
f"merged={len(merged_candidates)}, "
|
| 958 |
+
f"passed={len(filtered_contexts)}, "
|
| 959 |
f"selected={len(selected_contexts)}, "
|
| 960 |
f"threshold={effective_threshold}, "
|
| 961 |
f"rewrite_used={rewrite_info.get('query_rewrite_used')}, "
|
|
|
|
| 965 |
|
| 966 |
return selected_contexts, rewrite_info
|
| 967 |
|
|
|
|
| 968 |
def build_rag_prompt(query: str, contexts: list[dict]) -> str:
|
| 969 |
"""
|
| 970 |
Construct the RAG prompt by combining retrieved context with the user question.
|
|
|
|
| 971 |
La distance n'est pas ajoutée dans le prompt pour économiser quelques tokens.
|
| 972 |
Elle reste disponible dans les sources retournées par l'API.
|
| 973 |
"""
|
|
|
|
| 1089 |
"source": ctx["source"],
|
| 1090 |
"score": ctx["similarity_score"],
|
| 1091 |
"distance": ctx["distance"],
|
| 1092 |
+
"bm25_score": ctx.get("bm25_score", 0.0),
|
| 1093 |
+
"bm25_normalized_score": ctx.get("bm25_normalized_score", 0.0),
|
| 1094 |
+
"rerank_score": ctx.get("rerank_score", 0.0),
|
| 1095 |
+
"term_coverage": ctx.get("term_coverage", 0.0),
|
| 1096 |
+
"retrieval_method": ctx.get("retrieval_method", "vector"),
|
| 1097 |
"passed_threshold": ctx["passed_threshold"],
|
| 1098 |
"chunk_index": ctx.get("chunk_index"),
|
| 1099 |
"ref_text": ctx["text"],
|
|
|
|
| 1225 |
"documents_in_store": collection.count(),
|
| 1226 |
"embedding_model": EMBEDDING_MODEL_NAME,
|
| 1227 |
"llm_model": LLM_MODEL_NAME,
|
| 1228 |
+
"retrieval_strategy": "hybrid_vector_bm25_plus_deterministic_reranker_plus_adaptive_distance_threshold",
|
| 1229 |
"query_rewrite_enabled": QUERY_REWRITE_ENABLED,
|
| 1230 |
"query_rewrite_max_words": QUERY_REWRITE_MAX_WORDS,
|
| 1231 |
"retrieval_candidates": RETRIEVAL_CANDIDATES,
|
| 1232 |
+
"bm25_candidates": BM25_CANDIDATES,
|
| 1233 |
+
"rerank_candidates_limit": RERANK_CANDIDATES_LIMIT,
|
| 1234 |
+
"rerank_weights": {
|
| 1235 |
+
"vector": RERANK_VECTOR_WEIGHT,
|
| 1236 |
+
"bm25": RERANK_BM25_WEIGHT,
|
| 1237 |
+
"term_coverage": RERANK_TERM_COVERAGE_WEIGHT,
|
| 1238 |
+
},
|
| 1239 |
"default_distance_threshold": DISTANCE_THRESHOLD,
|
| 1240 |
"max_context_chunks": MAX_CONTEXT_CHUNKS,
|
| 1241 |
"fallback_to_best_chunk": FALLBACK_TO_BEST_CHUNK,
|
|
|
|
| 1258 |
sources_text = "\n".join(
|
| 1259 |
(
|
| 1260 |
f" - {s['source']} "
|
| 1261 |
+
f"(method: {s.get('retrieval_method', 'vector')}, "
|
| 1262 |
+
f"distance: {s.get('distance', 0):.4f}, "
|
| 1263 |
+
f"vector: {s.get('score', 0):.4f}, "
|
| 1264 |
+
f"bm25: {s.get('bm25_score', 0):.4f}, "
|
| 1265 |
+
f"rerank: {s.get('rerank_score', 0):.4f})"
|
| 1266 |
)
|
| 1267 |
for s in result["sources"]
|
| 1268 |
)
|
|
|
|
| 1310 |
with gr.Blocks(title="RAG Chat API - Gustave Eiffel Hackathon") as demo:
|
| 1311 |
gr.Markdown("""
|
| 1312 |
# 🗼 RAG Chat API - Gustave Eiffel Hackathon 2026
|
|
|
|
| 1313 |
This application demonstrates a complete **Retrieval-Augmented Generation (RAG)** system.
|
|
|
|
| 1314 |
**Current improvements:**
|
| 1315 |
- Conditional LLM query rewriting for short or ambiguous questions
|
| 1316 |
- Deterministic query expansion for actuarial acronyms such as BEL, SCR, GLM, MRH
|
| 1317 |
+
- Hybrid vector + BM25 search
|
| 1318 |
+
- Cheap deterministic reranking, without extra LLM call
|
| 1319 |
- Vector search with adaptive distance threshold
|
| 1320 |
- Fewer context chunks sent to the LLM to reduce tokens, cost and CO2
|
|
|
|
| 1321 |
**API Endpoint:** Use `POST /query` with `{"query": "your question"}` for programmatic access.
|
|
|
|
| 1322 |
---
|
| 1323 |
""")
|
| 1324 |
|
|
|
|
| 1380 |
with gr.Tab("ℹ️ API Info"):
|
| 1381 |
gr.Markdown("""
|
| 1382 |
## API Endpoints
|
|
|
|
| 1383 |
### POST /query
|
|
|
|
| 1384 |
```json
|
| 1385 |
{
|
| 1386 |
"query": "BEL",
|
| 1387 |
"top_k": 3
|
| 1388 |
}
|
| 1389 |
```
|
|
|
|
| 1390 |
**Response:**
|
|
|
|
| 1391 |
```json
|
| 1392 |
{
|
| 1393 |
"answer": "...",
|
|
|
|
| 1402 |
"rewritten_query": "Qu'est-ce que le Best Estimate Liability dans les mémoires d'actuariat ?"
|
| 1403 |
}
|
| 1404 |
```
|
|
|
|
| 1405 |
### POST /ingest
|
|
|
|
| 1406 |
```json
|
| 1407 |
{
|
| 1408 |
"text": "Your document text here...",
|
| 1409 |
"source": "document_name.txt"
|
| 1410 |
}
|
| 1411 |
```
|
|
|
|
| 1412 |
### GET /health
|
|
|
|
| 1413 |
Returns system health, document count and retrieval configuration.
|
| 1414 |
""")
|
| 1415 |
|