Spaces:
Sleeping
Sleeping
query rewriting, expansion des acronymes, seuil distance, top_k
Browse files
app.py
CHANGED
|
@@ -2,17 +2,24 @@
|
|
| 2 |
RAG Chat API - Gustave Eiffel Hackathon 2026
|
| 3 |
=============================================
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
5. End-to-end RAG pipeline: ingest → embed → retrieve → generate
|
| 13 |
|
| 14 |
Architecture:
|
| 15 |
-
User Query
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
"""
|
| 17 |
|
| 18 |
import os
|
|
@@ -23,7 +30,7 @@ from pathlib import Path
|
|
| 23 |
from typing import Optional
|
| 24 |
|
| 25 |
# Must be set before chromadb is imported so the module never registers its
|
| 26 |
-
# posthog telemetry hook
|
| 27 |
os.environ.setdefault("ANONYMIZED_TELEMETRY", "False")
|
| 28 |
|
| 29 |
import requests as http_requests
|
|
@@ -38,90 +45,125 @@ from pypdf import PdfReader
|
|
| 38 |
|
| 39 |
from llm import call_llm as call_llm_with_metrics
|
| 40 |
|
|
|
|
| 41 |
logging.basicConfig(level=logging.INFO)
|
| 42 |
logger = logging.getLogger(__name__)
|
| 43 |
|
| 44 |
-
# Suppress non-fatal chromadb telemetry errors
|
| 45 |
logging.getLogger("chromadb.telemetry.product.posthog").setLevel(logging.CRITICAL)
|
| 46 |
|
|
|
|
| 47 |
# ---------------------------------------------------------------------------
|
| 48 |
# Configuration
|
| 49 |
# ---------------------------------------------------------------------------
|
| 50 |
|
| 51 |
-
# Resolve the data directory: /data when running inside HF Spaces
|
| 52 |
# ./data for local development.
|
| 53 |
DATA_DIR = Path("/data") if Path("/data").is_dir() else Path("./data")
|
| 54 |
|
| 55 |
CHROMA_PERSIST_DIR = str(DATA_DIR / "chroma_db")
|
| 56 |
TRAIN_DOCS_DIR = Path("./train_data")
|
| 57 |
COLLECTION_NAME = "rag_documents"
|
|
|
|
|
|
|
| 58 |
CHUNK_SIZE = 512
|
| 59 |
CHUNK_OVERLAP = 50
|
|
|
|
|
|
|
| 60 |
TOP_K_RESULTS = 3
|
| 61 |
|
| 62 |
-
|
| 63 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
_CONFIG_PATH = DATA_DIR / "config.json"
|
| 65 |
if not _CONFIG_PATH.exists():
|
| 66 |
_CONFIG_PATH = Path(__file__).parent / "config.json"
|
| 67 |
logger.warning(
|
| 68 |
-
f"No config.json found in {DATA_DIR} — falling back to root config.json
|
| 69 |
"Copy config.json to the data directory and fill in your values for production use."
|
| 70 |
)
|
|
|
|
| 71 |
with open(_CONFIG_PATH, encoding="utf-8") as _f:
|
| 72 |
_config = json.load(_f)
|
| 73 |
|
| 74 |
-
# Embedding model
|
| 75 |
EMBEDDING_ENDPOINT_URL = _config["embedding"]["endpoint_url"]
|
| 76 |
EMBEDDING_MODEL_NAME = _config["embedding"]["model"]
|
| 77 |
|
| 78 |
-
# LLM
|
| 79 |
LLM_ENDPOINT_URL = _config["llm"]["endpoint_url"]
|
| 80 |
LLM_MODEL_NAME = _config["llm"]["model"]
|
| 81 |
LLM_MAX_TOKENS = _config["llm"].get("max_completion_tokens", 512)
|
| 82 |
LLM_TEMPERATURE = _config["llm"].get("temperature", 0.7)
|
| 83 |
LLM_TOP_P = _config["llm"].get("top_p", 0.95)
|
| 84 |
|
| 85 |
-
# Azure API key from environment variable
|
| 86 |
AZURE_API_KEY = os.environ.get("AZURE_API_KEY")
|
| 87 |
if not AZURE_API_KEY:
|
| 88 |
logger.warning("AZURE_API_KEY is not set — LLM and embedding calls will fail.")
|
| 89 |
|
| 90 |
-
# Prompt template
|
| 91 |
_PROMPT_TEMPLATE_PATH = Path(__file__).parent / "prompts" / "rag_prompt.txt"
|
| 92 |
RAG_PROMPT_TEMPLATE = _PROMPT_TEMPLATE_PATH.read_text(encoding="utf-8")
|
| 93 |
|
| 94 |
-
# ---------------------------------------------------------------------------
|
| 95 |
-
# Step 1: Embedding via Azure OpenAI
|
| 96 |
-
# ---------------------------------------------------------------------------
|
| 97 |
-
# Embeddings are generated by calling the Azure OpenAI /embeddings endpoint.
|
| 98 |
-
# No local model is loaded — the API handles all inference.
|
| 99 |
-
|
| 100 |
logger.info(f"Embedding model configured: {EMBEDDING_MODEL_NAME} via Azure OpenAI")
|
| 101 |
|
|
|
|
| 102 |
# ---------------------------------------------------------------------------
|
| 103 |
-
#
|
| 104 |
# ---------------------------------------------------------------------------
|
| 105 |
-
# ChromaDB runs in-process with persistent storage. This is ideal for HF Spaces
|
| 106 |
-
# because it requires no external database service.
|
| 107 |
|
| 108 |
logger.info(f"Initializing ChromaDB at: {CHROMA_PERSIST_DIR}")
|
|
|
|
| 109 |
chroma_client = chromadb.PersistentClient(
|
| 110 |
path=CHROMA_PERSIST_DIR,
|
| 111 |
settings=Settings(anonymized_telemetry=False),
|
| 112 |
)
|
|
|
|
| 113 |
collection = chroma_client.get_or_create_collection(
|
| 114 |
name=COLLECTION_NAME,
|
| 115 |
metadata={"hnsw:space": "cosine"},
|
| 116 |
)
|
| 117 |
-
logger.info(f"ChromaDB collection '{COLLECTION_NAME}' ready. Documents: {collection.count()}")
|
| 118 |
-
|
| 119 |
-
# ---------------------------------------------------------------------------
|
| 120 |
-
# Step 3: LLM Configuration (Azure Foundry GPT-5)
|
| 121 |
-
# ---------------------------------------------------------------------------
|
| 122 |
-
# We call the Azure OpenAI-compatible endpoint directly via requests.
|
| 123 |
-
# Endpoint URL and model are configured in config.json.
|
| 124 |
|
|
|
|
| 125 |
logger.info(f"LLM configured: {LLM_MODEL_NAME} via {LLM_ENDPOINT_URL}")
|
| 126 |
|
| 127 |
|
|
@@ -132,80 +174,102 @@ logger.info(f"LLM configured: {LLM_MODEL_NAME} via {LLM_ENDPOINT_URL}")
|
|
| 132 |
def extract_text_from_pdf(pdf_path: Path) -> str:
|
| 133 |
"""
|
| 134 |
Extract text content from a PDF file using pypdf.
|
| 135 |
-
|
| 136 |
-
This demonstrates how to convert PDF documents into plain text
|
| 137 |
-
for downstream embedding. Each page is extracted sequentially
|
| 138 |
-
and concatenated with page separators for traceability.
|
| 139 |
"""
|
| 140 |
reader = PdfReader(str(pdf_path))
|
| 141 |
pages_text = []
|
| 142 |
|
| 143 |
for page_num, page in enumerate(reader.pages, start=1):
|
| 144 |
text = page.extract_text()
|
|
|
|
| 145 |
if text and text.strip():
|
| 146 |
pages_text.append(f"[Page {page_num}]\n{text.strip()}")
|
| 147 |
|
| 148 |
full_text = "\n\n".join(pages_text)
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
return full_text
|
| 151 |
|
| 152 |
|
| 153 |
def chunk_text(text: str, source: str = "unknown") -> list[dict]:
|
| 154 |
"""
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
We use LangChain's RecursiveCharacterTextSplitter which intelligently
|
| 158 |
-
splits on paragraph/sentence boundaries to preserve semantic meaning.
|
| 159 |
"""
|
| 160 |
splitter = RecursiveCharacterTextSplitter(
|
| 161 |
chunk_size=CHUNK_SIZE,
|
| 162 |
chunk_overlap=CHUNK_OVERLAP,
|
| 163 |
separators=["\n\n", "\n", ". ", " ", ""],
|
| 164 |
)
|
|
|
|
| 165 |
chunks = splitter.split_text(text)
|
| 166 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
|
| 168 |
|
| 169 |
def generate_embeddings(texts: list[str]) -> list[list[float]]:
|
| 170 |
"""
|
| 171 |
Generate vector embeddings via the Azure OpenAI /embeddings endpoint.
|
| 172 |
-
|
| 173 |
-
The endpoint, model name, and API key are loaded from config.json
|
| 174 |
-
and the AZURE_API_KEY environment variable.
|
| 175 |
"""
|
| 176 |
headers = {
|
| 177 |
"api-key": AZURE_API_KEY,
|
| 178 |
"Content-Type": "application/json",
|
| 179 |
}
|
|
|
|
| 180 |
payload = {
|
| 181 |
"input": texts,
|
| 182 |
"model": EMBEDDING_MODEL_NAME,
|
| 183 |
}
|
|
|
|
| 184 |
try:
|
| 185 |
resp = http_requests.post(
|
| 186 |
-
EMBEDDING_ENDPOINT_URL,
|
|
|
|
|
|
|
|
|
|
| 187 |
)
|
| 188 |
resp.raise_for_status()
|
| 189 |
data = resp.json()
|
| 190 |
return [item["embedding"] for item in data["data"]]
|
|
|
|
| 191 |
except http_requests.exceptions.HTTPError as e:
|
| 192 |
logger.error(f"Embedding API call failed: {e} — {resp.text}")
|
| 193 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
except (http_requests.exceptions.JSONDecodeError, ValueError) as e:
|
| 195 |
-
logger.error(
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
except (KeyError, IndexError) as e:
|
| 198 |
logger.error(f"Unexpected embedding response format: {e} — body: {resp.text}")
|
| 199 |
-
raise HTTPException(
|
|
|
|
|
|
|
|
|
|
| 200 |
|
| 201 |
|
| 202 |
def add_documents_to_vectorstore(documents: list[dict]) -> int:
|
| 203 |
"""
|
| 204 |
Save document embeddings to the ChromaDB vector store.
|
| 205 |
-
|
| 206 |
-
This demonstrates Step 2c: How to persist embeddings for retrieval.
|
| 207 |
-
Each document gets a unique ID, its embedding vector, the raw text,
|
| 208 |
-
and metadata (source file, chunk index).
|
| 209 |
"""
|
| 210 |
if not documents:
|
| 211 |
return 0
|
|
@@ -214,8 +278,19 @@ def add_documents_to_vectorstore(documents: list[dict]) -> int:
|
|
| 214 |
embeddings = generate_embeddings(texts)
|
| 215 |
|
| 216 |
existing_count = collection.count()
|
| 217 |
-
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
collection.add(
|
| 221 |
ids=ids,
|
|
@@ -225,94 +300,410 @@ def add_documents_to_vectorstore(documents: list[dict]) -> int:
|
|
| 225 |
)
|
| 226 |
|
| 227 |
logger.info(f"Added {len(documents)} chunks to vector store. Total: {collection.count()}")
|
|
|
|
| 228 |
return len(documents)
|
| 229 |
|
| 230 |
|
| 231 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
"""
|
| 233 |
-
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
"""
|
| 240 |
if collection.count() == 0:
|
| 241 |
-
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 242 |
|
| 243 |
-
|
|
|
|
|
|
|
|
|
|
| 244 |
|
| 245 |
results = collection.query(
|
| 246 |
query_embeddings=[query_embedding],
|
| 247 |
-
n_results=
|
| 248 |
include=["documents", "metadatas", "distances"],
|
| 249 |
)
|
| 250 |
|
| 251 |
-
|
|
|
|
| 252 |
for i in range(len(results["documents"][0])):
|
| 253 |
-
|
|
|
|
|
|
|
|
|
|
| 254 |
"text": results["documents"][0][i],
|
| 255 |
-
"source":
|
| 256 |
-
"
|
|
|
|
|
|
|
|
|
|
| 257 |
})
|
| 258 |
|
| 259 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
|
| 262 |
def build_rag_prompt(query: str, contexts: list[dict]) -> str:
|
| 263 |
"""
|
| 264 |
Construct the RAG prompt by combining retrieved context with the user question.
|
| 265 |
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
- Acknowledge when information is insufficient
|
| 269 |
-
- Cite sources when possible
|
| 270 |
"""
|
| 271 |
context_text = "\n\n".join(
|
| 272 |
-
f"[Source: {ctx['source']}]\n{ctx['text']}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
)
|
| 274 |
|
| 275 |
-
prompt = RAG_PROMPT_TEMPLATE.format(context=context_text, question=query)
|
| 276 |
return prompt
|
| 277 |
|
| 278 |
|
| 279 |
def rag_query(query: str, top_k: int = TOP_K_RESULTS) -> dict:
|
| 280 |
"""
|
| 281 |
-
End-to-end RAG pipeline
|
| 282 |
-
|
| 283 |
-
This demonstrates Step 2d: How to make a RAG system end-to-end.
|
| 284 |
-
|
| 285 |
-
Pipeline steps:
|
| 286 |
-
1. Receive user query
|
| 287 |
-
2. Retrieve relevant context from vector store
|
| 288 |
-
3. Build augmented prompt with context
|
| 289 |
-
4. Call LLM to generate answer
|
| 290 |
-
5. Return answer with source metadata, explanation, token count, and timing
|
| 291 |
"""
|
| 292 |
start_time = time.perf_counter()
|
| 293 |
|
| 294 |
-
|
| 295 |
-
contexts = retrieve_relevant_context(query, top_k=top_k)
|
| 296 |
|
| 297 |
if not contexts:
|
| 298 |
elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
return {
|
| 300 |
-
"answer":
|
| 301 |
"sources": [],
|
| 302 |
-
"explanation":
|
| 303 |
-
"total_token":
|
| 304 |
-
"prompt_tokens": 0,
|
| 305 |
-
"completion_tokens": 0,
|
| 306 |
"cached_tokens": 0,
|
| 307 |
-
"
|
| 308 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 309 |
"run_time_in_ms": elapsed_ms,
|
| 310 |
}
|
| 311 |
|
| 312 |
-
# Step 2: Build the augmented prompt
|
| 313 |
prompt = build_rag_prompt(query, contexts)
|
| 314 |
|
| 315 |
-
# Step 3: Generate answer from LLM (with token + CO2 metrics)
|
| 316 |
llm_result = call_llm_with_metrics(
|
| 317 |
prompt,
|
| 318 |
endpoint_url=LLM_ENDPOINT_URL,
|
|
@@ -322,12 +713,17 @@ def rag_query(query: str, top_k: int = TOP_K_RESULTS) -> dict:
|
|
| 322 |
temperature=LLM_TEMPERATURE,
|
| 323 |
top_p=LLM_TOP_P,
|
| 324 |
)
|
|
|
|
| 325 |
raw_content = llm_result["content"]
|
| 326 |
tokens = llm_result["tokens"]
|
| 327 |
-
total_token = tokens["total"]
|
| 328 |
|
| 329 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
json_str = raw_content.strip()
|
|
|
|
| 331 |
if json_str.startswith("```"):
|
| 332 |
json_str = json_str.split("\n", 1)[-1]
|
| 333 |
json_str = json_str.rsplit("```", 1)[0].strip()
|
|
@@ -342,28 +738,67 @@ def rag_query(query: str, top_k: int = TOP_K_RESULTS) -> dict:
|
|
| 342 |
|
| 343 |
elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
|
| 344 |
|
| 345 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
return {
|
| 347 |
"answer": answer,
|
| 348 |
-
"sources": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
"explanation": explanation,
|
|
|
|
|
|
|
| 350 |
"total_token": total_token,
|
| 351 |
-
"prompt_tokens": tokens["prompt"],
|
| 352 |
-
"completion_tokens": tokens["completion"],
|
| 353 |
"cached_tokens": tokens["cached"],
|
| 354 |
-
|
| 355 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 356 |
"run_time_in_ms": elapsed_ms,
|
| 357 |
}
|
| 358 |
|
| 359 |
|
| 360 |
# ---------------------------------------------------------------------------
|
| 361 |
-
#
|
| 362 |
# ---------------------------------------------------------------------------
|
| 363 |
|
| 364 |
-
|
| 365 |
def ingest_train_documents():
|
| 366 |
-
"""
|
|
|
|
|
|
|
| 367 |
if collection.count() > 0:
|
| 368 |
logger.info("Vector store already has documents, skipping ingestion.")
|
| 369 |
return
|
|
@@ -372,28 +807,32 @@ def ingest_train_documents():
|
|
| 372 |
logger.warning(f"No train_data directory found at: {TRAIN_DOCS_DIR}")
|
| 373 |
return
|
| 374 |
|
| 375 |
-
|
|
|
|
| 376 |
for file_path in TRAIN_DOCS_DIR.rglob("*.txt"):
|
| 377 |
logger.info(f"Ingesting text file: {file_path.name}")
|
| 378 |
-
text = file_path.read_text(encoding="utf-8")
|
| 379 |
chunks = chunk_text(text, source=file_path.name)
|
| 380 |
-
add_documents_to_vectorstore(chunks)
|
| 381 |
|
| 382 |
-
# Ingest PDF files (recursively in subdirectories)
|
| 383 |
for file_path in TRAIN_DOCS_DIR.rglob("*.pdf"):
|
| 384 |
logger.info(f"Ingesting PDF file: {file_path.name}")
|
| 385 |
text = extract_text_from_pdf(file_path)
|
|
|
|
| 386 |
if text.strip():
|
| 387 |
chunks = chunk_text(text, source=file_path.name)
|
| 388 |
-
add_documents_to_vectorstore(chunks)
|
| 389 |
else:
|
| 390 |
logger.warning(f"No extractable text found in: {file_path.name}")
|
| 391 |
|
| 392 |
-
logger.info(
|
|
|
|
|
|
|
|
|
|
| 393 |
|
| 394 |
|
| 395 |
# ---------------------------------------------------------------------------
|
| 396 |
-
#
|
| 397 |
# ---------------------------------------------------------------------------
|
| 398 |
|
| 399 |
app = FastAPI(
|
|
@@ -404,13 +843,17 @@ app = FastAPI(
|
|
| 404 |
|
| 405 |
|
| 406 |
class QueryRequest(BaseModel):
|
| 407 |
-
"""
|
|
|
|
|
|
|
| 408 |
query: str
|
| 409 |
top_k: Optional[int] = TOP_K_RESULTS
|
| 410 |
|
| 411 |
|
| 412 |
class IngestRequest(BaseModel):
|
| 413 |
-
"""
|
|
|
|
|
|
|
| 414 |
text: str
|
| 415 |
source: str = "user_upload"
|
| 416 |
|
|
@@ -418,27 +861,9 @@ class IngestRequest(BaseModel):
|
|
| 418 |
@app.post("/query")
|
| 419 |
async def query_endpoint(request: QueryRequest):
|
| 420 |
"""
|
| 421 |
-
RAG Query Endpoint
|
| 422 |
-
|
| 423 |
-
Accepts a user query, retrieves relevant context from the vector store,
|
| 424 |
-
and generates an answer using the LLM.
|
| 425 |
-
|
| 426 |
-
Request body:
|
| 427 |
-
- query (str): The user's question
|
| 428 |
-
- top_k (int, optional): Number of context chunks to retrieve (default: 3)
|
| 429 |
-
|
| 430 |
-
Returns:
|
| 431 |
-
- answer (str): The generated answer
|
| 432 |
-
- sources (list): Source documents used for context
|
| 433 |
-
- explanation (str): Explanation of the retrieval and answer logic
|
| 434 |
-
- total_token (int): Total token count from the LLM call
|
| 435 |
-
- prompt_tokens (int): Prompt token count
|
| 436 |
-
- completion_tokens (int): Completion token count
|
| 437 |
-
- cached_tokens (int): Cached prompt tokens (when reported by provider)
|
| 438 |
-
- co2_grams (float | None): Estimated CO2 emission in grams (via ecologits)
|
| 439 |
-
- energy_kwh (float | None): Estimated energy use in kWh (via ecologits)
|
| 440 |
-
- run_time_in_ms (float): Pipeline execution time in milliseconds
|
| 441 |
"""
|
|
|
|
| 442 |
result = rag_query(request.query, top_k=request.top_k)
|
| 443 |
return JSONResponse(content=result)
|
| 444 |
|
|
@@ -447,15 +872,10 @@ async def query_endpoint(request: QueryRequest):
|
|
| 447 |
async def ingest_endpoint(request: IngestRequest):
|
| 448 |
"""
|
| 449 |
Document Ingestion Endpoint.
|
| 450 |
-
|
| 451 |
-
Accepts raw text, chunks it, generates embeddings, and stores in the vector store.
|
| 452 |
-
|
| 453 |
-
Request body:
|
| 454 |
-
- text (str): The document text to ingest
|
| 455 |
-
- source (str, optional): Source identifier for the document
|
| 456 |
"""
|
| 457 |
chunks = chunk_text(request.text, source=request.source)
|
| 458 |
count = add_documents_to_vectorstore(chunks)
|
|
|
|
| 459 |
return JSONResponse(content={
|
| 460 |
"status": "success",
|
| 461 |
"chunks_added": count,
|
|
@@ -465,43 +885,84 @@ async def ingest_endpoint(request: IngestRequest):
|
|
| 465 |
|
| 466 |
@app.get("/health")
|
| 467 |
async def health_check():
|
| 468 |
-
"""
|
|
|
|
|
|
|
| 469 |
return {
|
| 470 |
"status": "healthy",
|
| 471 |
"documents_in_store": collection.count(),
|
| 472 |
"embedding_model": EMBEDDING_MODEL_NAME,
|
| 473 |
"llm_model": LLM_MODEL_NAME,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 474 |
}
|
| 475 |
|
| 476 |
|
| 477 |
# ---------------------------------------------------------------------------
|
| 478 |
-
#
|
| 479 |
# ---------------------------------------------------------------------------
|
| 480 |
|
| 481 |
def gradio_query(question: str) -> tuple[str, str, str, str, str]:
|
| 482 |
-
"""
|
|
|
|
|
|
|
| 483 |
if not question.strip():
|
| 484 |
return "Please enter a question.", "", "", "", ""
|
|
|
|
| 485 |
result = rag_query(question)
|
|
|
|
| 486 |
sources_text = "\n".join(
|
| 487 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 488 |
)
|
| 489 |
-
|
| 490 |
explanation = result.get("explanation", "")
|
| 491 |
token_info = str(result.get("total_token", 0))
|
|
|
|
| 492 |
co2_value = result.get("co2_grams")
|
| 493 |
co2_info = f"{co2_value:.4f} g" if isinstance(co2_value, (int, float)) else "N/A"
|
|
|
|
| 494 |
run_time = f"{result.get('run_time_in_ms', 0)} ms"
|
|
|
|
| 495 |
return answer, explanation, token_info, co2_info, run_time
|
| 496 |
|
| 497 |
|
| 498 |
def gradio_ingest(text: str, source_name: str) -> str:
|
| 499 |
-
"""
|
|
|
|
|
|
|
| 500 |
if not text.strip():
|
| 501 |
return "Please provide text to ingest."
|
|
|
|
| 502 |
chunks = chunk_text(text, source=source_name or "user_upload")
|
| 503 |
count = add_documents_to_vectorstore(chunks)
|
| 504 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 505 |
|
| 506 |
|
| 507 |
with gr.Blocks(title="RAG Chat API - Gustave Eiffel Hackathon") as demo:
|
|
@@ -510,6 +971,12 @@ with gr.Blocks(title="RAG Chat API - Gustave Eiffel Hackathon") as demo:
|
|
| 510 |
|
| 511 |
This application demonstrates a complete **Retrieval-Augmented Generation (RAG)** system.
|
| 512 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
**API Endpoint:** Use `POST /query` with `{"query": "your question"}` for programmatic access.
|
| 514 |
|
| 515 |
---
|
|
@@ -517,63 +984,91 @@ with gr.Blocks(title="RAG Chat API - Gustave Eiffel Hackathon") as demo:
|
|
| 517 |
|
| 518 |
with gr.Tab("💬 Chat"):
|
| 519 |
gr.Markdown("Ask questions about the ingested documents.")
|
|
|
|
| 520 |
with gr.Row():
|
| 521 |
query_input = gr.Textbox(
|
| 522 |
label="Your Question",
|
| 523 |
-
placeholder="e.g.,
|
| 524 |
lines=2,
|
| 525 |
)
|
|
|
|
| 526 |
query_button = gr.Button("Ask", variant="primary")
|
| 527 |
query_output = gr.Textbox(label="Answer", lines=8, interactive=False)
|
| 528 |
query_explanation = gr.Textbox(label="Explanation", lines=3, interactive=False)
|
|
|
|
| 529 |
with gr.Row():
|
| 530 |
query_tokens = gr.Textbox(label="Total Tokens", interactive=False)
|
| 531 |
query_co2 = gr.Textbox(label="CO2 Emission", interactive=False)
|
| 532 |
query_runtime = gr.Textbox(label="Run Time", interactive=False)
|
|
|
|
| 533 |
query_button.click(
|
| 534 |
fn=gradio_query,
|
| 535 |
inputs=query_input,
|
| 536 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 537 |
)
|
| 538 |
|
| 539 |
with gr.Tab("📄 Ingest Documents"):
|
| 540 |
gr.Markdown("Add new documents to the knowledge base.")
|
|
|
|
| 541 |
doc_text = gr.Textbox(
|
| 542 |
label="Document Text",
|
| 543 |
placeholder="Paste your document text here...",
|
| 544 |
lines=10,
|
| 545 |
)
|
|
|
|
| 546 |
doc_source = gr.Textbox(
|
| 547 |
label="Source Name",
|
| 548 |
placeholder="e.g., my_document.txt",
|
| 549 |
value="user_upload",
|
| 550 |
)
|
|
|
|
| 551 |
ingest_button = gr.Button("Ingest Document", variant="primary")
|
| 552 |
ingest_output = gr.Textbox(label="Status", interactive=False)
|
| 553 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 554 |
|
| 555 |
with gr.Tab("ℹ️ API Info"):
|
| 556 |
gr.Markdown("""
|
| 557 |
## API Endpoints
|
| 558 |
|
| 559 |
### POST /query
|
|
|
|
| 560 |
```json
|
| 561 |
{
|
| 562 |
-
"query": "
|
| 563 |
"top_k": 3
|
| 564 |
}
|
| 565 |
```
|
| 566 |
|
| 567 |
**Response:**
|
|
|
|
| 568 |
```json
|
| 569 |
{
|
| 570 |
-
"answer": "
|
| 571 |
-
"sources": [
|
| 572 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
}
|
| 574 |
```
|
| 575 |
|
| 576 |
### POST /ingest
|
|
|
|
| 577 |
```json
|
| 578 |
{
|
| 579 |
"text": "Your document text here...",
|
|
@@ -582,16 +1077,19 @@ with gr.Blocks(title="RAG Chat API - Gustave Eiffel Hackathon") as demo:
|
|
| 582 |
```
|
| 583 |
|
| 584 |
### GET /health
|
| 585 |
-
|
|
|
|
| 586 |
""")
|
| 587 |
|
| 588 |
-
|
| 589 |
app = gr.mount_gradio_app(app, demo, path="/")
|
| 590 |
|
|
|
|
| 591 |
# ---------------------------------------------------------------------------
|
| 592 |
# Entry Point
|
| 593 |
# ---------------------------------------------------------------------------
|
| 594 |
|
| 595 |
if __name__ == "__main__":
|
| 596 |
import uvicorn
|
| 597 |
-
|
|
|
|
|
|
| 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
|
| 22 |
+
→ Response
|
| 23 |
"""
|
| 24 |
|
| 25 |
import os
|
|
|
|
| 30 |
from typing import Optional
|
| 31 |
|
| 32 |
# Must be set before chromadb is imported so the module never registers its
|
| 33 |
+
# posthog telemetry hook.
|
| 34 |
os.environ.setdefault("ANONYMIZED_TELEMETRY", "False")
|
| 35 |
|
| 36 |
import requests as http_requests
|
|
|
|
| 45 |
|
| 46 |
from llm import call_llm as call_llm_with_metrics
|
| 47 |
|
| 48 |
+
|
| 49 |
logging.basicConfig(level=logging.INFO)
|
| 50 |
logger = logging.getLogger(__name__)
|
| 51 |
|
| 52 |
+
# Suppress non-fatal chromadb telemetry errors
|
| 53 |
logging.getLogger("chromadb.telemetry.product.posthog").setLevel(logging.CRITICAL)
|
| 54 |
|
| 55 |
+
|
| 56 |
# ---------------------------------------------------------------------------
|
| 57 |
# Configuration
|
| 58 |
# ---------------------------------------------------------------------------
|
| 59 |
|
| 60 |
+
# Resolve the data directory: /data when running inside HF Spaces bucket mount,
|
| 61 |
# ./data for local development.
|
| 62 |
DATA_DIR = Path("/data") if Path("/data").is_dir() else Path("./data")
|
| 63 |
|
| 64 |
CHROMA_PERSIST_DIR = str(DATA_DIR / "chroma_db")
|
| 65 |
TRAIN_DOCS_DIR = Path("./train_data")
|
| 66 |
COLLECTION_NAME = "rag_documents"
|
| 67 |
+
|
| 68 |
+
# Chunking fixe de base
|
| 69 |
CHUNK_SIZE = 512
|
| 70 |
CHUNK_OVERLAP = 50
|
| 71 |
+
|
| 72 |
+
# Ancien top_k par défaut
|
| 73 |
TOP_K_RESULTS = 3
|
| 74 |
|
| 75 |
+
|
| 76 |
+
# ---------------------------------------------------------------------------
|
| 77 |
+
# Retrieval Configuration
|
| 78 |
+
# ---------------------------------------------------------------------------
|
| 79 |
+
|
| 80 |
+
# Nombre de candidats récupérés au départ.
|
| 81 |
+
# On récupère plus large que le nombre final de chunks, puis on filtre.
|
| 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
|
| 87 |
+
|
| 88 |
+
# Nombre maximum de chunks envoyés au LLM.
|
| 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 le seuil,
|
| 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
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ---------------------------------------------------------------------------
|
| 99 |
+
# Query Rewriting Configuration
|
| 100 |
+
# ---------------------------------------------------------------------------
|
| 101 |
+
|
| 102 |
+
# Active/désactive le query rewriting LLM.
|
| 103 |
+
QUERY_REWRITE_ENABLED = True
|
| 104 |
+
|
| 105 |
+
# On ne reformule que les questions courtes/ambiguës pour limiter coût, tokens et CO2.
|
| 106 |
+
QUERY_REWRITE_MAX_WORDS = 6
|
| 107 |
+
|
| 108 |
+
# Nombre maximal de tokens générés par le LLM pour la reformulation.
|
| 109 |
+
QUERY_REWRITE_MAX_TOKENS = 60
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ---------------------------------------------------------------------------
|
| 113 |
+
# Load Config
|
| 114 |
+
# ---------------------------------------------------------------------------
|
| 115 |
+
|
| 116 |
_CONFIG_PATH = DATA_DIR / "config.json"
|
| 117 |
if not _CONFIG_PATH.exists():
|
| 118 |
_CONFIG_PATH = Path(__file__).parent / "config.json"
|
| 119 |
logger.warning(
|
| 120 |
+
f"No config.json found in {DATA_DIR} — falling back to root config.json. "
|
| 121 |
"Copy config.json to the data directory and fill in your values for production use."
|
| 122 |
)
|
| 123 |
+
|
| 124 |
with open(_CONFIG_PATH, encoding="utf-8") as _f:
|
| 125 |
_config = json.load(_f)
|
| 126 |
|
| 127 |
+
# Embedding model
|
| 128 |
EMBEDDING_ENDPOINT_URL = _config["embedding"]["endpoint_url"]
|
| 129 |
EMBEDDING_MODEL_NAME = _config["embedding"]["model"]
|
| 130 |
|
| 131 |
+
# LLM
|
| 132 |
LLM_ENDPOINT_URL = _config["llm"]["endpoint_url"]
|
| 133 |
LLM_MODEL_NAME = _config["llm"]["model"]
|
| 134 |
LLM_MAX_TOKENS = _config["llm"].get("max_completion_tokens", 512)
|
| 135 |
LLM_TEMPERATURE = _config["llm"].get("temperature", 0.7)
|
| 136 |
LLM_TOP_P = _config["llm"].get("top_p", 0.95)
|
| 137 |
|
| 138 |
+
# Azure API key from environment variable
|
| 139 |
AZURE_API_KEY = os.environ.get("AZURE_API_KEY")
|
| 140 |
if not AZURE_API_KEY:
|
| 141 |
logger.warning("AZURE_API_KEY is not set — LLM and embedding calls will fail.")
|
| 142 |
|
| 143 |
+
# Prompt template
|
| 144 |
_PROMPT_TEMPLATE_PATH = Path(__file__).parent / "prompts" / "rag_prompt.txt"
|
| 145 |
RAG_PROMPT_TEMPLATE = _PROMPT_TEMPLATE_PATH.read_text(encoding="utf-8")
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
logger.info(f"Embedding model configured: {EMBEDDING_MODEL_NAME} via Azure OpenAI")
|
| 148 |
|
| 149 |
+
|
| 150 |
# ---------------------------------------------------------------------------
|
| 151 |
+
# Initialize Vector Store
|
| 152 |
# ---------------------------------------------------------------------------
|
|
|
|
|
|
|
| 153 |
|
| 154 |
logger.info(f"Initializing ChromaDB at: {CHROMA_PERSIST_DIR}")
|
| 155 |
+
|
| 156 |
chroma_client = chromadb.PersistentClient(
|
| 157 |
path=CHROMA_PERSIST_DIR,
|
| 158 |
settings=Settings(anonymized_telemetry=False),
|
| 159 |
)
|
| 160 |
+
|
| 161 |
collection = chroma_client.get_or_create_collection(
|
| 162 |
name=COLLECTION_NAME,
|
| 163 |
metadata={"hnsw:space": "cosine"},
|
| 164 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 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 |
|
|
|
|
| 174 |
def extract_text_from_pdf(pdf_path: Path) -> str:
|
| 175 |
"""
|
| 176 |
Extract text content from a PDF file using pypdf.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
"""
|
| 178 |
reader = PdfReader(str(pdf_path))
|
| 179 |
pages_text = []
|
| 180 |
|
| 181 |
for page_num, page in enumerate(reader.pages, start=1):
|
| 182 |
text = page.extract_text()
|
| 183 |
+
|
| 184 |
if text and text.strip():
|
| 185 |
pages_text.append(f"[Page {page_num}]\n{text.strip()}")
|
| 186 |
|
| 187 |
full_text = "\n\n".join(pages_text)
|
| 188 |
+
|
| 189 |
+
logger.info(
|
| 190 |
+
f"Extracted {len(reader.pages)} pages from PDF: "
|
| 191 |
+
f"{pdf_path.name} ({len(full_text)} chars)"
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
return full_text
|
| 195 |
|
| 196 |
|
| 197 |
def chunk_text(text: str, source: str = "unknown") -> list[dict]:
|
| 198 |
"""
|
| 199 |
+
Chunking fixe de base.
|
|
|
|
|
|
|
|
|
|
| 200 |
"""
|
| 201 |
splitter = RecursiveCharacterTextSplitter(
|
| 202 |
chunk_size=CHUNK_SIZE,
|
| 203 |
chunk_overlap=CHUNK_OVERLAP,
|
| 204 |
separators=["\n\n", "\n", ". ", " ", ""],
|
| 205 |
)
|
| 206 |
+
|
| 207 |
chunks = splitter.split_text(text)
|
| 208 |
+
|
| 209 |
+
return [
|
| 210 |
+
{
|
| 211 |
+
"text": chunk,
|
| 212 |
+
"source": source,
|
| 213 |
+
"chunk_index": i,
|
| 214 |
+
}
|
| 215 |
+
for i, chunk in enumerate(chunks)
|
| 216 |
+
if chunk.strip()
|
| 217 |
+
]
|
| 218 |
|
| 219 |
|
| 220 |
def generate_embeddings(texts: list[str]) -> list[list[float]]:
|
| 221 |
"""
|
| 222 |
Generate vector embeddings via the Azure OpenAI /embeddings endpoint.
|
|
|
|
|
|
|
|
|
|
| 223 |
"""
|
| 224 |
headers = {
|
| 225 |
"api-key": AZURE_API_KEY,
|
| 226 |
"Content-Type": "application/json",
|
| 227 |
}
|
| 228 |
+
|
| 229 |
payload = {
|
| 230 |
"input": texts,
|
| 231 |
"model": EMBEDDING_MODEL_NAME,
|
| 232 |
}
|
| 233 |
+
|
| 234 |
try:
|
| 235 |
resp = http_requests.post(
|
| 236 |
+
EMBEDDING_ENDPOINT_URL,
|
| 237 |
+
headers=headers,
|
| 238 |
+
json=payload,
|
| 239 |
+
timeout=120,
|
| 240 |
)
|
| 241 |
resp.raise_for_status()
|
| 242 |
data = resp.json()
|
| 243 |
return [item["embedding"] for item in data["data"]]
|
| 244 |
+
|
| 245 |
except http_requests.exceptions.HTTPError as e:
|
| 246 |
logger.error(f"Embedding API call failed: {e} — {resp.text}")
|
| 247 |
+
raise HTTPException(
|
| 248 |
+
status_code=503,
|
| 249 |
+
detail=f"Embedding service unavailable: {str(e)}",
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
except (http_requests.exceptions.JSONDecodeError, ValueError) as e:
|
| 253 |
+
logger.error(
|
| 254 |
+
f"Embedding API returned non-JSON response "
|
| 255 |
+
f"(status {resp.status_code}): {repr(resp.text)}"
|
| 256 |
+
)
|
| 257 |
+
raise HTTPException(
|
| 258 |
+
status_code=502,
|
| 259 |
+
detail="Embedding service returned an invalid response",
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
except (KeyError, IndexError) as e:
|
| 263 |
logger.error(f"Unexpected embedding response format: {e} — body: {resp.text}")
|
| 264 |
+
raise HTTPException(
|
| 265 |
+
status_code=502,
|
| 266 |
+
detail="Unexpected response from embedding service",
|
| 267 |
+
)
|
| 268 |
|
| 269 |
|
| 270 |
def add_documents_to_vectorstore(documents: list[dict]) -> int:
|
| 271 |
"""
|
| 272 |
Save document embeddings to the ChromaDB vector store.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
"""
|
| 274 |
if not documents:
|
| 275 |
return 0
|
|
|
|
| 278 |
embeddings = generate_embeddings(texts)
|
| 279 |
|
| 280 |
existing_count = collection.count()
|
| 281 |
+
|
| 282 |
+
ids = [
|
| 283 |
+
f"doc_{existing_count + i}"
|
| 284 |
+
for i in range(len(documents))
|
| 285 |
+
]
|
| 286 |
+
|
| 287 |
+
metadatas = [
|
| 288 |
+
{
|
| 289 |
+
"source": doc.get("source", "unknown"),
|
| 290 |
+
"chunk_index": doc.get("chunk_index", i),
|
| 291 |
+
}
|
| 292 |
+
for i, doc in enumerate(documents)
|
| 293 |
+
]
|
| 294 |
|
| 295 |
collection.add(
|
| 296 |
ids=ids,
|
|
|
|
| 300 |
)
|
| 301 |
|
| 302 |
logger.info(f"Added {len(documents)} chunks to vector store. Total: {collection.count()}")
|
| 303 |
+
|
| 304 |
return len(documents)
|
| 305 |
|
| 306 |
|
| 307 |
+
# ---------------------------------------------------------------------------
|
| 308 |
+
# Query Rewriting and Query Expansion
|
| 309 |
+
# ---------------------------------------------------------------------------
|
| 310 |
+
|
| 311 |
+
def clean_query_words(query: str) -> list[str]:
|
| 312 |
+
"""
|
| 313 |
+
Nettoyage simple d'une question pour détecter mots/acronymes.
|
| 314 |
+
"""
|
| 315 |
+
q = query.lower().strip()
|
| 316 |
+
|
| 317 |
+
cleaned = (
|
| 318 |
+
q.replace("?", " ")
|
| 319 |
+
.replace(",", " ")
|
| 320 |
+
.replace(".", " ")
|
| 321 |
+
.replace(";", " ")
|
| 322 |
+
.replace(":", " ")
|
| 323 |
+
.replace("'", " ")
|
| 324 |
+
.replace('"', " ")
|
| 325 |
+
.replace("(", " ")
|
| 326 |
+
.replace(")", " ")
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
return cleaned.split()
|
| 330 |
+
|
| 331 |
+
|
| 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 |
+
"""
|
| 339 |
+
if not QUERY_REWRITE_ENABLED:
|
| 340 |
+
return False
|
| 341 |
+
|
| 342 |
+
words = clean_query_words(query)
|
| 343 |
+
|
| 344 |
+
if not words:
|
| 345 |
+
return False
|
| 346 |
+
|
| 347 |
+
technical_terms = {
|
| 348 |
+
"bel", "scr", "mcr", "glm", "mrh",
|
| 349 |
+
"var", "tvar", "ifrs", "alm"
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
# Acronyme seul ou question très courte avec acronyme.
|
| 353 |
+
if len(words) <= QUERY_REWRITE_MAX_WORDS and any(w in technical_terms for w in words):
|
| 354 |
+
return True
|
| 355 |
+
|
| 356 |
+
# Question très courte, potentiellement ambiguë.
|
| 357 |
+
if len(words) <= 3:
|
| 358 |
+
return True
|
| 359 |
+
|
| 360 |
+
return False
|
| 361 |
+
|
| 362 |
+
|
| 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.
|
| 370 |
+
- La fonction retourne aussi les métriques du rewriting.
|
| 371 |
+
"""
|
| 372 |
+
default_info = {
|
| 373 |
+
"query_rewrite_used": False,
|
| 374 |
+
"original_query": query,
|
| 375 |
+
"rewritten_query": query,
|
| 376 |
+
"query_rewrite_prompt_tokens": 0,
|
| 377 |
+
"query_rewrite_completion_tokens": 0,
|
| 378 |
+
"query_rewrite_total_tokens": 0,
|
| 379 |
+
"query_rewrite_co2_grams": None,
|
| 380 |
+
"query_rewrite_energy_kwh": None,
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
if not should_rewrite_query(query):
|
| 384 |
+
return query, default_info
|
| 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.
|
| 392 |
+
- Explicite seulement les acronymes actuariels évidents si présents :
|
| 393 |
+
BEL = Best Estimate Liability,
|
| 394 |
+
SCR = Solvency Capital Requirement,
|
| 395 |
+
MCR = Minimum Capital Requirement,
|
| 396 |
+
GLM = modèle linéaire généralisé,
|
| 397 |
+
MRH = multirisque habitation,
|
| 398 |
+
VaR = Value at Risk,
|
| 399 |
+
TVaR = Tail Value at Risk,
|
| 400 |
+
ALM = Asset Liability Management.
|
| 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 |
+
|
| 411 |
+
try:
|
| 412 |
+
rewrite_result = call_llm_with_metrics(
|
| 413 |
+
rewrite_prompt,
|
| 414 |
+
endpoint_url=LLM_ENDPOINT_URL,
|
| 415 |
+
api_key=AZURE_API_KEY,
|
| 416 |
+
model=LLM_MODEL_NAME,
|
| 417 |
+
max_completion_tokens=QUERY_REWRITE_MAX_TOKENS,
|
| 418 |
+
temperature=0,
|
| 419 |
+
top_p=1,
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
rewritten_query = rewrite_result["content"].strip()
|
| 423 |
+
rewritten_query = rewritten_query.strip('"').strip("'").strip()
|
| 424 |
+
|
| 425 |
+
if not rewritten_query:
|
| 426 |
+
return query, default_info
|
| 427 |
+
|
| 428 |
+
tokens = rewrite_result.get("tokens", {})
|
| 429 |
+
info = {
|
| 430 |
+
"query_rewrite_used": True,
|
| 431 |
+
"original_query": query,
|
| 432 |
+
"rewritten_query": rewritten_query,
|
| 433 |
+
"query_rewrite_prompt_tokens": tokens.get("prompt", 0),
|
| 434 |
+
"query_rewrite_completion_tokens": tokens.get("completion", 0),
|
| 435 |
+
"query_rewrite_total_tokens": tokens.get("total", 0),
|
| 436 |
+
"query_rewrite_co2_grams": rewrite_result.get("co2_grams"),
|
| 437 |
+
"query_rewrite_energy_kwh": rewrite_result.get("energy_kwh"),
|
| 438 |
+
}
|
| 439 |
+
|
| 440 |
+
logger.info(
|
| 441 |
+
f"Query rewritten: original='{query}' | rewritten='{rewritten_query}'"
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
return rewritten_query, info
|
| 445 |
+
|
| 446 |
+
except Exception as e:
|
| 447 |
+
logger.error(f"Query rewriting failed: {e}")
|
| 448 |
+
return query, default_info
|
| 449 |
+
|
| 450 |
+
|
| 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.
|
| 458 |
+
- Pas besoin de refaire l'ingestion.
|
| 459 |
+
"""
|
| 460 |
+
q = query.lower().strip()
|
| 461 |
+
|
| 462 |
+
expansions = {
|
| 463 |
+
"bel": "Best Estimate Liability Best Estimate provision technique assurance vie solvabilité",
|
| 464 |
+
"scr": "Solvency Capital Requirement capital de solvabilité Solvabilité II",
|
| 465 |
+
"mcr": "Minimum Capital Requirement minimum capital requis Solvabilité II",
|
| 466 |
+
"glm": "modèle linéaire généralisé GLM tarification fréquence sévérité sinistres",
|
| 467 |
+
"mrh": "multirisque habitation assurance habitation sinistres habitation",
|
| 468 |
+
"var": "Value at Risk VaR quantile risque capital économique",
|
| 469 |
+
"tvar": "Tail Value at Risk TVaR risque extrême capital économique",
|
| 470 |
+
"ifrs": "IFRS 17 norme comptable assurance contrats d'assurance",
|
| 471 |
+
"alm": "Asset Liability Management gestion actif passif",
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
words = set(clean_query_words(q))
|
| 475 |
+
|
| 476 |
+
expanded = query
|
| 477 |
+
|
| 478 |
+
for term, expansion in expansions.items():
|
| 479 |
+
if term in words or q == term:
|
| 480 |
+
expanded += " " + expansion
|
| 481 |
+
|
| 482 |
+
return expanded
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def build_retrieval_query(query: str) -> tuple[str, dict]:
|
| 486 |
+
"""
|
| 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)
|
| 494 |
+
retrieval_query = expand_query(rewritten_query)
|
| 495 |
+
|
| 496 |
+
rewrite_info["retrieval_query"] = retrieval_query
|
| 497 |
+
|
| 498 |
+
return retrieval_query, rewrite_info
|
| 499 |
+
|
| 500 |
+
|
| 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.
|
| 508 |
+
"""
|
| 509 |
+
q = query.lower().strip()
|
| 510 |
+
|
| 511 |
+
technical_terms = {
|
| 512 |
+
"bel", "scr", "mcr", "glm", "mrh",
|
| 513 |
+
"var", "tvar", "ifrs", "alm"
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
words = clean_query_words(query)
|
| 517 |
+
|
| 518 |
+
# Acronyme seul : BEL, SCR, GLM...
|
| 519 |
+
if q in technical_terms:
|
| 520 |
+
return 0.70
|
| 521 |
+
|
| 522 |
+
# Question courte contenant un terme technique
|
| 523 |
+
if len(words) <= 3 and any(word in technical_terms for word in words):
|
| 524 |
+
return 0.70
|
| 525 |
+
|
| 526 |
+
# Question très courte : seuil un peu plus permissif
|
| 527 |
+
if len(words) <= 5:
|
| 528 |
+
return 0.65
|
| 529 |
+
|
| 530 |
+
# Cas général
|
| 531 |
+
return DISTANCE_THRESHOLD
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
# ---------------------------------------------------------------------------
|
| 535 |
+
# Retrieval
|
| 536 |
+
# ---------------------------------------------------------------------------
|
| 537 |
+
|
| 538 |
+
def retrieve_relevant_context(
|
| 539 |
+
query: str,
|
| 540 |
+
top_k: int = TOP_K_RESULTS,
|
| 541 |
+
) -> tuple[list[dict], dict]:
|
| 542 |
+
"""
|
| 543 |
+
Retrieve relevant document chunks with optional query rewriting and
|
| 544 |
+
adaptive distance threshold.
|
| 545 |
+
|
| 546 |
+
Différence avec le code de base :
|
| 547 |
+
- Avant : on prenait toujours les top_k chunks les plus proches.
|
| 548 |
+
- Maintenant :
|
| 549 |
+
1. on reformule la question si elle est courte/ambiguë ;
|
| 550 |
+
2. on enrichit les acronymes ;
|
| 551 |
+
3. on récupère plusieurs candidats ;
|
| 552 |
+
4. on garde seulement ceux dont la distance passe le seuil adaptatif.
|
| 553 |
"""
|
| 554 |
if collection.count() == 0:
|
| 555 |
+
return [], {
|
| 556 |
+
"query_rewrite_used": False,
|
| 557 |
+
"original_query": query,
|
| 558 |
+
"rewritten_query": query,
|
| 559 |
+
"retrieval_query": query,
|
| 560 |
+
"effective_threshold": None,
|
| 561 |
+
"query_rewrite_prompt_tokens": 0,
|
| 562 |
+
"query_rewrite_completion_tokens": 0,
|
| 563 |
+
"query_rewrite_total_tokens": 0,
|
| 564 |
+
"query_rewrite_co2_grams": None,
|
| 565 |
+
"query_rewrite_energy_kwh": None,
|
| 566 |
+
}
|
| 567 |
+
|
| 568 |
+
retrieval_query, rewrite_info = build_retrieval_query(query)
|
| 569 |
+
effective_threshold = get_distance_threshold(query)
|
| 570 |
+
|
| 571 |
+
query_embedding = generate_embeddings([retrieval_query])[0]
|
| 572 |
+
|
| 573 |
+
max_contexts = min(top_k or TOP_K_RESULTS, MAX_CONTEXT_CHUNKS)
|
| 574 |
|
| 575 |
+
candidate_count = min(
|
| 576 |
+
max(RETRIEVAL_CANDIDATES, max_contexts),
|
| 577 |
+
collection.count(),
|
| 578 |
+
)
|
| 579 |
|
| 580 |
results = collection.query(
|
| 581 |
query_embeddings=[query_embedding],
|
| 582 |
+
n_results=candidate_count,
|
| 583 |
include=["documents", "metadatas", "distances"],
|
| 584 |
)
|
| 585 |
|
| 586 |
+
candidates = []
|
| 587 |
+
|
| 588 |
for i in range(len(results["documents"][0])):
|
| 589 |
+
distance = results["distances"][0][i]
|
| 590 |
+
metadata = results["metadatas"][0][i] or {}
|
| 591 |
+
|
| 592 |
+
candidates.append({
|
| 593 |
"text": results["documents"][0][i],
|
| 594 |
+
"source": metadata.get("source", "unknown"),
|
| 595 |
+
"chunk_index": metadata.get("chunk_index"),
|
| 596 |
+
"distance": distance,
|
| 597 |
+
"similarity_score": 1 - distance,
|
| 598 |
+
"passed_threshold": distance <= effective_threshold,
|
| 599 |
})
|
| 600 |
|
| 601 |
+
# ChromaDB renvoie normalement déjà les résultats triés,
|
| 602 |
+
# mais on retrie explicitement par sécurité.
|
| 603 |
+
candidates.sort(key=lambda x: x["distance"])
|
| 604 |
+
|
| 605 |
+
filtered_contexts = [
|
| 606 |
+
ctx for ctx in candidates
|
| 607 |
+
if ctx["distance"] <= effective_threshold
|
| 608 |
+
]
|
| 609 |
+
|
| 610 |
+
# Si aucun chunk ne passe le seuil, on peut soit ne rien envoyer au LLM,
|
| 611 |
+
# soit garder le meilleur chunk selon FALLBACK_TO_BEST_CHUNK.
|
| 612 |
+
if not filtered_contexts and FALLBACK_TO_BEST_CHUNK and candidates:
|
| 613 |
+
logger.info(
|
| 614 |
+
f"No chunk passed threshold={effective_threshold}. "
|
| 615 |
+
f"Falling back to best chunk with distance={candidates[0]['distance']:.4f}."
|
| 616 |
+
)
|
| 617 |
+
filtered_contexts = [candidates[0]]
|
| 618 |
+
|
| 619 |
+
selected_contexts = filtered_contexts[:max_contexts]
|
| 620 |
+
|
| 621 |
+
rewrite_info["effective_threshold"] = effective_threshold
|
| 622 |
+
rewrite_info["retrieval_candidates"] = len(candidates)
|
| 623 |
+
rewrite_info["passed_threshold"] = len(filtered_contexts)
|
| 624 |
+
rewrite_info["selected_contexts"] = len(selected_contexts)
|
| 625 |
+
|
| 626 |
+
logger.info(
|
| 627 |
+
f"Retrieval with query rewriting and adaptive distance threshold: "
|
| 628 |
+
f"candidates={len(candidates)}, "
|
| 629 |
+
f"passed_threshold={len(filtered_contexts)}, "
|
| 630 |
+
f"selected={len(selected_contexts)}, "
|
| 631 |
+
f"threshold={effective_threshold}, "
|
| 632 |
+
f"rewrite_used={rewrite_info.get('query_rewrite_used')}, "
|
| 633 |
+
f"retrieval_query='{retrieval_query[:120]}', "
|
| 634 |
+
f"query='{query[:80]}'"
|
| 635 |
+
)
|
| 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 |
"""
|
| 647 |
context_text = "\n\n".join(
|
| 648 |
+
f"[Source: {ctx['source']}]\n{ctx['text']}"
|
| 649 |
+
for ctx in contexts
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
prompt = RAG_PROMPT_TEMPLATE.format(
|
| 653 |
+
context=context_text,
|
| 654 |
+
question=query,
|
| 655 |
)
|
| 656 |
|
|
|
|
| 657 |
return prompt
|
| 658 |
|
| 659 |
|
| 660 |
def rag_query(query: str, top_k: int = TOP_K_RESULTS) -> dict:
|
| 661 |
"""
|
| 662 |
+
End-to-end RAG pipeline.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 663 |
"""
|
| 664 |
start_time = time.perf_counter()
|
| 665 |
|
| 666 |
+
contexts, retrieval_info = retrieve_relevant_context(query, top_k=top_k)
|
|
|
|
| 667 |
|
| 668 |
if not contexts:
|
| 669 |
elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
|
| 670 |
+
|
| 671 |
+
if collection.count() == 0:
|
| 672 |
+
answer = "No documents have been ingested yet. Please upload documents first."
|
| 673 |
+
explanation = "No documents found in the vector store to retrieve context from."
|
| 674 |
+
else:
|
| 675 |
+
effective_threshold = retrieval_info.get("effective_threshold")
|
| 676 |
+
answer = (
|
| 677 |
+
"I could not find sufficiently relevant context in the ingested documents "
|
| 678 |
+
"to answer this question reliably."
|
| 679 |
+
)
|
| 680 |
+
explanation = (
|
| 681 |
+
f"Documents exist in the vector store, but no retrieved chunk passed "
|
| 682 |
+
f"the adaptive distance threshold of {effective_threshold}. "
|
| 683 |
+
"This avoids sending weak or irrelevant context to the LLM."
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
rewrite_tokens = retrieval_info.get("query_rewrite_total_tokens", 0)
|
| 687 |
+
|
| 688 |
return {
|
| 689 |
+
"answer": answer,
|
| 690 |
"sources": [],
|
| 691 |
+
"explanation": explanation,
|
| 692 |
+
"total_token": rewrite_tokens,
|
| 693 |
+
"prompt_tokens": retrieval_info.get("query_rewrite_prompt_tokens", 0),
|
| 694 |
+
"completion_tokens": retrieval_info.get("query_rewrite_completion_tokens", 0),
|
| 695 |
"cached_tokens": 0,
|
| 696 |
+
"query_rewrite_used": retrieval_info.get("query_rewrite_used", False),
|
| 697 |
+
"rewritten_query": retrieval_info.get("rewritten_query", query),
|
| 698 |
+
"retrieval_query": retrieval_info.get("retrieval_query", query),
|
| 699 |
+
"query_rewrite_total_tokens": retrieval_info.get("query_rewrite_total_tokens", 0),
|
| 700 |
+
"co2_grams": retrieval_info.get("query_rewrite_co2_grams"),
|
| 701 |
+
"energy_kwh": retrieval_info.get("query_rewrite_energy_kwh"),
|
| 702 |
"run_time_in_ms": elapsed_ms,
|
| 703 |
}
|
| 704 |
|
|
|
|
| 705 |
prompt = build_rag_prompt(query, contexts)
|
| 706 |
|
|
|
|
| 707 |
llm_result = call_llm_with_metrics(
|
| 708 |
prompt,
|
| 709 |
endpoint_url=LLM_ENDPOINT_URL,
|
|
|
|
| 713 |
temperature=LLM_TEMPERATURE,
|
| 714 |
top_p=LLM_TOP_P,
|
| 715 |
)
|
| 716 |
+
|
| 717 |
raw_content = llm_result["content"]
|
| 718 |
tokens = llm_result["tokens"]
|
|
|
|
| 719 |
|
| 720 |
+
rewrite_total_tokens = retrieval_info.get("query_rewrite_total_tokens", 0)
|
| 721 |
+
answer_total_tokens = tokens["total"]
|
| 722 |
+
total_token = rewrite_total_tokens + answer_total_tokens
|
| 723 |
+
|
| 724 |
+
# Parse structured JSON response from LLM
|
| 725 |
json_str = raw_content.strip()
|
| 726 |
+
|
| 727 |
if json_str.startswith("```"):
|
| 728 |
json_str = json_str.split("\n", 1)[-1]
|
| 729 |
json_str = json_str.rsplit("```", 1)[0].strip()
|
|
|
|
| 738 |
|
| 739 |
elapsed_ms = round((time.perf_counter() - start_time) * 1000, 2)
|
| 740 |
|
| 741 |
+
# Addition approximative des métriques CO2/énergie du rewriting et de la réponse finale.
|
| 742 |
+
rewrite_co2 = retrieval_info.get("query_rewrite_co2_grams")
|
| 743 |
+
final_co2 = llm_result.get("co2_grams")
|
| 744 |
+
|
| 745 |
+
if isinstance(rewrite_co2, (int, float)) and isinstance(final_co2, (int, float)):
|
| 746 |
+
total_co2 = rewrite_co2 + final_co2
|
| 747 |
+
else:
|
| 748 |
+
total_co2 = final_co2
|
| 749 |
+
|
| 750 |
+
rewrite_energy = retrieval_info.get("query_rewrite_energy_kwh")
|
| 751 |
+
final_energy = llm_result.get("energy_kwh")
|
| 752 |
+
|
| 753 |
+
if isinstance(rewrite_energy, (int, float)) and isinstance(final_energy, (int, float)):
|
| 754 |
+
total_energy = rewrite_energy + final_energy
|
| 755 |
+
else:
|
| 756 |
+
total_energy = final_energy
|
| 757 |
+
|
| 758 |
return {
|
| 759 |
"answer": answer,
|
| 760 |
+
"sources": [
|
| 761 |
+
{
|
| 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"],
|
| 768 |
+
}
|
| 769 |
+
for ctx in contexts
|
| 770 |
+
],
|
| 771 |
"explanation": explanation,
|
| 772 |
+
|
| 773 |
+
# Tokens totaux = rewriting éventuel + génération finale.
|
| 774 |
"total_token": total_token,
|
| 775 |
+
"prompt_tokens": tokens["prompt"] + retrieval_info.get("query_rewrite_prompt_tokens", 0),
|
| 776 |
+
"completion_tokens": tokens["completion"] + retrieval_info.get("query_rewrite_completion_tokens", 0),
|
| 777 |
"cached_tokens": tokens["cached"],
|
| 778 |
+
|
| 779 |
+
# Détail du rewriting
|
| 780 |
+
"query_rewrite_used": retrieval_info.get("query_rewrite_used", False),
|
| 781 |
+
"rewritten_query": retrieval_info.get("rewritten_query", query),
|
| 782 |
+
"retrieval_query": retrieval_info.get("retrieval_query", query),
|
| 783 |
+
"query_rewrite_total_tokens": retrieval_info.get("query_rewrite_total_tokens", 0),
|
| 784 |
+
"answer_generation_total_tokens": answer_total_tokens,
|
| 785 |
+
|
| 786 |
+
# Métriques CO2/énergie totales approximatives
|
| 787 |
+
"co2_grams": total_co2,
|
| 788 |
+
"energy_kwh": total_energy,
|
| 789 |
+
|
| 790 |
"run_time_in_ms": elapsed_ms,
|
| 791 |
}
|
| 792 |
|
| 793 |
|
| 794 |
# ---------------------------------------------------------------------------
|
| 795 |
+
# Ingest Train Documents
|
| 796 |
# ---------------------------------------------------------------------------
|
| 797 |
|
|
|
|
| 798 |
def ingest_train_documents():
|
| 799 |
+
"""
|
| 800 |
+
Load and embed training documents into the vector store.
|
| 801 |
+
"""
|
| 802 |
if collection.count() > 0:
|
| 803 |
logger.info("Vector store already has documents, skipping ingestion.")
|
| 804 |
return
|
|
|
|
| 807 |
logger.warning(f"No train_data directory found at: {TRAIN_DOCS_DIR}")
|
| 808 |
return
|
| 809 |
|
| 810 |
+
total_chunks = 0
|
| 811 |
+
|
| 812 |
for file_path in TRAIN_DOCS_DIR.rglob("*.txt"):
|
| 813 |
logger.info(f"Ingesting text file: {file_path.name}")
|
| 814 |
+
text = file_path.read_text(encoding="utf-8", errors="ignore")
|
| 815 |
chunks = chunk_text(text, source=file_path.name)
|
| 816 |
+
total_chunks += add_documents_to_vectorstore(chunks)
|
| 817 |
|
|
|
|
| 818 |
for file_path in TRAIN_DOCS_DIR.rglob("*.pdf"):
|
| 819 |
logger.info(f"Ingesting PDF file: {file_path.name}")
|
| 820 |
text = extract_text_from_pdf(file_path)
|
| 821 |
+
|
| 822 |
if text.strip():
|
| 823 |
chunks = chunk_text(text, source=file_path.name)
|
| 824 |
+
total_chunks += add_documents_to_vectorstore(chunks)
|
| 825 |
else:
|
| 826 |
logger.warning(f"No extractable text found in: {file_path.name}")
|
| 827 |
|
| 828 |
+
logger.info(
|
| 829 |
+
f"Train document ingestion complete. "
|
| 830 |
+
f"Chunks added: {total_chunks}. Total chunks: {collection.count()}"
|
| 831 |
+
)
|
| 832 |
|
| 833 |
|
| 834 |
# ---------------------------------------------------------------------------
|
| 835 |
+
# FastAPI Application
|
| 836 |
# ---------------------------------------------------------------------------
|
| 837 |
|
| 838 |
app = FastAPI(
|
|
|
|
| 843 |
|
| 844 |
|
| 845 |
class QueryRequest(BaseModel):
|
| 846 |
+
"""
|
| 847 |
+
Request schema for the /query endpoint.
|
| 848 |
+
"""
|
| 849 |
query: str
|
| 850 |
top_k: Optional[int] = TOP_K_RESULTS
|
| 851 |
|
| 852 |
|
| 853 |
class IngestRequest(BaseModel):
|
| 854 |
+
"""
|
| 855 |
+
Request schema for the /ingest endpoint.
|
| 856 |
+
"""
|
| 857 |
text: str
|
| 858 |
source: str = "user_upload"
|
| 859 |
|
|
|
|
| 861 |
@app.post("/query")
|
| 862 |
async def query_endpoint(request: QueryRequest):
|
| 863 |
"""
|
| 864 |
+
RAG Query Endpoint.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 865 |
"""
|
| 866 |
+
logger.info(f"Query received: {request.query}")
|
| 867 |
result = rag_query(request.query, top_k=request.top_k)
|
| 868 |
return JSONResponse(content=result)
|
| 869 |
|
|
|
|
| 872 |
async def ingest_endpoint(request: IngestRequest):
|
| 873 |
"""
|
| 874 |
Document Ingestion Endpoint.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 875 |
"""
|
| 876 |
chunks = chunk_text(request.text, source=request.source)
|
| 877 |
count = add_documents_to_vectorstore(chunks)
|
| 878 |
+
|
| 879 |
return JSONResponse(content={
|
| 880 |
"status": "success",
|
| 881 |
"chunks_added": count,
|
|
|
|
| 885 |
|
| 886 |
@app.get("/health")
|
| 887 |
async def health_check():
|
| 888 |
+
"""
|
| 889 |
+
Health check endpoint.
|
| 890 |
+
"""
|
| 891 |
return {
|
| 892 |
"status": "healthy",
|
| 893 |
"documents_in_store": collection.count(),
|
| 894 |
"embedding_model": EMBEDDING_MODEL_NAME,
|
| 895 |
"llm_model": LLM_MODEL_NAME,
|
| 896 |
+
"retrieval_strategy": "conditional_llm_query_rewriting_plus_query_expansion_plus_adaptive_distance_threshold",
|
| 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,
|
| 903 |
}
|
| 904 |
|
| 905 |
|
| 906 |
# ---------------------------------------------------------------------------
|
| 907 |
+
# Gradio UI
|
| 908 |
# ---------------------------------------------------------------------------
|
| 909 |
|
| 910 |
def gradio_query(question: str) -> tuple[str, str, str, str, str]:
|
| 911 |
+
"""
|
| 912 |
+
Handle queries from the Gradio chat interface.
|
| 913 |
+
"""
|
| 914 |
if not question.strip():
|
| 915 |
return "Please enter a question.", "", "", "", ""
|
| 916 |
+
|
| 917 |
result = rag_query(question)
|
| 918 |
+
|
| 919 |
sources_text = "\n".join(
|
| 920 |
+
(
|
| 921 |
+
f" - {s['source']} "
|
| 922 |
+
f"(distance: {s.get('distance', 0):.4f}, "
|
| 923 |
+
f"relevance: {s.get('score', 0):.4f})"
|
| 924 |
+
)
|
| 925 |
+
for s in result["sources"]
|
| 926 |
+
)
|
| 927 |
+
|
| 928 |
+
rewrite_info = ""
|
| 929 |
+
if result.get("query_rewrite_used"):
|
| 930 |
+
rewrite_info = (
|
| 931 |
+
f"\n\n🔎 Rewritten query used for retrieval:\n"
|
| 932 |
+
f"{result.get('rewritten_query')}"
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
answer = (
|
| 936 |
+
f"{result['answer']}\n\n📚 Sources:\n{sources_text}{rewrite_info}"
|
| 937 |
+
if result["sources"]
|
| 938 |
+
else f"{result['answer']}{rewrite_info}"
|
| 939 |
)
|
| 940 |
+
|
| 941 |
explanation = result.get("explanation", "")
|
| 942 |
token_info = str(result.get("total_token", 0))
|
| 943 |
+
|
| 944 |
co2_value = result.get("co2_grams")
|
| 945 |
co2_info = f"{co2_value:.4f} g" if isinstance(co2_value, (int, float)) else "N/A"
|
| 946 |
+
|
| 947 |
run_time = f"{result.get('run_time_in_ms', 0)} ms"
|
| 948 |
+
|
| 949 |
return answer, explanation, token_info, co2_info, run_time
|
| 950 |
|
| 951 |
|
| 952 |
def gradio_ingest(text: str, source_name: str) -> str:
|
| 953 |
+
"""
|
| 954 |
+
Handle document ingestion from the Gradio UI.
|
| 955 |
+
"""
|
| 956 |
if not text.strip():
|
| 957 |
return "Please provide text to ingest."
|
| 958 |
+
|
| 959 |
chunks = chunk_text(text, source=source_name or "user_upload")
|
| 960 |
count = add_documents_to_vectorstore(chunks)
|
| 961 |
+
|
| 962 |
+
return (
|
| 963 |
+
f"✅ Ingested {count} chunks. "
|
| 964 |
+
f"Total documents in store: {collection.count()}"
|
| 965 |
+
)
|
| 966 |
|
| 967 |
|
| 968 |
with gr.Blocks(title="RAG Chat API - Gustave Eiffel Hackathon") as demo:
|
|
|
|
| 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 |
---
|
|
|
|
| 984 |
|
| 985 |
with gr.Tab("💬 Chat"):
|
| 986 |
gr.Markdown("Ask questions about the ingested documents.")
|
| 987 |
+
|
| 988 |
with gr.Row():
|
| 989 |
query_input = gr.Textbox(
|
| 990 |
label="Your Question",
|
| 991 |
+
placeholder="e.g., BEL, SCR, GLM, ou Comment le SCR est-il modélisé en assurance vie ?",
|
| 992 |
lines=2,
|
| 993 |
)
|
| 994 |
+
|
| 995 |
query_button = gr.Button("Ask", variant="primary")
|
| 996 |
query_output = gr.Textbox(label="Answer", lines=8, interactive=False)
|
| 997 |
query_explanation = gr.Textbox(label="Explanation", lines=3, interactive=False)
|
| 998 |
+
|
| 999 |
with gr.Row():
|
| 1000 |
query_tokens = gr.Textbox(label="Total Tokens", interactive=False)
|
| 1001 |
query_co2 = gr.Textbox(label="CO2 Emission", interactive=False)
|
| 1002 |
query_runtime = gr.Textbox(label="Run Time", interactive=False)
|
| 1003 |
+
|
| 1004 |
query_button.click(
|
| 1005 |
fn=gradio_query,
|
| 1006 |
inputs=query_input,
|
| 1007 |
+
outputs=[
|
| 1008 |
+
query_output,
|
| 1009 |
+
query_explanation,
|
| 1010 |
+
query_tokens,
|
| 1011 |
+
query_co2,
|
| 1012 |
+
query_runtime,
|
| 1013 |
+
],
|
| 1014 |
)
|
| 1015 |
|
| 1016 |
with gr.Tab("📄 Ingest Documents"):
|
| 1017 |
gr.Markdown("Add new documents to the knowledge base.")
|
| 1018 |
+
|
| 1019 |
doc_text = gr.Textbox(
|
| 1020 |
label="Document Text",
|
| 1021 |
placeholder="Paste your document text here...",
|
| 1022 |
lines=10,
|
| 1023 |
)
|
| 1024 |
+
|
| 1025 |
doc_source = gr.Textbox(
|
| 1026 |
label="Source Name",
|
| 1027 |
placeholder="e.g., my_document.txt",
|
| 1028 |
value="user_upload",
|
| 1029 |
)
|
| 1030 |
+
|
| 1031 |
ingest_button = gr.Button("Ingest Document", variant="primary")
|
| 1032 |
ingest_output = gr.Textbox(label="Status", interactive=False)
|
| 1033 |
+
|
| 1034 |
+
ingest_button.click(
|
| 1035 |
+
fn=gradio_ingest,
|
| 1036 |
+
inputs=[doc_text, doc_source],
|
| 1037 |
+
outputs=ingest_output,
|
| 1038 |
+
)
|
| 1039 |
|
| 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": "...",
|
| 1058 |
+
"sources": [
|
| 1059 |
+
{
|
| 1060 |
+
"source": "document.pdf",
|
| 1061 |
+
"score": 0.82,
|
| 1062 |
+
"distance": 0.18
|
| 1063 |
+
}
|
| 1064 |
+
],
|
| 1065 |
+
"query_rewrite_used": true,
|
| 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...",
|
|
|
|
| 1077 |
```
|
| 1078 |
|
| 1079 |
### GET /health
|
| 1080 |
+
|
| 1081 |
+
Returns system health, document count and retrieval configuration.
|
| 1082 |
""")
|
| 1083 |
|
| 1084 |
+
|
| 1085 |
app = gr.mount_gradio_app(app, demo, path="/")
|
| 1086 |
|
| 1087 |
+
|
| 1088 |
# ---------------------------------------------------------------------------
|
| 1089 |
# Entry Point
|
| 1090 |
# ---------------------------------------------------------------------------
|
| 1091 |
|
| 1092 |
if __name__ == "__main__":
|
| 1093 |
import uvicorn
|
| 1094 |
+
|
| 1095 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|