Update chatbot.py
Browse files- chatbot.py +44 -27
chatbot.py
CHANGED
|
@@ -10,7 +10,6 @@ import torch
|
|
| 10 |
import faiss
|
| 11 |
from sentence_transformers import SentenceTransformer
|
| 12 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 13 |
-
import gradio as gr
|
| 14 |
|
| 15 |
# ---------------------------------------------------------------------------
|
| 16 |
# Defaults — edit these if you don't want to pass CLI flags every time
|
|
@@ -18,7 +17,7 @@ import gradio as gr
|
|
| 18 |
DEFAULT_FAISS_INDEX_PATH = "./hbl_site_index_COMPLETE.faiss"
|
| 19 |
DEFAULT_CHUNKS_METADATA_PATH = "./hbl_site_metadata_COMPLETE.pkl"
|
| 20 |
DEFAULT_EMBED_MODEL_PATH = "./bge-m3"
|
| 21 |
-
DEFAULT_LLM_MODEL_PATH = "./qwen2.5-3b"
|
| 22 |
|
| 23 |
RETRIEVAL_TOP_K = 4
|
| 24 |
RETRIEVAL_MIN_SCORE = 0.55
|
|
@@ -99,21 +98,19 @@ def format_chunks_display(retrieved):
|
|
| 99 |
lines = []
|
| 100 |
for i, r in enumerate(retrieved, 1):
|
| 101 |
preview = r["text"][:400] + ("..." if len(r["text"]) > 400 else "")
|
| 102 |
-
lines.append(f"
|
| 103 |
-
return "\n
|
| 104 |
|
| 105 |
# ---------------------------------------------------------------------------
|
| 106 |
# Main
|
| 107 |
# ---------------------------------------------------------------------------
|
| 108 |
def parse_args():
|
| 109 |
-
p = argparse.ArgumentParser(description="HBL Internal Assistant (RAG chatbot)")
|
| 110 |
p.add_argument("--faiss-index", default=os.environ.get("FAISS_INDEX_PATH", DEFAULT_FAISS_INDEX_PATH))
|
| 111 |
p.add_argument("--chunks-metadata", default=os.environ.get("CHUNKS_METADATA_PATH", DEFAULT_CHUNKS_METADATA_PATH))
|
| 112 |
p.add_argument("--embed-model", default=os.environ.get("EMBED_MODEL_PATH", DEFAULT_EMBED_MODEL_PATH))
|
| 113 |
p.add_argument("--llm-model", default=os.environ.get("LLM_MODEL_PATH", DEFAULT_LLM_MODEL_PATH))
|
| 114 |
-
p.add_argument("--
|
| 115 |
-
p.add_argument("--port", type=int, default=7860)
|
| 116 |
-
p.add_argument("--share", action="store_true", help="Create a public gradio.live tunnel (needs internet)")
|
| 117 |
return p.parse_args()
|
| 118 |
|
| 119 |
def main():
|
|
@@ -127,7 +124,6 @@ def main():
|
|
| 127 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 128 |
print(f"Using device: {device}")
|
| 129 |
|
| 130 |
-
# Prevent CPU execution from saturating background threads and freezing the OS
|
| 131 |
if device == "cpu":
|
| 132 |
torch.set_num_threads(4)
|
| 133 |
torch.set_num_interop_threads(4)
|
|
@@ -148,9 +144,6 @@ def main():
|
|
| 148 |
print(f"Loading LLM from {args.llm_model}...")
|
| 149 |
tokenizer = AutoTokenizer.from_pretrained(args.llm_model)
|
| 150 |
|
| 151 |
-
# FIX: on CPU, load in bfloat16 (half the RAM of float32) with
|
| 152 |
-
# low_cpu_mem_usage=True (avoids the ~2x transient spike during load).
|
| 153 |
-
# On CUDA, bfloat16 + device_map="auto" lets accelerate place weights on GPU directly.
|
| 154 |
if device == "cuda":
|
| 155 |
llm_model = AutoModelForCausalLM.from_pretrained(
|
| 156 |
args.llm_model,
|
|
@@ -170,7 +163,7 @@ def main():
|
|
| 170 |
)
|
| 171 |
llm_model = llm_model.to("cpu")
|
| 172 |
|
| 173 |
-
print("LLM ready.")
|
| 174 |
|
| 175 |
def retrieve(query, k=RETRIEVAL_TOP_K, min_score=RETRIEVAL_MIN_SCORE):
|
| 176 |
t0 = time.time()
|
|
@@ -221,20 +214,44 @@ def main():
|
|
| 221 |
traceback.print_exc()
|
| 222 |
return f"⚠️ Internal error: {e}", "*Error occurred*"
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
if __name__ == "__main__":
|
| 240 |
main()
|
|
|
|
| 10 |
import faiss
|
| 11 |
from sentence_transformers import SentenceTransformer
|
| 12 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
|
|
| 13 |
|
| 14 |
# ---------------------------------------------------------------------------
|
| 15 |
# Defaults — edit these if you don't want to pass CLI flags every time
|
|
|
|
| 17 |
DEFAULT_FAISS_INDEX_PATH = "./hbl_site_index_COMPLETE.faiss"
|
| 18 |
DEFAULT_CHUNKS_METADATA_PATH = "./hbl_site_metadata_COMPLETE.pkl"
|
| 19 |
DEFAULT_EMBED_MODEL_PATH = "./bge-m3"
|
| 20 |
+
DEFAULT_LLM_MODEL_PATH = "./qwen2.5-3b-instruct"
|
| 21 |
|
| 22 |
RETRIEVAL_TOP_K = 4
|
| 23 |
RETRIEVAL_MIN_SCORE = 0.55
|
|
|
|
| 98 |
lines = []
|
| 99 |
for i, r in enumerate(retrieved, 1):
|
| 100 |
preview = r["text"][:400] + ("..." if len(r["text"]) > 400 else "")
|
| 101 |
+
lines.append(f"[{i}] score: {r['score']:.3f} source: {r['source_url']}\n > {preview}")
|
| 102 |
+
return "\n".join(lines)
|
| 103 |
|
| 104 |
# ---------------------------------------------------------------------------
|
| 105 |
# Main
|
| 106 |
# ---------------------------------------------------------------------------
|
| 107 |
def parse_args():
|
| 108 |
+
p = argparse.ArgumentParser(description="HBL Internal Assistant (RAG chatbot) — terminal version")
|
| 109 |
p.add_argument("--faiss-index", default=os.environ.get("FAISS_INDEX_PATH", DEFAULT_FAISS_INDEX_PATH))
|
| 110 |
p.add_argument("--chunks-metadata", default=os.environ.get("CHUNKS_METADATA_PATH", DEFAULT_CHUNKS_METADATA_PATH))
|
| 111 |
p.add_argument("--embed-model", default=os.environ.get("EMBED_MODEL_PATH", DEFAULT_EMBED_MODEL_PATH))
|
| 112 |
p.add_argument("--llm-model", default=os.environ.get("LLM_MODEL_PATH", DEFAULT_LLM_MODEL_PATH))
|
| 113 |
+
p.add_argument("--show-chunks", action="store_true", help="Print retrieved chunks before each answer")
|
|
|
|
|
|
|
| 114 |
return p.parse_args()
|
| 115 |
|
| 116 |
def main():
|
|
|
|
| 124 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 125 |
print(f"Using device: {device}")
|
| 126 |
|
|
|
|
| 127 |
if device == "cpu":
|
| 128 |
torch.set_num_threads(4)
|
| 129 |
torch.set_num_interop_threads(4)
|
|
|
|
| 144 |
print(f"Loading LLM from {args.llm_model}...")
|
| 145 |
tokenizer = AutoTokenizer.from_pretrained(args.llm_model)
|
| 146 |
|
|
|
|
|
|
|
|
|
|
| 147 |
if device == "cuda":
|
| 148 |
llm_model = AutoModelForCausalLM.from_pretrained(
|
| 149 |
args.llm_model,
|
|
|
|
| 163 |
)
|
| 164 |
llm_model = llm_model.to("cpu")
|
| 165 |
|
| 166 |
+
print("LLM ready.\n")
|
| 167 |
|
| 168 |
def retrieve(query, k=RETRIEVAL_TOP_K, min_score=RETRIEVAL_MIN_SCORE):
|
| 169 |
t0 = time.time()
|
|
|
|
| 214 |
traceback.print_exc()
|
| 215 |
return f"⚠️ Internal error: {e}", "*Error occurred*"
|
| 216 |
|
| 217 |
+
# ---------------------------------------------------------------------
|
| 218 |
+
# Terminal chat loop (replaces Gradio ChatInterface)
|
| 219 |
+
# ---------------------------------------------------------------------
|
| 220 |
+
history = [] # list of {"role": "user"/"assistant", "content": str}
|
| 221 |
+
print("=" * 60)
|
| 222 |
+
print("HBL Internal Assistant — terminal mode")
|
| 223 |
+
print("Type your question and press Enter.")
|
| 224 |
+
print("Commands: 'exit' or 'quit' to stop, 'reset' to clear history.")
|
| 225 |
+
print("=" * 60 + "\n")
|
| 226 |
+
|
| 227 |
+
while True:
|
| 228 |
+
try:
|
| 229 |
+
message = input("You: ").strip()
|
| 230 |
+
except (EOFError, KeyboardInterrupt):
|
| 231 |
+
print("\nExiting.")
|
| 232 |
+
break
|
| 233 |
+
|
| 234 |
+
if not message:
|
| 235 |
+
continue
|
| 236 |
+
if message.lower() in ("exit", "quit"):
|
| 237 |
+
print("Exiting.")
|
| 238 |
+
break
|
| 239 |
+
if message.lower() == "reset":
|
| 240 |
+
history = []
|
| 241 |
+
print("(history cleared)\n")
|
| 242 |
+
continue
|
| 243 |
+
|
| 244 |
+
answer, chunks_display = chatbot_respond(message, history)
|
| 245 |
+
|
| 246 |
+
if args.show_chunks:
|
| 247 |
+
print("\n--- Retrieved chunks ---")
|
| 248 |
+
print(chunks_display)
|
| 249 |
+
print("------------------------\n")
|
| 250 |
+
|
| 251 |
+
print(f"\nAssistant: {answer}\n")
|
| 252 |
+
|
| 253 |
+
history.append({"role": "user", "content": message})
|
| 254 |
+
history.append({"role": "assistant", "content": answer})
|
| 255 |
|
| 256 |
if __name__ == "__main__":
|
| 257 |
main()
|