|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +from pathlib import Path |
| 4 | +from llama_index.core import ( |
| 5 | + VectorStoreIndex, |
| 6 | + StorageContext, |
| 7 | + load_index_from_storage, |
| 8 | + Settings, |
| 9 | +) |
| 10 | +from llama_index.llms.ollama import Ollama |
| 11 | +from llama_index.embeddings.huggingface import HuggingFaceEmbedding |
| 12 | +from llama_index.readers.file import PDFReader |
| 13 | + |
| 14 | +# Config |
| 15 | +ROOT_DIR = Path(__file__).resolve().parent.parent |
| 16 | +DATA_DIR = ROOT_DIR / "data" |
| 17 | +STORAGE_DIR = ROOT_DIR / "storage" |
| 18 | + |
| 19 | +async def build_and_save_index(): |
| 20 | + """Builds the index from PDF files and saves it.""" |
| 21 | + print("Loading PDF documents...") |
| 22 | + reader = PDFReader() |
| 23 | + documents = reader.load_data(folder_path=DATA_DIR) |
| 24 | + |
| 25 | + print("Building index...") |
| 26 | + index = VectorStoreIndex.from_documents(documents) |
| 27 | + |
| 28 | + print(f"Saving index to {STORAGE_DIR}/...") |
| 29 | + index.storage_context.persist(persist_dir=STORAGE_DIR) |
| 30 | + return index |
| 31 | + |
| 32 | +async def load_or_build_index(): |
| 33 | + """Loads existing index or builds a new one if not found.""" |
| 34 | + if os.path.exists(STORAGE_DIR): |
| 35 | + print(f"Loading existing index from {STORAGE_DIR}/...") |
| 36 | + storage_context = StorageContext.from_defaults(persist_dir=STORAGE_DIR) |
| 37 | + index = load_index_from_storage(storage_context) |
| 38 | + else: |
| 39 | + index = await build_and_save_index() |
| 40 | + return index |
| 41 | + |
| 42 | +async def main(): |
| 43 | + # Step 1: Setup global Settings |
| 44 | + Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-base-en-v1.5") |
| 45 | + Settings.llm = Ollama(model="llama3.1", request_timeout=360.0) |
| 46 | + |
| 47 | + # Step 2: Load or build the index |
| 48 | + index = await load_or_build_index() |
| 49 | + |
| 50 | + # Step 3: Create a query engine |
| 51 | + query_engine = index.as_query_engine() |
| 52 | + |
| 53 | + print("\n🔵 Chatbot ready! Type your questions (type 'exit' to quit):\n") |
| 54 | + |
| 55 | + while True: |
| 56 | + user_query = input("You: ") |
| 57 | + if user_query.lower() in ("exit", "quit"): |
| 58 | + print("Bye!") |
| 59 | + break |
| 60 | + response = await query_engine.aquery(user_query) |
| 61 | + print(f"Bot: {response}\n") |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + asyncio.run(main()) |
0 commit comments