import argparse import json import os import sys import time from pathlib import Path from typing import NotRequired, Protocol, TypedDict from llama_cloud import LlamaCloud from llama_cloud.types.parsing_get_response import MarkdownPageMarkdownResultPage from llama_index.core import Document, StorageContext, VectorStoreIndex from llama_index.core.base.base_retriever import BaseRetriever from llama_index.core.data_structs import IndexDict from llama_index.core.llms import MockLLM from llama_index.core.node_parser import SentenceSplitter from llama_index.core.retrievers import QueryFusionRetriever from llama_index.core.retrievers.fusion_retriever import FUSION_MODES from llama_index.embeddings.openai import OpenAIEmbedding from llama_index.retrievers.bm25 import BM25Retriever PARSE_TIER = "cost_effective" PARSE_VERSION = "latest" EMBEDDING_MODEL = "text-embedding-3-small" RESULTS_PER_SEARCH = 10 PARSE_ATTEMPTS = 3 PARSE_RETRY_SECONDS = 10 PRIVATE_FILE_MODE_MASK = 0o077 class ParsedFile(TypedDict): tier: str version: str pages: list[str] file_id: NotRequired[str] error: NotRequired[str] class Question(TypedDict): question: str file: str class SearchResult(TypedDict): path: str text: str class SideAnswer(TypedDict): question: str searchable: bool results: list[SearchResult] class PersistableStorage(Protocol): def persist(self, persist_dir: str) -> None: ... def persist_storage(storage: PersistableStorage, folder: Path) -> None: storage.persist(persist_dir=str(folder)) def required_variable(name: str) -> str: value = os.environ.get(name, "") if not value: sys.exit(f"Set {name}.") return value def source_paths(files_root: Path) -> list[Path]: return sorted( path.relative_to(files_root) for path in files_root.rglob("*") if path.is_file() and not path.name.startswith(".") ) def parsed_path(out_root: Path, relative: Path) -> Path: return out_root / "parsed" / f"{relative.as_posix()}.json" def read_parsed(out_root: Path, relative: Path) -> ParsedFile: parsed: ParsedFile = json.loads(parsed_path(out_root, relative).read_text(encoding="utf-8")) return parsed def parse_one(client: LlamaCloud, source: Path) -> ParsedFile: uploaded = client.files.create(file=source, purpose="parse") result = client.parsing.parse( file_id=uploaded.id, tier=PARSE_TIER, version=PARSE_VERSION, expand=["markdown"], ) parsed_pages = result.markdown.pages if result.markdown else [] pages = [ page.markdown for page in parsed_pages if isinstance(page, MarkdownPageMarkdownResultPage) ] return {"tier": PARSE_TIER, "version": PARSE_VERSION, "file_id": uploaded.id, "pages": pages} def parse_with_retries(client: LlamaCloud, source: Path) -> ParsedFile: for attempt in range(1, PARSE_ATTEMPTS): try: return parse_one(client, source) except Exception: time.sleep(PARSE_RETRY_SECONDS * attempt) try: return parse_one(client, source) except Exception as error: return {"tier": PARSE_TIER, "version": PARSE_VERSION, "error": str(error), "pages": []} def parse_all(files_root: Path, out_root: Path) -> None: client = LlamaCloud(api_key=required_variable("LLAMA_CLOUD_API_KEY")) for relative in source_paths(files_root): target = parsed_path(out_root, relative) if target.exists(): continue target.parent.mkdir(parents=True, exist_ok=True) parsed = parse_with_retries(client, files_root / relative) target.write_text(json.dumps(parsed), encoding="utf-8") characters = sum(len(page) for page in parsed["pages"]) outcome = parsed.get("error", "parsed") print(f"{relative}: {len(parsed['pages'])} pages, {characters} characters, {outcome}") def documents_of(files_root: Path, out_root: Path) -> list[Document]: documents: list[Document] = [] for relative in source_paths(files_root): pages = read_parsed(out_root, relative)["pages"] text = "\n\n".join(page for page in pages if page.strip()) if text: documents.append(Document(text=text, metadata={"path": relative.as_posix()})) return documents def embedding() -> OpenAIEmbedding: return OpenAIEmbedding(model=EMBEDDING_MODEL, api_key=required_variable("OPENAI_API_KEY")) def built_index(files_root: Path, out_root: Path) -> VectorStoreIndex: storage = out_root / "index" model = embedding() if (storage / "docstore.json").exists(): context = StorageContext.from_defaults(persist_dir=str(storage)) saved = context.index_store.index_structs() if len(saved) != 1 or not isinstance(saved[0], IndexDict): sys.exit(f"{storage} has to hold exactly one vector index.") return VectorStoreIndex(index_struct=saved[0], storage_context=context, embed_model=model) documents = documents_of(files_root, out_root) nodes = SentenceSplitter().get_nodes_from_documents(documents) index = VectorStoreIndex(nodes, embed_model=model, show_progress=True) persist_storage(index.storage_context, storage) return index def retrieved(retriever: BaseRetriever, question: str) -> list[SearchResult]: return [ {"path": str(hit.node.metadata.get("path", "")), "text": hit.node.get_content()} for hit in retriever.retrieve(question)[:RESULTS_PER_SEARCH] ] def read_questions(questions_path: Path) -> list[Question]: lines = questions_path.read_text(encoding="utf-8").splitlines() questions: list[Question] = [json.loads(line) for line in lines if line.strip()] return questions def search_all(files_root: Path, out_root: Path, questions_path: Path) -> None: index = built_index(files_root, out_root) nodes = list(index.docstore.docs.values()) vector = index.as_retriever(similarity_top_k=RESULTS_PER_SEARCH) keyword = BM25Retriever.from_defaults(nodes=nodes, similarity_top_k=RESULTS_PER_SEARCH) hybrid = QueryFusionRetriever( [vector, keyword], llm=MockLLM(), mode=FUSION_MODES.RECIPROCAL_RANK, similarity_top_k=RESULTS_PER_SEARCH, num_queries=1, use_async=False, ) readable = { relative.as_posix() for relative in source_paths(files_root) if read_parsed(out_root, relative)["pages"] } questions = read_questions(questions_path) retrievers: tuple[tuple[str, BaseRetriever], ...] = ( ("llamaindex-vector", vector), ("llamaindex-hybrid", hybrid), ) for name, retriever in retrievers: side: list[SideAnswer] = [ { "question": question["question"], "searchable": question["file"] in readable, "results": retrieved(retriever, question["question"]), } for question in questions ] target = out_root / "sides" / f"{name}.json" target.parent.mkdir(parents=True, exist_ok=True) target.write_text(json.dumps(side), encoding="utf-8") print(f"{name}: {len(side)} questions") def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("step", choices=["parse", "search"]) parser.add_argument("--files", required=True, type=Path) parser.add_argument("--out", required=True, type=Path) parser.add_argument("--questions", type=Path) options = parser.parse_args() os.umask(PRIVATE_FILE_MODE_MASK) files_root: Path = options.files out_root: Path = options.out questions_path: Path | None = options.questions if options.step == "parse": parse_all(files_root, out_root) return if questions_path is None: sys.exit("Pass --questions for the search step.") search_all(files_root, out_root, questions_path) if __name__ == "__main__": main()