Spaces:
Running on Zero
Running on Zero
File size: 24,862 Bytes
4298e57 7d171c2 2d7100b 4298e57 2d7100b 4298e57 dc26dec 4298e57 2d7100b 4298e57 dc26dec 4298e57 dc26dec 4298e57 dc26dec 4298e57 2d7100b 4298e57 7d171c2 4298e57 2d7100b dc26dec 2d7100b 4298e57 dc26dec 2d7100b 4298e57 2d7100b 4298e57 2d7100b 4298e57 dc26dec 4298e57 2d7100b 4298e57 dc26dec 4298e57 2d7100b 4298e57 dc26dec 2d7100b 4298e57 2d7100b 4298e57 2d7100b 4298e57 dc26dec 4298e57 2d7100b 4298e57 2d7100b 4298e57 dc26dec 4298e57 dc26dec 4298e57 2d7100b 4298e57 dc26dec 4298e57 2d7100b 4298e57 dc26dec 4298e57 e24b8e9 4298e57 e24b8e9 4298e57 e24b8e9 4298e57 dc26dec 4298e57 dc26dec 4298e57 dc26dec 4298e57 dc26dec 4298e57 dc26dec 4298e57 dc26dec 4298e57 dc26dec 4298e57 2d7100b 4298e57 dc26dec 4298e57 2d7100b 4298e57 2d7100b 4298e57 2d7100b 4298e57 dc26dec | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 | from __future__ import annotations
import html
import os
import re
import threading
from dataclasses import dataclass
IS_HF_SPACE = bool(os.getenv("SPACE_ID"))
if IS_HF_SPACE:
import spaces
else:
class _SpacesShim:
@staticmethod
def GPU(duration: int = 60, **_kwargs):
def decorator(fn):
return fn
return decorator
spaces = _SpacesShim()
import faiss
import numpy as np
import pandas as pd
import torch
from huggingface_hub import InferenceClient, hf_hub_download
from sentence_transformers import SentenceTransformer
from transformers import AutoModelForCausalLM, AutoTokenizer
from config import (
EMBEDDING_MODEL_ID,
FAR_DATASET_FILE,
FAR_DATASET_REPO,
FAR_SOURCE_URL,
HF_INFERENCE_MODEL,
HF_TOKEN,
LLM_BACKEND,
LOCAL_MODEL_ID,
MAX_CONTEXT_CHARS,
SYSTEM_PROMPT,
)
from document_loader import Chunk, infer_far_section
# search results
@dataclass
class SearchHit:
"""
One retrieved RAG passage
chunk:
Original document chunk
score:
FAISS cosine-similarity score
"""
chunk: Chunk
score: float
# Knowledge base
class KnowledgeBase:
"""
in-memory FAISS vector knowledge base
"""
def __init__(self) -> None:
self.chunks: list[Chunk] = []
self.index: faiss.IndexFlatIP | None = None
self.dimension: int | None = None
def add(self, chunks: list[Chunk]) -> int:
"""
Embed and add chunks to the FAISS index
Returns the number of chunks added
"""
if not chunks:
return 0
embeddings = embed_passages(
[chunk.text for chunk in chunks]
)
# building the FAISS index the first time documents are added
if self.index is None:
self.dimension = int(embeddings.shape[1])
self.index = faiss.IndexFlatIP(
self.dimension
)
# prevent accidental mixing of embeddings with different vector dimensions
if embeddings.shape[1] != self.dimension:
raise ValueError(
"Embedding dimension changed during this session"
)
self.index.add(embeddings)
self.chunks.extend(chunks)
return len(chunks)
def clear(self) -> None:
"""Remove all indexed documents"""
self.chunks.clear()
self.index = None
self.dimension = None
def search(
self,
query: str,
top_k: int = 6,
) -> list[SearchHit]:
"""
Retrieving the most relevant passages for a question
"""
if self.index is None or not self.chunks:
return []
query = query.strip()
if not query:
return []
# convert question into an embedding
query_vec = embed_query(query)
# never request more results than exist
k = min(
max(1, int(top_k)),
len(self.chunks),
)
# retrieve extra candidates because we perform lightweight deduplication afterward
candidate_count = min(
k * 2,
len(self.chunks),
)
scores, indices = self.index.search(
query_vec,
candidate_count,
)
hits: list[SearchHit] = []
# avoid repeatedly returning effectively identical source/page/section combinations
seen: set[
tuple[str, int | None, str | None]
] = set()
for score, idx in zip(
scores[0],
indices[0],
):
if idx < 0:
continue
chunk = self.chunks[int(idx)]
fingerprint = (
chunk.source_name,
chunk.page,
chunk.section,
)
if fingerprint in seen:
continue
seen.add(fingerprint)
hits.append(
SearchHit(
chunk=chunk,
score=float(score),
)
)
if len(hits) >= k:
break
return hits
@property
def document_count(self) -> int:
"""no. of unique source documents"""
return len(
{
chunk.source_name
for chunk in self.chunks
}
)
@property
def chunk_count(self) -> int:
"""total number of chunks in the knowledge base"""
return len(self.chunks)
# Global model caches
_EMBEDDER: SentenceTransformer | None = None
_EMBEDDER_LOCK = threading.Lock()
_LOCAL_MODEL = None
_LOCAL_TOKENIZER = None
_LOCAL_MODEL_LOCK = threading.Lock()
# Embedding model
def get_embedding_device() -> str:
"""
return the device using embedding model
"""
if IS_HF_SPACE:
return "cuda"
return "cuda" if torch.cuda.is_available() else "cpu"
def _load_embedder() -> SentenceTransformer:
"""
embedding model
"""
device = get_embedding_device()
print(
f"[embedding] Loading {EMBEDDING_MODEL_ID} on {device}",
flush=True,
)
model = SentenceTransformer(
EMBEDDING_MODEL_ID,
device=device,
)
print(
"[embedding] Model ready.",
flush=True,
)
return model
if IS_HF_SPACE:
_EMBEDDER = _load_embedder()
def get_embedder() -> SentenceTransformer:
"""
return the shared embedding model
"""
global _EMBEDDER
if _EMBEDDER is not None:
return _EMBEDDER
with _EMBEDDER_LOCK:
if _EMBEDDER is None:
_EMBEDDER = _load_embedder()
return _EMBEDDER
def _encode(
texts: list[str],
*,
batch_size: int = 16,
) -> np.ndarray:
"""
encode text into normalized float32 vectors for FAISS
"""
if not texts:
raise ValueError(
"Cannot embed an empty list of texts"
)
model = get_embedder()
vectors = model.encode(
texts,
batch_size=int(batch_size),
normalize_embeddings=True,
convert_to_numpy=True,
show_progress_bar=False,
)
vectors = vectors.astype("float32")
# return ordinary CPU/NumPy data across the ZeroGPU process boundary
return np.ascontiguousarray(vectors)
@spaces.GPU(duration=120)
def embed_passages(
texts: list[str],
) -> np.ndarray:
"""
embed document/FAR passages
"""
return _encode(
texts,
batch_size=16,
)
@spaces.GPU(duration=30)
def embed_query(
query: str,
) -> np.ndarray:
"""
Embed a retrieval query on ZeroGPU
"""
clean = query.strip()
if not clean:
raise ValueError(
"Query cannot be empty"
)
model = get_embedder()
prompts = getattr(
model,
"prompts",
{},
)
if "query" in prompts:
vectors = model.encode(
[clean],
prompt_name="query",
batch_size=1,
normalize_embeddings=True,
convert_to_numpy=True,
show_progress_bar=False,
)
vectors = vectors.astype(
"float32"
)
return np.ascontiguousarray(
vectors
)
instructed = (
"Represent this sentence for searching "
f"relevant passages: {clean}"
)
return _encode(
[instructed],
batch_size=1,
)
# FAR Hugging Face dataset
def _normalize_chunk_id(
raw_id,
fallback: int,
) -> str:
"""
Convert CSV Chunk ID values into clean strings.
Examples:
12.0 -> "12"
"FAR-52.212" -> "FAR-52.212"
"""
if pd.isna(raw_id):
return str(fallback)
value = str(raw_id).strip()
try:
number = float(value)
if number.is_integer():
return str(int(number))
except ValueError:
pass
return value or str(fallback)
def load_far_dataset(
max_rows: int = 2500,
) -> list[Chunk]:
"""
Download and load the FAR chunk corpus from hf
"""
max_rows = int(max_rows)
if max_rows <= 0:
raise ValueError(
"max_rows must be greater than zero."
)
print(
"[FAR] Downloading starter corpus...",
flush=True,
)
print(
f"[FAR] Repository: {FAR_DATASET_REPO}",
flush=True,
)
print(
f"[FAR] File: {FAR_DATASET_FILE}",
flush=True,
)
try:
local_path = hf_hub_download(
repo_id=FAR_DATASET_REPO,
filename=FAR_DATASET_FILE,
repo_type="dataset",
token=HF_TOKEN,
)
except Exception as exc:
raise RuntimeError(
"Unable to download the FAR dataset from "
"Hugging Face.\n\n"
f"Repository: {FAR_DATASET_REPO}\n"
f"File: {FAR_DATASET_FILE}\n"
f"Error: {exc}"
) from exc
print(
f"[FAR] Downloaded to: {local_path}",
flush=True,
)
try:
frame = pd.read_csv(
local_path
)
except Exception as exc:
raise RuntimeError(
"The FAR CSV was downloaded but could "
f"not be read: {exc}"
) from exc
required_column = "Chunk Text"
if required_column not in frame.columns:
raise ValueError(
"Expected the FAR chunk file to contain "
f"'{required_column}'. "
f"Found columns: {list(frame.columns)}"
)
# remove records without usable text
frame = frame.dropna(
subset=[required_column]
)
# limit initial corpus size for local testing
frame = frame.head(
max_rows
)
chunks: list[Chunk] = []
for row_number, (_, row) in enumerate(
frame.iterrows(),
start=1,
):
text = str(
row[required_column]
).strip()
if not text:
continue
raw_id = row.get(
"Chunk ID",
row_number,
)
chunk_id = _normalize_chunk_id(
raw_id,
row_number,
)
# try to identify the FAR section from the chunk text itself
section = infer_far_section(
text
)
chunk = Chunk(
chunk_id=chunk_id,
text=text,
source_name=(
"Federal Acquisition Regulation"
),
source_type=(
"Hugging Face FAR dataset"
),
section=section,
url=FAR_SOURCE_URL,
metadata={
"dataset_repo": FAR_DATASET_REPO,
"dataset_file": FAR_DATASET_FILE,
"source": "Federal Acquisition Regulation",
},
)
chunks.append(chunk)
if not chunks:
raise RuntimeError(
"The FAR dataset loaded successfully, "
"but no usable text chunks were found."
)
print(
f"[FAR] Loaded {len(chunks):,} chunks.",
flush=True,
)
return chunks
# RAG context construction
def build_context(
hits: list[SearchHit],
max_chars: int = MAX_CONTEXT_CHARS,
) -> str:
"""
convert retrieved passages into the context supplied
to the language model
each passage receives a stable source identifier:
[S1]
[S2]
[S3]
...
"""
blocks: list[str] = []
used_chars = 0
for source_number, hit in enumerate(
hits,
start=1,
):
chunk = hit.chunk
header = [
f"[S{source_number}]",
f"Source: {chunk.source_name}",
f"Citation: {chunk.citation}",
]
if chunk.url:
header.append(
f"Official/source URL: {chunk.url}"
)
block = (
"\n".join(header)
+ "\nRetrieved text:\n"
+ chunk.text.strip()
)
# stop adding context once the configured character budget has been reached
if (
used_chars + len(block) > max_chars
and blocks
):
break
blocks.append(block)
used_chars += len(block)
return "\n\n---\n\n".join(
blocks
)
# Local LM
def _get_local_model():
"""
loading the local Hugging Face language model once
(CUDA is used automatically when available)
"""
if IS_HF_SPACE:
raise RuntimeError(
"Local LLM fallback is disabled on this ZeroGPU Space. "
"Use LLM_BACKEND=hf_api with HF_TOKEN configured as a Space Secret."
)
global _LOCAL_MODEL
global _LOCAL_TOKENIZER
if (
_LOCAL_MODEL is not None
and _LOCAL_TOKENIZER is not None
):
return (
_LOCAL_MODEL,
_LOCAL_TOKENIZER,
)
with _LOCAL_MODEL_LOCK:
if (
_LOCAL_MODEL is not None
and _LOCAL_TOKENIZER is not None
):
return (
_LOCAL_MODEL,
_LOCAL_TOKENIZER,
)
print(
f"[LLM] Loading tokenizer: "
f"{LOCAL_MODEL_ID}",
flush=True,
)
tokenizer = AutoTokenizer.from_pretrained(
LOCAL_MODEL_ID,
token=HF_TOKEN,
)
if tokenizer.pad_token is None:
tokenizer.pad_token = (
tokenizer.eos_token
)
if torch.cuda.is_available():
dtype = (
torch.bfloat16
if torch.cuda.is_bf16_supported()
else torch.float16
)
device = "cuda"
else:
dtype = torch.float32
device = "cpu"
print(
f"[LLM] Loading model: "
f"{LOCAL_MODEL_ID}",
flush=True,
)
print(
f"[LLM] Device: {device}",
flush=True,
)
print(
f"[LLM] Dtype: {dtype}",
flush=True,
)
model = AutoModelForCausalLM.from_pretrained(
LOCAL_MODEL_ID,
dtype=dtype,
low_cpu_mem_usage=True,
token=HF_TOKEN,
)
model = model.to(
device
)
model.eval()
_LOCAL_MODEL = model
_LOCAL_TOKENIZER = tokenizer
print(
"[LLM] Local model ready.",
flush=True,
)
return (
_LOCAL_MODEL,
_LOCAL_TOKENIZER,
)
# HF hosted inference
def _generate_hf_api(
messages: list[dict],
temperature: float,
max_new_tokens: int,
) -> str:
"""
generate an answer through Hugging Face Inference Providers
"""
if not HF_TOKEN:
raise RuntimeError(
"HF_TOKEN is not configured for the "
"Hugging Face Inference backend."
)
client = InferenceClient(
api_key=HF_TOKEN,
provider="together",
)
response = client.chat_completion(
model=HF_INFERENCE_MODEL,
messages=messages,
max_tokens=int(max_new_tokens),
temperature=max(
0.7,
float(temperature),
),
top_p=0.8,
presence_penalty=1.5,
extra_body={
"top_k": 20,
"chat_template_kwargs": {
"enable_thinking": False,
},
},
)
message = response.choices[0].message
content = message.content
if not content:
reasoning = getattr(
message,
"reasoning",
None,
)
if reasoning:
raise RuntimeError(
"The model returned reasoning but no final answer. "
"Increase the answer token limit or verify that "
"thinking mode is disabled by the selected provider."
)
raise RuntimeError(
"The Hugging Face model returned an empty response."
)
return content.strip()
# Local generation
def _generate_local(
messages: list[dict],
temperature: float,
max_new_tokens: int,
) -> str:
"""
generate an answer using the locally loaded model
"""
model, tokenizer = (
_get_local_model()
)
prompt = tokenizer.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
inputs = tokenizer(
prompt,
return_tensors="pt",
)
device = next(
model.parameters()
).device
inputs = {
key: value.to(device)
for key, value
in inputs.items()
}
temperature = float(
temperature
)
do_sample = (
temperature > 0
)
generation_kwargs = {
"max_new_tokens": int(
max_new_tokens
),
"do_sample": do_sample,
"pad_token_id": (
tokenizer.eos_token_id
),
"eos_token_id": (
tokenizer.eos_token_id
),
}
if do_sample:
generation_kwargs.update(
temperature=max(
temperature,
1e-5,
),
top_p=0.85, # param in ml model that controls the randomness and creativity of text generation, tells the model to add up the probabilities of the most likely next words until they reach 85%, the model only picks from this group of words, cutting out the 15% of weird or rare words
)
with torch.inference_mode():
output = model.generate(
**inputs,
**generation_kwargs,
)
generated_tokens = output[0][
inputs["input_ids"].shape[1]:
]
answer = tokenizer.decode(
generated_tokens,
skip_special_tokens=True,
)
return answer.strip()
# backend selection
def choose_backend() -> str:
"""
choosing the generation backend
"""
configured = (
LLM_BACKEND
.strip()
.lower()
)
if IS_HF_SPACE:
if not HF_TOKEN:
raise RuntimeError(
"HF_TOKEN is required on the Hugging Face Space. "
"Configure it as a Space Secret and use "
"LLM_BACKEND=hf_api."
)
return "hf_api"
if configured in {
"hf_api",
"local",
}:
return configured
if HF_TOKEN:
return "hf_api"
return "local"
# citation validation
def _extract_citation_ids(
answer: str,
) -> list[str]:
"""
Extract source IDs such as:
[S1]
[S2]
"""
return re.findall(
r"\[S(\d+)\]",
answer,
)
# main RAG answer function
def answer_question(
question: str,
hits: list[SearchHit],
temperature: float = 0.15,
max_new_tokens: int = 700,
) -> tuple[str, dict]:
"""
Produce a grounded answer from retrieved source passages
"""
question = question.strip()
if not question:
return (
"Please enter a policy question.",
{
"backend": None,
"retrieved_chunks": 0,
},
)
if not hits:
return (
"No indexed source passages were "
"available for this question",
{
"backend": None,
"retrieved_chunks": 0,
},
)
context = build_context(
hits
)
user_prompt = f"""
Question:
{question}
Retrieved sources:
{context}
Instructions:
Answer the question using only the retrieved sources
Cite factual claims inline using the source identifiers
provided above, for example [S1] or [S2]
Do not invent source identifiers
If the retrieved material does not contain enough information
to answer the question, state that explicitly
Write the answer now.
""".strip()
messages = [
{
"role": "system",
"content": SYSTEM_PROMPT,
},
{
"role": "user",
"content": user_prompt,
},
]
backend = choose_backend()
# Hosted Hugging Face generation
if backend == "hf_api":
try:
answer = _generate_hf_api(
messages,
temperature,
max_new_tokens,
)
model_used = (
HF_INFERENCE_MODEL
)
except Exception as exc:
# if user explicitly selected hf_api, surface the API failure
if (
LLM_BACKEND
.strip()
.lower()
== "hf_api"
):
raise
print(
"[LLM] Hugging Face API failed. "
"Falling back to local model.",
flush=True,
)
print(
f"[LLM] API error: {exc}",
flush=True,
)
answer = _generate_local(
messages,
temperature,
max_new_tokens,
)
model_used = (
LOCAL_MODEL_ID
)
backend = (
"local fallback after HF API "
f"error: {type(exc).__name__}"
)
# Local generation
else:
answer = _generate_local(
messages,
temperature,
max_new_tokens,
)
model_used = (
LOCAL_MODEL_ID
)
# Citation validation
valid_ids = {
str(i)
for i in range(
1,
len(hits) + 1,
)
}
cited_ids = (
_extract_citation_ids(
answer
)
)
invalid_ids = sorted(
{
citation_id
for citation_id
in cited_ids
if citation_id
not in valid_ids
}
)
if invalid_ids:
answer += (
"\n\n**Citation check:** "
"The model emitted an invalid source "
"marker. Verify the retrieved source "
"panel before relying on that statement."
)
diagnostics = {
"backend": backend,
"model": model_used,
"embedding_model": (
EMBEDDING_MODEL_ID
),
"embedding_device": (
get_embedding_device()
),
"retrieved_chunks": len(
hits
),
"citations_emitted": sorted(
set(cited_ids),
key=lambda x: int(x),
),
"invalid_citations": (
invalid_ids
),
"context_characters": len(
context
),
}
return (
answer,
diagnostics,
)
# render retrieved source cards
def render_sources(
hits: list[SearchHit],
) -> str:
"""
Render retrieved passages as HTML cards for Gradio.
"""
if not hits:
return (
"<div class='status-card'>"
"No sources retrieved."
"</div>"
)
cards: list[str] = []
for source_number, hit in enumerate(
hits,
start=1,
):
chunk = hit.chunk
excerpt = (
chunk.text
.strip()
.replace("\n", " ")
)
if len(excerpt) > 520:
excerpt = (
excerpt[:517]
.rstrip()
+ "..."
)
link = ""
if chunk.url:
safe_url = html.escape(
chunk.url,
quote=True,
)
link = (
f"<a href='{safe_url}' "
"target='_blank' "
"rel='noopener noreferrer'>"
"Open source"
"</a>"
)
safe_citation = html.escape(
chunk.citation
)
safe_excerpt = html.escape(
excerpt
)
cards.append(
f"""
<div class="source-card">
<div class="source-top">
<span class="source-id">
S{source_number}
</span>
<span class="score">
score {hit.score:.3f}
</span>
</div>
<div class="source-title">
{safe_citation}
</div>
<div class="source-excerpt">
{safe_excerpt}
</div>
<div class="source-link">
{link}
</div>
</div>
"""
)
return (
"<div class='sources-grid'>"
+ "".join(cards)
+ "</div>"
) |