"""Built-in RAG (Retrieval-Augmented Generation) Engine for Mythos-From-Scratch. Supports: - Indexing local files (.txt, .md, .jsonl, .json, .csv, .pdf) or Hugging Face datasets - Dense vector search (SentenceTransformers + normalized cosine similarity) with BM25 fallback - Grounded generation using your custom-trained Mythos model + <|context|>...<|/context|> tokens """ import argparse import glob import json import math import os import re from collections import Counter from typing import Dict, List, Optional, Tuple import numpy as np import torch from transformers import AutoModelForCausalLM, AutoTokenizer from dataset_utils import iter_custom_texts from reasoning_engine import THINKING_PROFILES, generate_with_thinking def chunk_text(text: str, chunk_size: int = 450, overlap: int = 80) -> List[str]: words = text.split() if not words: return [] chunks = [] step = max(1, chunk_size - overlap) for i in range(0, len(words), step): piece = " ".join(words[i : i + chunk_size]).strip() if piece: chunks.append(piece) if i + chunk_size >= len(words): break return chunks def _read_pdfs(local_dir: str) -> List[Tuple[str, str]]: docs = [] if not local_dir or not os.path.exists(local_dir): return docs pdfs = glob.glob(os.path.join(local_dir, "**", "*.pdf"), recursive=True) if not pdfs: return docs try: from pypdf import PdfReader except ImportError: return docs for fp in sorted(pdfs): try: reader = PdfReader(fp) text = "\n".join(page.extract_text() or "" for page in reader.pages).strip() if text: docs.append((os.path.basename(fp), text)) except Exception: continue return docs class MythosRAGIndex: def __init__(self, embed_model: str = "BAAI/bge-small-en-v1.5"): self.embed_model_name = embed_model self.chunks: List[Dict[str, str]] = [] self.embeddings: Optional[np.ndarray] = None self._encoder = None def _get_encoder(self): if self._encoder is None: try: from sentence_transformers import SentenceTransformer device = "cuda" if torch.cuda.is_available() else "cpu" self._encoder = SentenceTransformer(self.embed_model_name, device=device) except Exception: self._encoder = False return self._encoder if self._encoder is not False else None def build_from_sources( self, local_data_dir: Optional[str] = None, dataset_name: Optional[str] = None, dataset_config: Optional[str] = None, text_column: Optional[str] = None, max_docs: int = 5000, chunk_size: int = 350, overlap: int = 60, ): raw_docs: List[Tuple[str, str]] = [] if local_data_dir: raw_docs.extend(_read_pdfs(local_data_dir)) for idx, text in enumerate( iter_custom_texts( dataset_name=dataset_name, dataset_config=dataset_config, text_column=text_column, local_data_dir=local_data_dir, max_samples=max_docs, streaming=True, ) ): src = dataset_name or local_data_dir or "custom" raw_docs.append((f"{src}#{idx}", text)) self.chunks = [] for source, doc_text in raw_docs: for ci, ch in enumerate(chunk_text(doc_text, chunk_size=chunk_size, overlap=overlap)): self.chunks.append({"source": source, "chunk_id": str(ci), "text": ch}) if not self.chunks: raise ValueError("No text chunks found to index for RAG.") encoder = self._get_encoder() if encoder is not None: texts = [c["text"] for c in self.chunks] emb = encoder.encode(texts, batch_size=64, normalize_embeddings=True, show_progress_bar=True) self.embeddings = np.asarray(emb, dtype=np.float32) else: self.embeddings = None print(f"Indexed {len(self.chunks)} chunks (dense_embeddings={'yes' if self.embeddings is not None else 'bm25-fallback'})") def save(self, index_dir: str): os.makedirs(index_dir, exist_ok=True) with open(os.path.join(index_dir, "chunks.json"), "w", encoding="utf-8") as f: json.dump({"embed_model": self.embed_model_name, "chunks": self.chunks}, f, ensure_ascii=False) if self.embeddings is not None: np.save(os.path.join(index_dir, "embeddings.npy"), self.embeddings) @classmethod def load(cls, index_dir: str) -> "MythosRAGIndex": with open(os.path.join(index_dir, "chunks.json"), "r", encoding="utf-8") as f: meta = json.load(f) inst = cls(embed_model=meta.get("embed_model", "BAAI/bge-small-en-v1.5")) inst.chunks = meta["chunks"] emb_path = os.path.join(index_dir, "embeddings.npy") if os.path.exists(emb_path): inst.embeddings = np.load(emb_path) return inst def retrieve(self, query: str, top_k: int = 4) -> List[Dict[str, str]]: if not self.chunks: return [] encoder = self._get_encoder() if encoder is not None and self.embeddings is not None: q_emb = encoder.encode([query], normalize_embeddings=True) scores = np.dot(self.embeddings, q_emb[0]) top_idx = np.argsort(scores)[::-1][:top_k] return [{**self.chunks[i], "score": float(scores[i])} for i in top_idx] # Pure-Python BM25/TF-IDF fallback q_terms = re.findall(r"\w+", query.lower()) q_counts = Counter(q_terms) scored = [] for idx, ch in enumerate(self.chunks): d_terms = re.findall(r"\w+", ch["text"].lower()) d_counts = Counter(d_terms) score = sum(min(q_counts[t], d_counts[t]) for t in q_counts) / math.sqrt(len(d_terms) + 1.0) scored.append((score, idx)) scored.sort(reverse=True) return [{**self.chunks[i], "score": float(s)} for s, i in scored[:top_k]] def rag_answer( model_dir: str, index_dir: str, query: str, top_k: int = 4, thinking_mode: str = "high", ) -> Tuple[Dict[str, str], List[Dict[str, str]]]: index = MythosRAGIndex.load(index_dir) hits = index.retrieve(query, top_k=top_k) context_block = "\n\n".join(f"[{i+1}] ({h['source']}): {h['text']}" for i, h in enumerate(hits)) device = "cuda" if torch.cuda.is_available() else "cpu" tok = AutoTokenizer.from_pretrained(model_dir) model = AutoModelForCausalLM.from_pretrained(model_dir, trust_remote_code=True).to(device).eval() result = generate_with_thinking( model=model, tokenizer=tok, query=query, thinking_mode=thinking_mode, context_text=context_block, ) return result, hits if __name__ == "__main__": parser = argparse.ArgumentParser(description="Build or query Mythos RAG index.") sub = parser.add_subparsers(dest="cmd", required=True) p_idx = sub.add_parser("index", help="Index local files or HF dataset for RAG.") p_idx.add_argument("--index_dir", type=str, default="./mythos_rag_index") p_idx.add_argument("--local_data_dir", type=str, default=None) p_idx.add_argument("--dataset_name", type=str, default=None) p_idx.add_argument("--dataset_config", type=str, default=None) p_idx.add_argument("--text_column", type=str, default=None) p_idx.add_argument("--max_docs", type=int, default=5000) p_ask = sub.add_parser("ask", help="Retrieve context and generate answer with Mythos.") p_ask.add_argument("--model_dir", type=str, default="./mythos_pretrained") p_ask.add_argument("--index_dir", type=str, default="./mythos_rag_index") p_ask.add_argument("--query", type=str, required=True) p_ask.add_argument("--top_k", type=int, default=4) p_ask.add_argument("--thinking_mode", type=str, default="high", choices=list(THINKING_PROFILES.keys())) args = parser.parse_args() if args.cmd == "index": rag = MythosRAGIndex() rag.build_from_sources( local_data_dir=args.local_data_dir, dataset_name=args.dataset_name, dataset_config=args.dataset_config, text_column=args.text_column, max_docs=args.max_docs, ) rag.save(args.index_dir) elif args.cmd == "ask": res, hits = rag_answer( model_dir=args.model_dir, index_dir=args.index_dir, query=args.query, top_k=args.top_k, thinking_mode=args.thinking_mode, ) print("=== Retrieved Sources ===") for h in hits: print(f"- {h['source']} (score={h['score']:.3f})") if res["thinking"]: print(f"\n=== Thinking ({res['mode'].upper()}) ===\n{res['thinking']}") print("\n=== Mythos Answer ===") print(res["answer"])