Spaces:
Sleeping
Sleeping
NandiniKodali988 commited on
Commit ·
c1eb4e1
1
Parent(s): 1c484d0
code updated for research papers
Browse filesFiles changed (6)
- eval/eval_set.yamlAdded+70
- eval/evaluate.pyAdded+97
- main.py+23-1
- src/agents/image_processing_agent.py+2-1
- src/agents/pdf_agent.py+29-6
- src/agents/rag_agent.pyAdded+66
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970# Evaluation question bank# Each question has a query and the filename of the document that should be retrieved.# Add more questions as you index more documents.
questions: # discussion.pdf — ML Fashion Recommendation System project - query: "How does the outfit recommendation system work?" expected_source: "discussion.pdf"
- query: "What is ResNet-50 used for in the project?" expected_source: "discussion.pdf"
- query: "How is FAISS used for similarity search?" expected_source: "discussion.pdf"
- query: "What database stores the clothing embeddings?" expected_source: "discussion.pdf"
- query: "How is the application deployed and containerized?" expected_source: "discussion.pdf"
- query: "What monitoring tools are used in production?" expected_source: "discussion.pdf"
- query: "How are clothing images classified into categories?" expected_source: "discussion.pdf"
- query: "What frontend framework is used for wardrobe management?" expected_source: "discussion.pdf"
# CoverLetter_SamsungIntern.pdf — Samsung Bixby Edge AI internship cover letter - query: "What internship is the cover letter applying for?" expected_source: "CoverLetter_SamsungIntern.pdf"
- query: "What RAG system was built end to end?" expected_source: "CoverLetter_SamsungIntern.pdf"
- query: "What university does the applicant attend?" expected_source: "CoverLetter_SamsungIntern.pdf"
- query: "What challenge does on-device AI face compared to cloud AI?" expected_source: "CoverLetter_SamsungIntern.pdf"
- query: "What orchestration framework was used for agentic workflows?" expected_source: "CoverLetter_SamsungIntern.pdf"
# test_RP1.pdf — "A Systematic Survey of Prompt Engineering in LLMs" (Sahoo et al., 2024) - query: "What is chain-of-thought prompting and how does it improve reasoning?" expected_source: "test_RP1.pdf"
- query: "How does Tree-of-Thoughts differ from Chain-of-Thought prompting?" expected_source: "test_RP1.pdf"
- query: "What is Retrieval Augmented Generation and how does it reduce hallucinations?" expected_source: "test_RP1.pdf"
- query: "What is zero-shot prompting in large language models?" expected_source: "test_RP1.pdf"
- query: "How does Self-Consistency improve chain-of-thought reasoning?" expected_source: "test_RP1.pdf"
- query: "What is Automatic Prompt Engineer APE?" expected_source: "test_RP1.pdf"
- query: "How does ReAct combine reasoning and action in language models?" expected_source: "test_RP1.pdf"
- query: "What is few-shot prompting and when is it used?" expected_source: "test_RP1.pdf"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import argparseimport sysfrom pathlib import Path
import yaml
# allow imports from project rootsys.path.insert(0, str(Path(__file__).parent.parent))
from src.agents.indexing_agent import IndexingAgent
def load_questions(path: Path) -> list[dict]: with open(path) as f: return yaml.safe_load(f)["questions"]
def hit_rank(results: list[dict], expected_filename: str) -> int | None: """Return 1-based rank of the first result from expected_filename, or None.""" for i, hit in enumerate(results, start=1): if hit["metadata"].get("filename", "") == expected_filename: return i return None
def run_eval(questions: list[dict], indexing_agent: IndexingAgent, top_k: int) -> list[dict]: rows = [] for q in questions: query = q["query"] expected = q["expected_source"] results = indexing_agent.search(query, top_k=top_k) rank = hit_rank(results, expected) rows.append({"query": query, "expected": expected, "rank": rank, "results": results}) return rows
def print_report(rows: list[dict], top_k: int): for row in rows: rank = row["rank"] print(f'\nQuery: "{row["query"]}"') for i, hit in enumerate(row["results"], start=1): fname = hit["metadata"].get("filename", "?") dist = hit["distance"] marker = " ✓" if fname == row["expected"] else "" print(f" [{i}] {fname} ({dist:.4f}){marker}") if rank is None: print(f" ✗ expected '{row['expected']}' not found in top {top_k}")
# aggregate metrics n = len(rows) ranks = [r["rank"] for r in rows]
def recall_at(k): """Fraction of queries where the correct doc appears anywhere in top-k.""" hits = sum(1 for r in ranks if r is not None and r <= k) return hits, n, hits / n * 100
def precision_at(k): """Average fraction of top-k results that come from the correct doc.""" scores = [] for row in rows: correct = sum( 1 for hit in row["results"][:k] if hit["metadata"].get("filename", "") == row["expected"] ) scores.append(correct / k) return sum(scores) / n
mrr = sum((1 / r) for r in ranks if r is not None) / n
print(f"\n{'='*45}") print(f"Evaluation Summary ({n} queries, top_k={top_k})") print(f"{'='*45}") for k in [1, 3, 5]: if k <= top_k: hits, total, pct = recall_at(k) p = precision_at(k) print(f"Recall@{k} : {hits}/{total} ({pct:.1f}%)") print(f"Precision@{k} : {p:.3f}") print(f"MRR : {mrr:.3f}")
def main(): parser = argparse.ArgumentParser(description="Evaluate search quality of the pipeline") parser.add_argument("--eval-set", default="eval/eval_set.yaml", type=Path) parser.add_argument("--chroma-db", default="./chroma_db") parser.add_argument("--top-k", type=int, default=5) args = parser.parse_args()
questions = load_questions(args.eval_set) agent = IndexingAgent(chroma_db_path=args.chroma_db) rows = run_eval(questions, agent, top_k=args.top_k) print_report(rows, top_k=args.top_k)
if __name__ == "__main__": main()32 unmodified lines33343536373839404142434432 unmodified linesparser.add_argument("--search", "-s", help="Run a search query against the indexed documents")parser.add_argument("--top-k", type=int, default=5, help="Number of results for --search")parser.add_argument("--verbose", "-v", action="store_true", help="Enable debug logging")args = parser.parse_args()setup_logging(args.verbose)if args.search:# Search-only mode — skip processingfrom src.agents.indexing_agent import IndexingAgent32 unmodified lines3334353637383940414243444546474849505152535455565758596061626364656632 unmodified linesparser.add_argument("--search", "-s", help="Run a search query against the indexed documents")parser.add_argument("--query", "-q", help="Ask a question — retrieves relevant chunks and generates a grounded answer")parser.add_argument("--top-k", type=int, default=5, help="Number of results for --search / --query")parser.add_argument("--verbose", "-v", action="store_true", help="Enable debug logging")args = parser.parse_args()setup_logging(args.verbose)if args.query:from src.agents.indexing_agent import IndexingAgentfrom src.agents.rag_agent import RAGAgentindexing_agent = IndexingAgent(chroma_db_path=args.chroma_db)rag_agent = RAGAgent()chunks = indexing_agent.search(args.query, top_k=args.top_k)if not chunks:print("No relevant documents found in the index.")returnresult = rag_agent.answer(args.query, chunks)print(f"\nQuestion: {args.query}\n")print(f"Answer:\n{result['answer']}")print(f"\nSources ({result['chunks_used']} chunks): {', '.join(result['sources'])}")returnif args.search:# Search-only mode — skip processingfrom src.agents.indexing_agent import IndexingAgent
42 unmodified lines4344454647484942 unmodified lines)description = resp.content[0].text.strip()return f"\n\n> **Image description:** {description}\n"def _media_type(self, image_path: Path) -> str:ext = image_path.suffix.lower()42 unmodified lines434445464748495042 unmodified lines)description = resp.content[0].text.strip()# always use a path relative to the output dir — images/ is always next to the .mdreturn f"\n\n> **Image description:** {description}\n"def _media_type(self, image_path: Path) -> str:ext = image_path.suffix.lower()
123414 unmodified lines1920212223242526272 unmodified lines30313233343536373839404142434445464748495051525354555657585960import loggingfrom pathlib import Pathimport fitz # PyMuPDF14 unmodified linesmetadata = self._get_metadata(file_path)pages_md = []with fitz.open(str(file_path)) as doc, pdfplumber.open(str(file_path)) as plumber:for page_num, (fitz_page, plumber_page) in enumerate(zip(doc, plumber.pages), start=1):pages_md.append(self._process_page(fitz_page, plumber_page, page_num, metadata["title"], doc))header = f"# {metadata['title']}\n"if metadata.get("author"):2 unmodified linesreturn {"markdown": header + "\n\n".join(pages_md), "metadata": metadata}def _process_page(self, fitz_page, plumber_page, page_num, doc_title, doc) -> str:parts = [f"## Page {page_num}\n"]text = fitz_page.get_text("text").strip()if text:parts.append(text)for table in plumber_page.extract_tables() or []:parts.append(self._table_to_markdown(table))for i, img_ref in enumerate(fitz_page.get_images(full=True)):xref = img_ref[0]try:parts.append(self._extract_image(doc, xref, page_num, i, doc_title))except Exception as e:logger.warning("page %d image %d failed: %s", page_num, i, e)return "\n\n".join(parts)def _extract_image(self, doc, xref, page_num, img_index, doc_title) -> str:raw = doc.extract_image(xref)img_path = self.images_dir / f"p{page_num}_img{img_index}.{raw['ext']}"img_path.write_bytes(raw["image"])return self.image_agent.describe(img_path, f"a PDF titled '{doc_title}' (page {page_num})")def _get_metadata(self, file_path: Path) -> dict:with fitz.open(str(file_path)) as doc:m = doc.metadata or {}1234514 unmodified lines202122232425262728292 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import loggingimport refrom pathlib import Pathimport fitz # PyMuPDF14 unmodified linesmetadata = self._get_metadata(file_path)pages_md = []doc_stem = file_path.stemwith fitz.open(str(file_path)) as doc, pdfplumber.open(str(file_path)) as plumber:for page_num, (fitz_page, plumber_page) in enumerate(zip(doc, plumber.pages), start=1):pages_md.append(self._process_page(fitz_page, plumber_page, page_num, metadata["title"], doc, doc_stem))header = f"# {metadata['title']}\n"if metadata.get("author"):2 unmodified linesreturn {"markdown": header + "\n\n".join(pages_md), "metadata": metadata}# matches figure captions at start of line: "Figure 1:", "Fig. 2:" etc.# does NOT match inline references like "(see Fig.2)"_FIGURE_RE = re.compile(r"^fig(ure)?\.?\s*\d+\s*:", re.IGNORECASE | re.MULTILINE)def _process_page(self, fitz_page, plumber_page, page_num, doc_title, doc, doc_stem) -> str:parts = [f"## Page {page_num}\n"]text = fitz_page.get_text("text").strip()text = re.sub(r"([a-z])-\n([a-z])", r"\1\2", text)if text:parts.append(text)for table in plumber_page.extract_tables() or []:parts.append(self._table_to_markdown(table))# try embedded raster images firstraster_images = fitz_page.get_images(full=True)for i, img_ref in enumerate(raster_images):xref = img_ref[0]try:parts.append(self._extract_raster_image(doc, xref, page_num, i, doc_title, doc_stem))except Exception as e:logger.warning("page %d image %d failed: %s", page_num, i, e)# if no raster images but the page mentions a figure, render the whole pageif not raster_images and self._FIGURE_RE.search(text):try:parts.append(self._render_page_as_image(fitz_page, page_num, doc_title, doc_stem))except Exception as e:logger.warning("page %d render failed: %s", page_num, e)return "\n\n".join(parts)def _extract_raster_image(self, doc, xref, page_num, img_index, doc_title, doc_stem) -> str:raw = doc.extract_image(xref)img_path = self.images_dir / f"{doc_stem}_p{page_num}_img{img_index}.{raw['ext']}"img_path.write_bytes(raw["image"])return self.image_agent.describe(img_path, f"a PDF titled '{doc_title}' (page {page_num})")def _render_page_as_image(self, fitz_page, page_num, doc_title, doc_stem) -> str:# render at 2x resolution so text in diagrams is legible to Claude Visionpixmap = fitz_page.get_pixmap(dpi=150)img_path = self.images_dir / f"{doc_stem}_p{page_num}_render.png"pixmap.save(str(img_path))return self.image_agent.describe(img_path, f"a PDF titled '{doc_title}' (page {page_num})")def _get_metadata(self, file_path: Path) -> dict:with fitz.open(str(file_path)) as doc:m = doc.metadata or {}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import loggingimport os
import anthropic
logger = logging.getLogger(__name__)
DEFAULT_MODEL = "claude-sonnet-4-6"
SYSTEM_PROMPT = ( "You are a helpful assistant that answers questions strictly based on the provided " "document excerpts. Each excerpt is labelled with a [number] and its source filename. " "Cite sources inline using [number] immediately after the relevant statement. " "If multiple excerpts support the same point, cite all of them. " "If the answer cannot be found in the excerpts, say: " "'I could not find an answer in the indexed documents.' " "Do not speculate or use knowledge outside the provided context.")
class RAGAgent: def __init__(self, model: str = DEFAULT_MODEL): self.client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY")) self.model = model
def answer(self, question: str, chunks: list[dict]) -> dict: """Generate a grounded answer from retrieved chunks.
Returns: { "answer": str, # Claude's response with inline citations "sources": list[str], # unique filenames of chunks used "chunks_used": int, } """ context_parts = [] for i, chunk in enumerate(chunks, 1): meta = chunk["metadata"] fname = meta.get("filename", meta.get("source_file", "unknown")) section = meta.get("section_heading", "") header = f"[{i}] {fname}" + (f" — {section}" if section else "") context_parts.append(f"{header}\n{chunk['text']}")
context = "\n\n---\n\n".join(context_parts) user_message = f"Document excerpts:\n\n{context}\n\n---\n\nQuestion: {question}"
response = self.client.messages.create( model=self.model, max_tokens=1024, system=SYSTEM_PROMPT, messages=[{"role": "user", "content": user_message}], )
answer_text = response.content[0].text
seen: set[str] = set() sources: list[str] = [] for chunk in chunks: meta = chunk["metadata"] fname = meta.get("filename", meta.get("source_file", "unknown")) if fname not in seen: seen.add(fname) sources.append(fname)
logger.debug("RAG answer generated using %d chunks from %s", len(chunks), sources) return {"answer": answer_text, "sources": sources, "chunks_used": len(chunks)}eval/eval_set.yamlAdded+70
eval/evaluate.pyAdded+97
main.py+23-1
src/agents/image_processing_agent.py+2-1
src/agents/pdf_agent.py+29-6
src/agents/rag_agent.pyAdded+66