From 014e69714a3f1de14460ea825f8d302dcf960438 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Sun, 17 Mar 2024 16:47:28 -0400 Subject: [PATCH 01/53] Update prompts and embedding test --- src/grag/rag/basic_rag.py | 4 +-- src/tests/embedding_test.py | 55 ++++++++++--------------------------- src/tests/prompts_test.py | 38 +++++++++++++++++++++++++ 3 files changed, 54 insertions(+), 43 deletions(-) create mode 100644 src/tests/prompts_test.py diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index 4650424..725cd2e 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -1,5 +1,5 @@ import json -from typing import List +from typing import List, Union from grag import prompts from grag.components.llm import LLM @@ -19,7 +19,7 @@ def __init__(self, task='QA', llm_kwargs=None, retriever_kwargs=None, - custom_prompt: Union[Prompt, FewShotPrompt] = None + custom_prompt: Union[Prompt, FewShotPrompt, None] = None ): if retriever_kwargs is None: diff --git a/src/tests/embedding_test.py b/src/tests/embedding_test.py index e433879..4111ace 100644 --- a/src/tests/embedding_test.py +++ b/src/tests/embedding_test.py @@ -1,4 +1,5 @@ import numpy as np +import pytest from grag.components.embedding import Embedding @@ -18,48 +19,20 @@ def cosine_similarity(a, b): {'embedding_type': 'instructor-embedding', 'embedding_model': 'hkunlp/instructor-xl', } ] -# Test Documents -docs = ['Dynamic programming is both a mathematical optimization method and an algorithmic paradigm. The method was ' - 'developed by Richard Bellman in the 1950s and has found applications in numerous fields, from aerospace ' - 'engineering to economics.', - 'In computer science, recursion is a method of solving a computational problem where the solution depends on ' - 'solutions to smaller instances of the same problem. Recursion solves such recursive problems by using ' - 'functions that call themselves from within their own code. The approach can be applied to many types of ' - 'problems, and recursion is one of the central ideas of computer science.'] -print('Documents:') -for i, doc in enumerate(docs): - print(f'{i + 1}. {doc}') -query = 'What is recursion?' -print(f'Query: {query}') +@pytest.mark.parametrize('embedding_config', embedding_configs) +def test_embeddings(embedding_config): + # docs tuple format: (doc, similar to doc, asimilar to doc) + doc_sets = [('The new movie is awesome.', 'The new movie is so great.', 'The video is awful'), + ('The cat sits outside.', 'The dog plays in the garden.', 'The car is parked inside')] + embedding = Embedding(**embedding_config) + for docs in doc_sets: + doc_vecs = [embedding.embedding_function.embed_query(doc) for doc in docs] + similarity_scores = [cosine_similarity(doc_vecs[0], doc_vecs[1]), + cosine_similarity(doc_vecs[0], doc_vecs[2])] + assert similarity_scores[0] > similarity_scores[1] -# testing first config -print(f'Testing: {embedding_configs[0]}') -embedding = Embedding(**embedding_configs[0]) -docs_vector = embedding.embedding_function.embed_documents(docs) -query_vector = embedding.embedding_function.embed_query(query) - -similarity_scores = [cosine_similarity(query_vector, doc_vector) for doc_vector in docs_vector] -print(f'Similairty Scores: {similarity_scores}') - -if similarity_scores[1] > similarity_scores[0]: - print('Test Passed') -else: - print('Test Failed') - -# testing second config -print(f'Testing: {embedding_configs[1]}') - -embedding = Embedding(**embedding_configs[1]) -docs_vector = embedding.embedding_function.embed_documents(docs) -query_vector = embedding.embedding_function.embed_query(query) - -similarity_scores = [cosine_similarity(query_vector, doc_vector) for doc_vector in docs_vector] - -print(f'Similairty Scores: {similarity_scores}') -if similarity_scores[1] > similarity_scores[0]: - print('Test Passed') -else: - print('Test Failed') +if __name__ == '__main__': + test_embeddings(embedding_configs[0]) diff --git a/src/tests/prompts_test.py b/src/tests/prompts_test.py new file mode 100644 index 0000000..fee7edc --- /dev/null +++ b/src/tests/prompts_test.py @@ -0,0 +1,38 @@ +from grag.components.prompt import Prompt +from importlib_resources import files + +question = "What is the capital of France" +context = "Paris is the capital and most populous city of France. With an official estimated population of 2,102,650 \ +residents as of 1 January 2023 in an area of more than 105 km2 (41 sq mi), Paris is the fourth-most populated \ +city in the European Union and the 30th most densely populated city in the world in 2022. Since the 17th century, \ +Paris has been one of the world's major centres of finance, diplomacy, commerce, culture, fashion, and gastronomy. \ +For its leading role in the arts and sciences, as well as its early and extensive system of street lighting, in the \ +19th century, it became known as the City of Light." + + +def test_prompt_files(): + prompt_files = list(files('grag.prompts').glob('*.json')) + for file in prompt_files: + if file.name.startswith("matcher"): + prompt_files.remove(file) + for file in prompt_files: + prompt = Prompt.load(file) + assert isinstance(prompt, Prompt) + + +def test_custom_prompt(): + template = '''Answer the following question based on the given context. + question: {question} + context: {context} + answer: + ''' + correct_prompt = f'''Answer the following question based on the given context. + question: {question} + context: {context} + answer: + ''' + custom_prompt = Prompt( + input_keys={"context", "question"}, + template=template + ) + assert custom_prompt.format(question=question, context=context) == correct_prompt From fb1511c6fb8f298157f67b1d6b63c7373fe08554 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Mon, 18 Mar 2024 19:26:23 -0400 Subject: [PATCH 02/53] chroma test --- src/tests/chroma_test.py | 100 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 src/tests/chroma_test.py diff --git a/src/tests/chroma_test.py b/src/tests/chroma_test.py new file mode 100644 index 0000000..1596dd3 --- /dev/null +++ b/src/tests/chroma_test.py @@ -0,0 +1,100 @@ +import asyncio + +from grag.components.chroma_client import ChromaClient +from langchain_core.documents import Document + + +def test_chroma_connection(): + client = ChromaClient() + response = client.test_connection() + assert isinstance(response, int) + + +def test_chroma_add_docs(): + docs = [ + """And so on this rainbow day, with storms all around them, and blue sky + above, they rode only as far as the valley. But from there, before they + turned to go back, the monuments appeared close, and they loomed + grandly with the background of purple bank and creamy cloud and shafts + of golden lightning. They seemed like sentinels--guardians of a great + and beautiful love born under their lofty heights, in the lonely + silence of day, in the star-thrown shadow of night. They were like that + love. And they held Lucy and Slone, calling every day, giving a + nameless and tranquil content, binding them true to love, true to the + sage and the open, true to that wild upland home.""", + """Slone and Lucy never rode down so far as the stately monuments, though + these held memories as hauntingly sweet as others were poignantly + bitter. Lucy never rode the King again. But Slone rode him, learned to + love him. And Lucy did not race any more. When Slone tried to stir in + her the old spirit all the response he got was a wistful shake of head + or a laugh that hid the truth or an excuse that the strain on her + ankles from Joel Creech's lasso had never mended. The girl was + unutterably happy, but it was possible that she would never race a + horse again.""", + """Bostil wanted to be alone, to welcome the King, to lead him back to the + home corral, perhaps to hide from all eyes the change and the uplift + that would forever keep him from wronging another man. + + The late rains came and like magic, in a few days, the sage grew green + and lustrous and fresh, the gray turning to purple. + + Every morning the sun rose white and hot in a blue and cloudless sky. + And then soon the horizon line showed creamy clouds that rose and + spread and darkened. Every afternoon storms hung along the ramparts and + rainbows curved down beautiful and ethereal. The dim blackness of the + storm-clouds was split to the blinding zigzag of lightning, and the + thunder rolled and boomed, like the Colorado in flood.""", + ] + client = ChromaClient(collection_name="test") + if client.collection.count() > 0: + client.chroma_client.delete_collection("test") + client = ChromaClient(collection_name="test") + docs = [Document(page_content=doc) for doc in docs] + client.add_docs(docs) + collection_count = client.collection.count() + assert collection_count == len(docs) + + +def test_chroma_aadd_docs(): + docs = [ + """And so on this rainbow day, with storms all around them, and blue sky + above, they rode only as far as the valley. But from there, before they + turned to go back, the monuments appeared close, and they loomed + grandly with the background of purple bank and creamy cloud and shafts + of golden lightning. They seemed like sentinels--guardians of a great + and beautiful love born under their lofty heights, in the lonely + silence of day, in the star-thrown shadow of night. They were like that + love. And they held Lucy and Slone, calling every day, giving a + nameless and tranquil content, binding them true to love, true to the + sage and the open, true to that wild upland home.""", + """Slone and Lucy never rode down so far as the stately monuments, though + these held memories as hauntingly sweet as others were poignantly + bitter. Lucy never rode the King again. But Slone rode him, learned to + love him. And Lucy did not race any more. When Slone tried to stir in + her the old spirit all the response he got was a wistful shake of head + or a laugh that hid the truth or an excuse that the strain on her + ankles from Joel Creech's lasso had never mended. The girl was + unutterably happy, but it was possible that she would never race a + horse again.""", + """Bostil wanted to be alone, to welcome the King, to lead him back to the + home corral, perhaps to hide from all eyes the change and the uplift + that would forever keep him from wronging another man. + + The late rains came and like magic, in a few days, the sage grew green + and lustrous and fresh, the gray turning to purple. + + Every morning the sun rose white and hot in a blue and cloudless sky. + And then soon the horizon line showed creamy clouds that rose and + spread and darkened. Every afternoon storms hung along the ramparts and + rainbows curved down beautiful and ethereal. The dim blackness of the + storm-clouds was split to the blinding zigzag of lightning, and the + thunder rolled and boomed, like the Colorado in flood.""", + ] + client = ChromaClient(collection_name="test") + if client.collection.count() > 0: + client.chroma_client.delete_collection("test") + client = ChromaClient(collection_name="test") + docs = [Document(page_content=doc) for doc in docs] + loop = asyncio.get_event_loop() + loop.run_until_complete(client.aadd_docs(docs)) + assert client.collection.count() == len(docs) From 169b2e9e12c3bdc76cb5dfc87679910568f23cce Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Mon, 18 Mar 2024 19:37:27 -0400 Subject: [PATCH 03/53] Ruff config --- pyproject.toml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pyproject.toml b/pyproject.toml index 8919cc9..b2fb18d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -97,3 +97,15 @@ exclude_lines = [ "if __name__ == .__main__.:", "if TYPE_CHECKING:", ] + +[tool.ruff] +line-length = 88 +indent-width = 4 + +[tool.ruff.lint] +select = ["E4", "E7", "E9", "F", "I"] + +[tool.ruff.format] +quote-style = "double" +indent-style = "space" +docstring-code-format = false From 0ed01ea3786551c0253c3844516d2581722918eb Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Mon, 18 Mar 2024 19:38:23 -0400 Subject: [PATCH 04/53] LLM test --- src/config.ini | 1 + src/grag/components/llm.py | 30 +++++++++--- src/tests/embedding_test.py | 4 -- src/tests/llm_test.py | 94 +++++++++++++------------------------ 4 files changed, 57 insertions(+), 72 deletions(-) diff --git a/src/config.ini b/src/config.ini index e68bd26..b99511c 100644 --- a/src/config.ini +++ b/src/config.ini @@ -2,6 +2,7 @@ model_name : Llama-2-13b-chat # meta-llama/Llama-2-70b-chat-hf Mixtral-8x7B-Instruct-v0.1 quantization : Q5_K_M +pipeline : llama_cpp device_map : auto task : text-generation max_new_tokens : 1024 diff --git a/src/grag/components/llm.py b/src/grag/components/llm.py index 89db30c..332d476 100644 --- a/src/grag/components/llm.py +++ b/src/grag/components/llm.py @@ -41,10 +41,14 @@ def __init__(self, n_ctx=llm_conf["n_ctx_cpp"], n_gpu_layers=llm_conf["n_gpu_layers_cpp"], std_out=llm_conf["std_out"], - base_dir=llm_conf["base_dir"] + base_dir=llm_conf["base_dir"], + quantization=llm_conf["quantization"], + pipeline=llm_conf["pipeline"], ): self.base_dir = Path(base_dir) self._model_name = model_name + self.quantization = quantization + self.pipeline = pipeline self.device_map = device_map self.task = task self.max_new_tokens = int(max_new_tokens) @@ -66,7 +70,7 @@ def model_name(self): def model_path(self): """Sets the model name.""" return str( - self.base_dir / self.model_name / f'ggml-model-{llm_conf["quantization"]}.gguf') + self.base_dir / self.model_name / f'ggml-model-{self.quantization}.gguf') @model_name.setter def model_name(self, value): @@ -81,10 +85,18 @@ def hf_pipeline(self, is_local=False): """ if is_local: - hf_model = self.model_path + hf_model = Path(self.model_path).parent else: hf_model = self.model_name - quantization_config = BitsAndBytesConfig(load_in_8bit=True) + match self.quantization: + case 'Q8': + quantization_config = BitsAndBytesConfig(load_in_8bit=True) + case 'Q4': + quantization_config = BitsAndBytesConfig(load_in_4bit=True) + case _: + raise ValueError( + f'{self.quantization} is not a valid quantization. Non-local hf_pipeline takes only Q4 and Q8.') + try: # Try to load the model without passing the token tokenizer = AutoTokenizer.from_pretrained(hf_model) @@ -137,11 +149,13 @@ def llama_cpp(self): def load_model(self, model_name=None, - pipeline='llama_cpp', + pipeline=None, + quantization=None, is_local=True): """Loads the model based on the specified pipeline and model name. Args: + quantization (str): Quantization of the LLM model like Q5_K_M, f16, etc. Optional. model_name (str): The name of the model to load. Optional. pipeline (str): The pipeline to use for loading the model. Defaults to 'llama_cpp'. is_local (bool): Whether the model is loaded from a local directory. Defaults to True. @@ -149,8 +163,12 @@ def load_model(self, if model_name is not None: self.model_name = model_name + if pipeline is not None: + self.pipeline = pipeline + if quantization is not None: + self.quantization = quantization - match pipeline: + match self.pipeline: case 'llama_cpp': return self.llama_cpp() case 'hf': diff --git a/src/tests/embedding_test.py b/src/tests/embedding_test.py index 4111ace..78743a5 100644 --- a/src/tests/embedding_test.py +++ b/src/tests/embedding_test.py @@ -32,7 +32,3 @@ def test_embeddings(embedding_config): similarity_scores = [cosine_similarity(doc_vecs[0], doc_vecs[1]), cosine_similarity(doc_vecs[0], doc_vecs[2])] assert similarity_scores[0] > similarity_scores[1] - - -if __name__ == '__main__': - test_embeddings(embedding_configs[0]) diff --git a/src/tests/llm_test.py b/src/tests/llm_test.py index 90691ca..931b69b 100644 --- a/src/tests/llm_test.py +++ b/src/tests/llm_test.py @@ -1,65 +1,35 @@ -import os - -from langchain_community.vectorstores import Chroma -from langchain.text_splitter import RecursiveCharacterTextSplitter -from langchain.chains import RetrievalQA -from langchain_community.document_loaders import PyPDFLoader, DirectoryLoader -from langchain_community.embeddings.sentence_transformer import SentenceTransformerEmbeddings -from langchain_community.embeddings import HuggingFaceInstructEmbeddings +from typing import Text +import pytest from grag.components.llm import LLM -# load docs from path -path = "../../data/test/pdfs/new_papers" -loader = DirectoryLoader(path, glob="./*.pdf", loader_cls=PyPDFLoader) -documents = loader.load() -text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) -texts = text_splitter.split_documents(documents) - -# embedding_function = SentenceTransformerEmbeddings(model_name="all-mpnet-base-v2") -# https://stackoverflow.com/a/77990923/13808323 -embedding_instruction = 'Represent the document for retrival' -embedding_function = HuggingFaceInstructEmbeddings(model_name='hkunlp/instructor-xl', - model_kwargs={"device": "cuda"}) -embedding_function.embed_instruction = embedding_instruction - -vectordb = Chroma.from_documents(documents=texts, - embedding=embedding_function) -retriever = vectordb.as_retriever(search_kwargs={"k": 5}) - -llm_ = LLM() - -models_to_test = ['Llama-2-7b-chat', - 'Llama-2-13b-chat', - 'Mixtral-8x7B-Instruct-v0.1'] - -pipeline_list = ['llama_cpp', 'hf'] - - -def test_model(model_list, pipeline_list): - for pipeline in pipeline_list: - print(f'****** TESTING PIPELINE: {pipeline} ******') - for model_name in model_list: - print(f'***** MODEL: {model_name} *****') - model = llm_.load_model(model_name=model_name, - pipeline=pipeline) - qa_chain = RetrievalQA.from_chain_type(llm=model, - chain_type="stuff", - retriever=retriever, - return_source_documents=True) - queries = ["What is Flash attention?", - "How many tokens was LLaMA-2 trained on?", - "How many examples do we need to provide for each tool?", - "What are the best retrieval augmentations for LLMs?" - ] - for query in queries: - print(f'Query: {query}') - llm_response = qa_chain(query) - process_llm_response(llm_response) - print("\n") - - del model, qa_chain - - -if __name__ == "__main__": - test_model(models_to_test, pipeline_list) +# +# models_to_test = ['Llama-2-7b-chat', +# 'Llama-2-13b-chat', +# 'Mixtral-8x7B-Instruct-v0.1', +# 'gemma-7b-it'] +# +# pipeline_list = ['llama_cpp', 'hf'] + +llama_models = ['Llama-2-7b-chat', + 'Llama-2-13b-chat', + 'Mixtral-8x7B-Instruct-v0.1', + 'gemma-7b-it'] +hf_models = ['meta-llama/Llama-2-7b-chat', + 'meta-llama/Llama-2-13b-chat', + 'mistralai/Mixtral-8x7B-Instruct-v0.1', + 'google/gemma-7b-it'] +cpp_quantization = ['Q5_K_M', 'Q5_K_M', 'Q4_K_M', 'f16'] +hf_quantization = ['Q8', 'Q4', 'Q4', 'Q4'] + +params = [(model, 'llama_cpp', quant) for model, quant in zip(llama_models, cpp_quantization)] +params.extend([(model, 'hf', quant) for model, quant in zip(llama_models, cpp_quantization)]) + + +@pytest.mark.parametrize("model_name, pipeline, quantization", params) +def test_model(model_name, pipeline, quantization): + llm_ = LLM(quantization=quantization, model_name=model_name, pipeline=pipeline) + model = llm_.load_model() + response = model.invoke("Who are you?") + assert isinstance(response, Text) + del model From 4b3a281706cab6689b406a9d7598360cddb78652 Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Mon, 18 Mar 2024 19:41:09 -0400 Subject: [PATCH 05/53] Ruff format --- src/grag/components/chroma_client.py | 5 +++-- src/grag/components/embedding.py | 4 +++- src/grag/components/llm.py | 8 ++++++-- src/grag/components/multivec_retriever.py | 7 ++++--- src/grag/components/prompt.py | 4 ++-- src/grag/rag/basic_rag.py | 9 +++++---- src/tests/chroma_add_test.py | 1 + src/tests/chroma_async_test.py | 1 + src/tests/embedding_test.py | 1 - src/tests/parse_pdf_test.py | 6 +++--- 10 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/grag/components/chroma_client.py b/src/grag/components/chroma_client.py index 22368b8..a833c04 100644 --- a/src/grag/components/chroma_client.py +++ b/src/grag/components/chroma_client.py @@ -2,14 +2,15 @@ from typing import List import chromadb -from grag.components.embedding import Embedding -from grag.components.utils import get_config from langchain_community.vectorstores import Chroma from langchain_community.vectorstores.utils import filter_complex_metadata from langchain_core.documents import Document from tqdm import tqdm from tqdm.asyncio import tqdm_asyncio +from grag.components.embedding import Embedding +from grag.components.utils import get_config + chroma_conf = get_config()['chroma'] diff --git a/src/grag/components/embedding.py b/src/grag/components/embedding.py index 66f7e98..248b103 100644 --- a/src/grag/components/embedding.py +++ b/src/grag/components/embedding.py @@ -1,5 +1,7 @@ from langchain_community.embeddings import HuggingFaceInstructEmbeddings -from langchain_community.embeddings.sentence_transformer import SentenceTransformerEmbeddings +from langchain_community.embeddings.sentence_transformer import ( + SentenceTransformerEmbeddings, +) class Embedding: diff --git a/src/grag/components/llm.py b/src/grag/components/llm.py index 332d476..2994761 100644 --- a/src/grag/components/llm.py +++ b/src/grag/components/llm.py @@ -7,8 +7,12 @@ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain_community.llms import LlamaCpp from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline -from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig -from transformers import pipeline +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + BitsAndBytesConfig, + pipeline, +) from .utils import get_config diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index 1cc6e56..b38f496 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -2,13 +2,14 @@ import uuid from typing import List -from grag.components.chroma_client import ChromaClient -from grag.components.text_splitter import TextSplitter -from grag.components.utils import get_config from langchain.retrievers.multi_vector import MultiVectorRetriever from langchain.storage import LocalFileStore from langchain_core.documents import Document +from grag.components.chroma_client import ChromaClient +from grag.components.text_splitter import TextSplitter +from grag.components.utils import get_config + multivec_retriever_conf = get_config()['multivec_retriever'] diff --git a/src/grag/components/prompt.py b/src/grag/components/prompt.py index 00dff95..3c20be9 100644 --- a/src/grag/components/prompt.py +++ b/src/grag/components/prompt.py @@ -1,10 +1,10 @@ import json from pathlib import Path -from typing import List, Union, Dict, Any, Optional +from typing import Any, Dict, List, Optional, Union from langchain.prompts.few_shot import FewShotPromptTemplate from langchain_core.prompts import PromptTemplate -from pydantic import BaseModel, field_validator, Field +from pydantic import BaseModel, Field, field_validator Example = Dict[str, Any] diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index 725cd2e..0233619 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -1,13 +1,14 @@ import json from typing import List, Union +from importlib_resources import files +from langchain_core.documents import Document + from grag import prompts from grag.components.llm import LLM from grag.components.multivec_retriever import Retriever -from grag.components.prompt import Prompt, FewShotPrompt +from grag.components.prompt import FewShotPrompt, Prompt from grag.components.utils import get_config -from importlib_resources import files -from langchain_core.documents import Document conf = get_config() @@ -123,7 +124,7 @@ def output_parser_wrapper(*args, **kwargs): if conf['llm']['std_out'] == 'False': # if self.llm_.callback_manager is None: print(response) - print(f'Sources: ') + print('Sources: ') for index, source in enumerate(sources): print(f'\t{index}: {source}') diff --git a/src/tests/chroma_add_test.py b/src/tests/chroma_add_test.py index 55fdd1c..7708160 100644 --- a/src/tests/chroma_add_test.py +++ b/src/tests/chroma_add_test.py @@ -1,4 +1,5 @@ import asyncio + # add code folder to sys path import os from pathlib import Path diff --git a/src/tests/chroma_async_test.py b/src/tests/chroma_async_test.py index bd212a1..c01794a 100644 --- a/src/tests/chroma_async_test.py +++ b/src/tests/chroma_async_test.py @@ -1,4 +1,5 @@ import asyncio + # add code folder to sys path import os import time diff --git a/src/tests/embedding_test.py b/src/tests/embedding_test.py index 78743a5..6d3e45a 100644 --- a/src/tests/embedding_test.py +++ b/src/tests/embedding_test.py @@ -1,6 +1,5 @@ import numpy as np import pytest - from grag.components.embedding import Embedding diff --git a/src/tests/parse_pdf_test.py b/src/tests/parse_pdf_test.py index 30d1e28..3561958 100644 --- a/src/tests/parse_pdf_test.py +++ b/src/tests/parse_pdf_test.py @@ -19,15 +19,15 @@ def main(filename): print(f'Parsed pdf in {time_taken:2f} secs') - print(f'******** TEXT ********') + print('******** TEXT ********') for doc in docs_dict['Text']: print(doc) - print(f'******** TABLES ********') + print('******** TABLES ********') for text_doc in docs_dict['Tables']: print(text_doc) - print(f'******** IMAGES ********') + print('******** IMAGES ********') for doc in docs_dict['Images']: print(doc) From fdc632585b49be0567adb037faa05c0e17a8f8e3 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Mon, 18 Mar 2024 22:38:50 -0400 Subject: [PATCH 06/53] Create ruff_linting workflow --- .github/workflows/ruff_linting | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 .github/workflows/ruff_linting diff --git a/.github/workflows/ruff_linting b/.github/workflows/ruff_linting new file mode 100644 index 0000000..6e52c41 --- /dev/null +++ b/.github/workflows/ruff_linting @@ -0,0 +1,25 @@ +name: Ruff Linting +on: + pull_request: + branches: + - main + +jobs: + adopt-ruff: + runs-on: ubuntu-latest + steps: + - name: Check out repository code + uses: actions/checkout@v4 + + - name: Set up python + id: setup-python + uses: actions/setup-python@v5 + with: + python-version: 3.x + + - name: Install ruff + run: pip install ruff + + - name: Run the adopt-ruff action + uses: ScDor/adopt-ruff@master + From 44571befe716c5f3b816fa162e1ffa084cbce081 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 12:39:15 -0400 Subject: [PATCH 07/53] debug chroma tests --- src/grag/components/chroma_client.py | 49 +++++++------- src/tests/chroma_add_test.py | 66 ------------------- ..._test.py => chroma_async_speed_compare.py} | 0 src/tests/{prompts_test.py => prompt_test.py} | 0 4 files changed, 24 insertions(+), 91 deletions(-) delete mode 100644 src/tests/chroma_add_test.py rename src/tests/{chroma_async_test.py => chroma_async_speed_compare.py} (100%) rename src/tests/{prompts_test.py => prompt_test.py} (100%) diff --git a/src/grag/components/chroma_client.py b/src/grag/components/chroma_client.py index a833c04..72b0db7 100644 --- a/src/grag/components/chroma_client.py +++ b/src/grag/components/chroma_client.py @@ -1,4 +1,3 @@ -import asyncio from typing import List import chromadb @@ -6,7 +5,7 @@ from langchain_community.vectorstores.utils import filter_complex_metadata from langchain_core.documents import Document from tqdm import tqdm -from tqdm.asyncio import tqdm_asyncio +from tqdm.asyncio import tqdm as atqdm from grag.components.embedding import Embedding from grag.components.utils import get_config @@ -15,8 +14,7 @@ class ChromaClient: - """ - A class for connecting to a hosted Chroma Vectorstore collection. + """A class for connecting to a hosted Chroma Vectorstore collection. Attributes: host : str @@ -45,15 +43,13 @@ def __init__(self, collection_name=chroma_conf['collection_name'], embedding_type=chroma_conf['embedding_type'], embedding_model=chroma_conf['embedding_model']): + """Args: + host: IP Address of hosted Chroma Vectorstore, defaults to argument from config file + port: port address of hosted Chroma Vectorstore, defaults to argument from config file + collection_name: name of the collection in the Chroma Vectorstore, defaults to argument from config file + embedding_type: type of embedding used, supported 'sentence-transformers' and 'instructor-embedding', defaults to argument from config file + embedding_model: model name of embedding used, should correspond to the embedding_type, defaults to argument from config file """ - Args: - host: IP Address of hosted Chroma Vectorstore, defaults to argument from config file - port: port address of hosted Chroma Vectorstore, defaults to argument from config file - collection_name: name of the collection in the Chroma Vectorstore, defaults to argument from config file - embedding_type: type of embedding used, supported 'sentence-transformers' and 'instructor-embedding', defaults to argument from config file - embedding_model: model name of embedding used, should correspond to the embedding_type, defaults to argument from config file - """ - self.host: str = host self.port: str = port self.collection_name: str = collection_name @@ -71,15 +67,14 @@ def __init__(self, self.allowed_metadata_types = (str, int, float, bool) def test_connection(self, verbose=True): - ''' - Tests connection with Chroma Vectorstore + """Tests connection with Chroma Vectorstore Args: verbose: if True, prints connection status Returns: A random integer if connection is alive else None - ''' + """ response = self.chroma_client.heartbeat() if verbose: if response: @@ -89,8 +84,7 @@ def test_connection(self, verbose=True): return response async def aadd_docs(self, docs: List[Document], verbose=True): - ''' - Asynchronously adds documents to chroma vectorstore + """Asynchronously adds documents to chroma vectorstore Args: docs: List of Documents @@ -98,25 +92,30 @@ async def aadd_docs(self, docs: List[Document], verbose=True): Returns: None - ''' + """ docs = self._filter_metadata(docs) - tasks = [self.langchain_chroma.aadd_documents([doc]) for doc in docs] + # tasks = [self.langchain_chroma.aadd_documents([doc]) for doc in docs] + # if verbose: + # await tqdm_asyncio.gather(*tasks, desc=f'Adding to {self.collection_name}') + # else: + # await asyncio.gather(*tasks) if verbose: - await tqdm_asyncio.gather(*tasks, desc=f'Adding to {self.collection_name}') + for doc in atqdm(docs, desc=f'Adding documents to {self.collection_name}', total=len(docs)): + await self.langchain_chroma.aadd_documents([doc]) else: - await asyncio.gather(*tasks) + for doc in docs: + await self.langchain_chroma.aadd_documents([doc]) def add_docs(self, docs: List[Document], verbose=True): - ''' - Adds documents to chroma vectorstore + """Adds documents to chroma vectorstore - Args: + Args: docs: List of Documents verbose: Show progress bar Returns: None - ''' + """ docs = self._filter_metadata(docs) for doc in (tqdm(docs, desc=f'Adding to {self.collection_name}:') if verbose else docs): _id = self.langchain_chroma.add_documents([doc]) diff --git a/src/tests/chroma_add_test.py b/src/tests/chroma_add_test.py deleted file mode 100644 index 7708160..0000000 --- a/src/tests/chroma_add_test.py +++ /dev/null @@ -1,66 +0,0 @@ -import asyncio - -# add code folder to sys path -import os -from pathlib import Path - -from grag.components.chroma_client import ChromaClient - -data_path = Path(os.getcwd()).parents[1] / 'data' / 'Gutenberg' / 'txt' # "data/Gutenberg/txt" -docs = [ - '''And so on this rainbow day, with storms all around them, and blue sky -above, they rode only as far as the valley. But from there, before they -turned to go back, the monuments appeared close, and they loomed -grandly with the background of purple bank and creamy cloud and shafts -of golden lightning. They seemed like sentinels--guardians of a great -and beautiful love born under their lofty heights, in the lonely -silence of day, in the star-thrown shadow of night. They were like that -love. And they held Lucy and Slone, calling every day, giving a -nameless and tranquil content, binding them true to love, true to the -sage and the open, true to that wild upland home.''', - '''Slone and Lucy never rode down so far as the stately monuments, though -these held memories as hauntingly sweet as others were poignantly -bitter. Lucy never rode the King again. But Slone rode him, learned to -love him. And Lucy did not race any more. When Slone tried to stir in -her the old spirit all the response he got was a wistful shake of head -or a laugh that hid the truth or an excuse that the strain on her -ankles from Joel Creech's lasso had never mended. The girl was -unutterably happy, but it was possible that she would never race a -horse again.''', - '''Bostil wanted to be alone, to welcome the King, to lead him back to the -home corral, perhaps to hide from all eyes the change and the uplift -that would forever keep him from wronging another man. - -The late rains came and like magic, in a few days, the sage grew green -and lustrous and fresh, the gray turning to purple. - -Every morning the sun rose white and hot in a blue and cloudless sky. -And then soon the horizon line showed creamy clouds that rose and -spread and darkened. Every afternoon storms hung along the ramparts and -rainbows curved down beautiful and ethereal. The dim blackness of the -storm-clouds was split to the blinding zigzag of lightning, and the -thunder rolled and boomed, like the Colorado in flood.''' -] - - -def main(): - # print(f'Total Number of docs: {len(docs)}') - - client = ChromaClient(collection_name='test') - - print('Before Adding Docs...') - print(f'The {client.collection_name} has {client.collection.count()} documents') - - n_docs = len(docs) - print(f'Adding {n_docs} docs synchronously') - client.add_docs(docs) - print(f'Adding {n_docs} docs asynchronously') - asyncio.run(client.aadd_docs(docs)) - - print('After Adding Docs...') - print(f'The {client.collection_name} has {client.collection.count()} documents') - - -if __name__ == "__main__": - main() - print('All Tests Passed') diff --git a/src/tests/chroma_async_test.py b/src/tests/chroma_async_speed_compare.py similarity index 100% rename from src/tests/chroma_async_test.py rename to src/tests/chroma_async_speed_compare.py diff --git a/src/tests/prompts_test.py b/src/tests/prompt_test.py similarity index 100% rename from src/tests/prompts_test.py rename to src/tests/prompt_test.py From 8e517324c57dcc7fc3b1c9a5569a3e2d2986861f Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 12:39:28 -0400 Subject: [PATCH 08/53] ruff lint docstrings --- pyproject.toml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index b2fb18d..897ab02 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -103,9 +103,12 @@ line-length = 88 indent-width = 4 [tool.ruff.lint] -select = ["E4", "E7", "E9", "F", "I"] +select = ["E4", "E7", "E9", "F", "I", "D"] [tool.ruff.format] quote-style = "double" indent-style = "space" -docstring-code-format = false +docstring-code-format = true + +[tool.ruff.lint.pydocstyle] +convention = "google" From 75b479e96010184776b107b8d052e8e2e1f2478c Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 12:40:06 -0400 Subject: [PATCH 09/53] separate pipes in llm test --- src/tests/llm_test.py | 46 ++++++++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/src/tests/llm_test.py b/src/tests/llm_test.py index 931b69b..4f3b8a2 100644 --- a/src/tests/llm_test.py +++ b/src/tests/llm_test.py @@ -22,14 +22,50 @@ cpp_quantization = ['Q5_K_M', 'Q5_K_M', 'Q4_K_M', 'f16'] hf_quantization = ['Q8', 'Q4', 'Q4', 'Q4'] -params = [(model, 'llama_cpp', quant) for model, quant in zip(llama_models, cpp_quantization)] -params.extend([(model, 'hf', quant) for model, quant in zip(llama_models, cpp_quantization)]) +# params = [(model, 'llama_cpp', quant) for model, quant in zip(llama_models, cpp_quantization)] +# params.extend([(model, 'hf', quant) for model, quant in zip(llama_models, cpp_quantization)]) +# +# +# @pytest.mark.parametrize("model_name, pipeline, quantization", params) +# def test_model(model_name, pipeline, quantization): +# llm_ = LLM(quantization=quantization, model_name=model_name, pipeline=pipeline) +# model = llm_.load_model() +# response = model.invoke("Who are you?") +# assert isinstance(response, Text) +# del model -@pytest.mark.parametrize("model_name, pipeline, quantization", params) -def test_model(model_name, pipeline, quantization): - llm_ = LLM(quantization=quantization, model_name=model_name, pipeline=pipeline) +params = [(model, quant) for model, quant in zip(llama_models, cpp_quantization)] + + +@pytest.mark.parametrize("model_name, quantization", params) +def test_llamacpp_pipe(model_name, quantization): + llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='llama_cpp') model = llm_.load_model() response = model.invoke("Who are you?") assert isinstance(response, Text) del model + + +params = [(model, quant) for model, quant in zip(llama_models, cpp_quantization)] + + +@pytest.mark.parametrize("model_name, quantization", params) +def test_hf_local_pipe(model_name, quantization): + llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='hf') + model = llm_.load_model() + response = model.invoke("Who are you?") + assert isinstance(response, Text) + del model + + +params = [(model, quant) for model, quant in zip(hf_models, hf_quantization)] + + +@pytest.mark.parametrize("hf_models, quantization", params) +def test_hf_web_pipe(model_name, quantization): + llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='hf') + model = llm_.load_model(is_local=False) + response = model.invoke("Who are you?") + assert isinstance(response, Text) + del model From 9e32fe59a179654c0b5c4ffe93b82587f14c6b41 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 12:40:16 -0400 Subject: [PATCH 10/53] add readme with valid tests --- src/tests/README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 src/tests/README.md diff --git a/src/tests/README.md b/src/tests/README.md new file mode 100644 index 0000000..bf09de5 --- /dev/null +++ b/src/tests/README.md @@ -0,0 +1,10 @@ +# Tests + +## Implemented Tests + +Tests not listed below are not finalized + +- chroma_test +- embedding_test +- prompt_test + - TODO: few shot prompt From 31c3dafaa59205ebb1efae199e151c80f51d998e Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 13:10:14 -0400 Subject: [PATCH 11/53] Ruff docstring changes --- src/grag/components/embedding.py | 3 +- src/grag/components/llm.py | 23 ++++----- src/grag/components/multivec_retriever.py | 60 ++++++++++------------- src/grag/components/parse_pdf.py | 21 +++----- src/grag/components/utils.py | 18 +++---- src/grag/rag/basic_rag.py | 3 +- 6 files changed, 51 insertions(+), 77 deletions(-) diff --git a/src/grag/components/embedding.py b/src/grag/components/embedding.py index 248b103..ed483c7 100644 --- a/src/grag/components/embedding.py +++ b/src/grag/components/embedding.py @@ -5,8 +5,7 @@ class Embedding: - """ - A class for vector embeddings. + """A class for vector embeddings. Supports: huggingface sentence transformers -> model_type = 'sentence-transformers' huggingface instructor embeddings -> model_type = 'instructor-embedding' diff --git a/src/grag/components/llm.py b/src/grag/components/llm.py index 2994761..05cd322 100644 --- a/src/grag/components/llm.py +++ b/src/grag/components/llm.py @@ -24,16 +24,16 @@ class LLM: """A class for managing and utilizing large language models (LLMs). - Attributes: - model_name (str): Name of the model to be loaded. - device_map (dict): Device mapping for model execution. - task (str): The task for which the model is being used. - max_new_tokens (int): Maximum new tokens to be generated. - temperature (float): Sampling temperature for generation. - n_batch (int): Number of batches for GPU CPP. - n_ctx (int): Context size for CPP. - n_gpu_layers (int): Number of GPU layers for CPP. - """ + Attributes: + model_name (str): Name of the model to be loaded. + device_map (dict): Device mapping for model execution. + task (str): The task for which the model is being used. + max_new_tokens (int): Maximum new tokens to be generated. + temperature (float): Sampling temperature for generation. + n_batch (int): Number of batches for GPU CPP. + n_ctx (int): Context size for CPP. + n_gpu_layers (int): Number of GPU layers for CPP. + """ def __init__(self, model_name=llm_conf["model_name"], @@ -87,7 +87,6 @@ def hf_pipeline(self, is_local=False): Args: is_local (bool): Whether to load the model from a local path. """ - if is_local: hf_model = Path(self.model_path).parent else: @@ -137,7 +136,6 @@ def hf_pipeline(self, is_local=False): def llama_cpp(self): """Loads the model using a custom CPP pipeline.""" - # https://stackoverflow.com/a/77734908/13808323 llm = LlamaCpp( model_path=self.model_path, @@ -164,7 +162,6 @@ def load_model(self, pipeline (str): The pipeline to use for loading the model. Defaults to 'llama_cpp'. is_local (bool): Whether the model is loaded from a local directory. Defaults to True. """ - if model_name is not None: self.model_name = model_name if pipeline is not None: diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index b38f496..a839917 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -14,8 +14,7 @@ class Retriever: - """ - A class for multi vector retriever, it connects to a vector database and a local file store. + """A class for multi vector retriever, it connects to a vector database and a local file store. It is used to return most similar chunks from a vector store but has the additional funcationality to return a linked document, chunk, etc. @@ -36,12 +35,11 @@ def __init__(self, id_key: str = multivec_retriever_conf['id_key'], namespace: str = multivec_retriever_conf['namespace'], top_k=1): - """ - Args: - store_path: Path to the local file store, defaults to argument from config file - id_key: A key prefix for identifying documents, defaults to argument from config file - namespace: A namespace for producing unique id, defaults to argument from congig file - top_k: Number of top chunks to return from similarity search, defaults to 1 + """Args: + store_path: Path to the local file store, defaults to argument from config file + id_key: A key prefix for identifying documents, defaults to argument from config file + namespace: A namespace for producing unique id, defaults to argument from congig file + top_k: Number of top chunks to return from similarity search, defaults to 1 """ self.store_path = store_path self.id_key = id_key @@ -58,8 +56,7 @@ def __init__(self, self.retriever.search_kwargs = {'k': self.top_k} def id_gen(self, doc: Document) -> str: - """ - Takes a document and returns a unique id (uuid5) using the namespace and document source. + """Takes a document and returns a unique id (uuid5) using the namespace and document source. This ensures that a single document always gets the same unique id. Args: @@ -71,8 +68,7 @@ def id_gen(self, doc: Document) -> str: return uuid.uuid5(self.namespace, doc.metadata['source']).hex def gen_doc_ids(self, docs: List[Document]) -> List[str]: - """ - Takes a list of documents and produces a list of unique id, refer id_gen method for more details. + """Takes a list of documents and produces a list of unique id, refer id_gen method for more details. Args: docs: List of langchain_core.documents.Document @@ -84,8 +80,7 @@ def gen_doc_ids(self, docs: List[Document]) -> List[str]: return [self.id_gen(doc) for doc in docs] def split_docs(self, docs: List[Document]) -> List[Document]: - """ - Takes a list of documents and splits them into smaller chunks using TextSplitter from compoenents.text_splitter + """Takes a list of documents and splits them into smaller chunks using TextSplitter from compoenents.text_splitter Also adds the unique parent document id into metadata Args: @@ -105,9 +100,9 @@ def split_docs(self, docs: List[Document]) -> List[Document]: return chunks def add_docs(self, docs: List[Document]): - """ - Takes a list of documents, splits them using the split_docs method and then adds them into the vector database + """Takes a list of documents, splits them using the split_docs method and then adds them into the vector database and adds the parent document into the file store. + Args: docs: List of langchain_core.documents.Document @@ -121,24 +116,23 @@ def add_docs(self, docs: List[Document]): self.retriever.docstore.mset(list(zip(doc_ids, docs))) async def aadd_docs(self, docs: List[Document]): - """ - Takes a list of documents, splits them using the split_docs method and then adds them into the vector database - and adds the parent document into the file store. - Args: - docs: List of langchain_core.documents.Document + """Takes a list of documents, splits them using the split_docs method and then adds them into the vector database + and adds the parent document into the file store. - Returns: - None + Args: + docs: List of langchain_core.documents.Document - """ + Returns: + None + + """ chunks = self.split_docs(docs) doc_ids = self.gen_doc_ids(docs) await asyncio.run(self.client.aadd_docs(chunks)) self.retriever.docstore.mset(list(zip(doc_ids))) def get_chunk(self, query: str, with_score=False, top_k=None): - """ - Returns the most (cosine) similar chunks from the vector database. + """Returns the most (cosine) similar chunks from the vector database. Args: query: A query string @@ -162,8 +156,7 @@ def get_chunk(self, query: str, with_score=False, top_k=None): ) async def aget_chunk(self, query: str, with_score=False, top_k=None): - """ - Returns the most (cosine) similar chunks from the vector database, asynchronously. + """Returns the most (cosine) similar chunks from the vector database, asynchronously. Args: query: A query string @@ -186,8 +179,7 @@ async def aget_chunk(self, query: str, with_score=False, top_k=None): ) def get_doc(self, query: str): - """ - Returns the parent document of the most (cosine) similar chunk from the vector database. + """Returns the parent document of the most (cosine) similar chunk from the vector database. Args: query: A query string @@ -198,8 +190,8 @@ def get_doc(self, query: str): return self.retriever.get_relevant_documents(query=query) async def aget_doc(self, query: str): - """ - Returns the parent documents of the most (cosine) similar chunks from the vector database. + """Returns the parent documents of the most (cosine) similar chunks from the vector database. + Args: query: A query string Returns: @@ -209,8 +201,8 @@ async def aget_doc(self, query: str): return await self.retriever.aget_relevant_documents(query=query) def get_docs_from_chunks(self, chunks: List[Document], one_to_one=False): - """ - Returns the parent documents of chunks. + """Returns the parent documents of chunks. + Args: chunks: chunks from vector store one_to_one: if True, returns parent doc for each chunk diff --git a/src/grag/components/parse_pdf.py b/src/grag/components/parse_pdf.py index 2b00579..00d0fa0 100644 --- a/src/grag/components/parse_pdf.py +++ b/src/grag/components/parse_pdf.py @@ -7,8 +7,7 @@ class ParsePDF: - """ - Parsing and partitioning PDF documents into Text, Table or Image elements. + """Parsing and partitioning PDF documents into Text, Table or Image elements. Attributes: single_text_out (bool): Whether to combine all text elements into a single output document. @@ -48,8 +47,7 @@ def __init__(self, self.table_as_html = table_as_html def partition(self, path: str): - """ - Partitions a PDF document into elements based on the instance's configuration. + """Partitions a PDF document into elements based on the instance's configuration. Parameters: path (str): The file path of the PDF document to be parsed and partitioned. @@ -70,8 +68,7 @@ def partition(self, path: str): return partitions def classify(self, partitions): - """ - Classifies the partitioned elements into Text, Tables, and Images list in a dictionary. + """Classifies the partitioned elements into Text, Tables, and Images list in a dictionary. Add captions for each element (if available). Parameters: @@ -145,8 +142,7 @@ def text_concat(self, elements) -> str: return full_text def process_text(self, elements): - """ - Processes text elements into langchain Documents. + """Processes text elements into langchain Documents. Parameters: elements (list): The list of text elements to be processed. @@ -168,8 +164,7 @@ def process_text(self, elements): return docs def process_tables(self, elements): - """ - Processes table elements into Documents, including handling of captions if specified. + """Processes table elements into Documents, including handling of captions if specified. Parameters: elements (list): The list of table elements (and optional captions) to be processed. @@ -199,8 +194,7 @@ def process_tables(self, elements): return docs def process_images(self, elements): - """ - Processes image elements into Documents, including handling of captions if specified. + """Processes image elements into Documents, including handling of captions if specified. Parameters: elements (list): The list of image elements (and optional captions) to be processed. @@ -224,8 +218,7 @@ def process_images(self, elements): return docs def load_file(self, path): - """ - Loads a PDF file, partitions and classifies its elements, and processes these elements into Documents. + """Loads a PDF file, partitions and classifies its elements, and processes these elements into Documents. Parameters: path (str): The file path of the PDF document to be loaded and processed. diff --git a/src/grag/components/utils.py b/src/grag/components/utils.py index a29af6e..ea3c041 100644 --- a/src/grag/components/utils.py +++ b/src/grag/components/utils.py @@ -10,8 +10,7 @@ def stuff_docs(docs: List[Document]) -> str: - """ - Args: + """Args: docs: List of langchain_core.documents.Document Returns: @@ -21,8 +20,7 @@ def stuff_docs(docs: List[Document]) -> str: def reformat_text_with_line_breaks(input_text, max_width=110): - """ - Reformat the given text to ensure each line does not exceed a specific width, + """Reformat the given text to ensure each line does not exceed a specific width, preserving existing line breaks. Args: @@ -45,8 +43,7 @@ def reformat_text_with_line_breaks(input_text, max_width=110): def display_llm_output_and_sources(response_from_llm): - """ - Displays the result from an LLM response and lists the sources. + """Displays the result from an LLM response and lists the sources. Args: response_from_llm (dict): The response object from an LLM which includes the result and source documents. @@ -63,8 +60,7 @@ def display_llm_output_and_sources(response_from_llm): def load_prompt(json_file: str | os.PathLike, return_input_vars=False): - """ - Loads a prompt template from json file and returns a langchain ChatPromptTemplate + """Loads a prompt template from json file and returns a langchain ChatPromptTemplate Args: json_file: path to the prompt template json file. @@ -84,8 +80,7 @@ def load_prompt(json_file: str | os.PathLike, return_input_vars=False): def find_config_path(current_path: Path) -> Path: - """ - Finds the path of the 'config.ini' file by traversing up the directory tree from the current path. + """Finds the path of the 'config.ini' file by traversing up the directory tree from the current path. This function starts at the current path and moves up the directory tree until it finds a file named 'config.ini'. If 'config.ini' is not found by the time the root of the directory tree is reached, a FileNotFoundError is raised. @@ -108,8 +103,7 @@ def find_config_path(current_path: Path) -> Path: def get_config() -> ConfigParser: - """ - Retrieves and parses the configuration settings from the 'config.ini' file. + """Retrieves and parses the configuration settings from the 'config.ini' file. This function locates the 'config.ini' file by calling `find_config_path` using the script's current location. It initializes a `ConfigParser` object to read the configuration settings from the located 'config.ini' file. diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index 0233619..18fbbc4 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -108,8 +108,7 @@ def prompt_matcher(self): @staticmethod def stuff_docs(docs: List[Document]) -> str: - """ - Args: + """Args: docs: List of langchain_core.documents.Document Returns: From b05818f5ae2adeb444d7e5960a8a0276e927bea4 Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Tue, 19 Mar 2024 16:34:40 -0400 Subject: [PATCH 12/53] Modified LLM tests --- src/grag/components/llm.py | 4 +++- src/tests/llm_test.py | 42 +++++++++++++++++++------------------- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/src/grag/components/llm.py b/src/grag/components/llm.py index 05cd322..5192881 100644 --- a/src/grag/components/llm.py +++ b/src/grag/components/llm.py @@ -153,7 +153,7 @@ def load_model(self, model_name=None, pipeline=None, quantization=None, - is_local=True): + is_local=None): """Loads the model based on the specified pipeline and model name. Args: @@ -168,6 +168,8 @@ def load_model(self, self.pipeline = pipeline if quantization is not None: self.quantization = quantization + if is_local is None: + is_local = False match self.pipeline: case 'llama_cpp': diff --git a/src/tests/llm_test.py b/src/tests/llm_test.py index 4f3b8a2..14a5193 100644 --- a/src/tests/llm_test.py +++ b/src/tests/llm_test.py @@ -15,8 +15,8 @@ 'Llama-2-13b-chat', 'Mixtral-8x7B-Instruct-v0.1', 'gemma-7b-it'] -hf_models = ['meta-llama/Llama-2-7b-chat', - 'meta-llama/Llama-2-13b-chat', +hf_models = ['meta-llama/Llama-2-7b-chat-hf', + 'meta-llama/Llama-2-13b-chat-hf', 'mistralai/Mixtral-8x7B-Instruct-v0.1', 'google/gemma-7b-it'] cpp_quantization = ['Q5_K_M', 'Q5_K_M', 'Q4_K_M', 'f16'] @@ -33,15 +33,27 @@ # response = model.invoke("Who are you?") # assert isinstance(response, Text) # del model +# +# +# params = [(model, quant) for model, quant in zip(llama_models, cpp_quantization)] +# +# +# @pytest.mark.parametrize("model_name, quantization", params) +# def test_hf_local_pipe(model_name, quantization): +# llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='hf') +# model = llm_.load_model() +# response = model.invoke("Who are you?") +# assert isinstance(response, Text) +# del model -params = [(model, quant) for model, quant in zip(llama_models, cpp_quantization)] +params = [(model, quant) for model, quant in zip(hf_models, hf_quantization)] -@pytest.mark.parametrize("model_name, quantization", params) -def test_llamacpp_pipe(model_name, quantization): - llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='llama_cpp') - model = llm_.load_model() +@pytest.mark.parametrize("hf_models, quantization", params) +def test_hf_web_pipe(hf_models, quantization): + llm_ = LLM(quantization=quantization, model_name=hf_models, pipeline='hf') + model = llm_.load_model(is_local=False) response = model.invoke("Who are you?") assert isinstance(response, Text) del model @@ -51,21 +63,9 @@ def test_llamacpp_pipe(model_name, quantization): @pytest.mark.parametrize("model_name, quantization", params) -def test_hf_local_pipe(model_name, quantization): - llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='hf') +def test_llamacpp_pipe(model_name, quantization): + llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='llama_cpp') model = llm_.load_model() response = model.invoke("Who are you?") assert isinstance(response, Text) del model - - -params = [(model, quant) for model, quant in zip(hf_models, hf_quantization)] - - -@pytest.mark.parametrize("hf_models, quantization", params) -def test_hf_web_pipe(model_name, quantization): - llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='hf') - model = llm_.load_model(is_local=False) - response = model.invoke("Who are you?") - assert isinstance(response, Text) - del model From 255112c5f1b2db48711346c178d06785038791ac Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Tue, 19 Mar 2024 16:45:55 -0400 Subject: [PATCH 13/53] all test cases passed --- src/tests/llm_test.py | 38 ++------------------------------------ 1 file changed, 2 insertions(+), 36 deletions(-) diff --git a/src/tests/llm_test.py b/src/tests/llm_test.py index 14a5193..44de0dd 100644 --- a/src/tests/llm_test.py +++ b/src/tests/llm_test.py @@ -3,50 +3,16 @@ import pytest from grag.components.llm import LLM -# -# models_to_test = ['Llama-2-7b-chat', -# 'Llama-2-13b-chat', -# 'Mixtral-8x7B-Instruct-v0.1', -# 'gemma-7b-it'] -# -# pipeline_list = ['llama_cpp', 'hf'] - llama_models = ['Llama-2-7b-chat', 'Llama-2-13b-chat', 'Mixtral-8x7B-Instruct-v0.1', 'gemma-7b-it'] hf_models = ['meta-llama/Llama-2-7b-chat-hf', 'meta-llama/Llama-2-13b-chat-hf', - 'mistralai/Mixtral-8x7B-Instruct-v0.1', + # 'mistralai/Mixtral-8x7B-Instruct-v0.1', 'google/gemma-7b-it'] cpp_quantization = ['Q5_K_M', 'Q5_K_M', 'Q4_K_M', 'f16'] -hf_quantization = ['Q8', 'Q4', 'Q4', 'Q4'] - -# params = [(model, 'llama_cpp', quant) for model, quant in zip(llama_models, cpp_quantization)] -# params.extend([(model, 'hf', quant) for model, quant in zip(llama_models, cpp_quantization)]) -# -# -# @pytest.mark.parametrize("model_name, pipeline, quantization", params) -# def test_model(model_name, pipeline, quantization): -# llm_ = LLM(quantization=quantization, model_name=model_name, pipeline=pipeline) -# model = llm_.load_model() -# response = model.invoke("Who are you?") -# assert isinstance(response, Text) -# del model -# -# -# params = [(model, quant) for model, quant in zip(llama_models, cpp_quantization)] -# -# -# @pytest.mark.parametrize("model_name, quantization", params) -# def test_hf_local_pipe(model_name, quantization): -# llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='hf') -# model = llm_.load_model() -# response = model.invoke("Who are you?") -# assert isinstance(response, Text) -# del model - - +hf_quantization = ['Q8', 'Q4', 'Q4'] # , 'Q4'] params = [(model, quant) for model, quant in zip(hf_models, hf_quantization)] From c8ebb949583df04a29bc2f20b139f125667deff6 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 17:05:10 -0400 Subject: [PATCH 14/53] Restructure tests --- src/__init__.py | 0 src/tests/__init__.py | 0 src/tests/chroma_async_speed_compare.py | 55 ------------------- src/tests/components/__init__.py | 0 src/tests/{ => components}/chroma_test.py | 0 src/tests/{ => components}/embedding_test.py | 0 src/tests/{ => components}/llm_test.py | 0 .../multivec_retriever_test.py | 0 src/tests/{ => components}/parse_pdf_test.py | 0 src/tests/{ => components}/prompt_test.py | 0 src/tests/rag/__init__.py | 0 src/tests/{ => rag}/basic_rag_test.py | 0 12 files changed, 55 deletions(-) create mode 100644 src/__init__.py create mode 100644 src/tests/__init__.py delete mode 100644 src/tests/chroma_async_speed_compare.py create mode 100644 src/tests/components/__init__.py rename src/tests/{ => components}/chroma_test.py (100%) rename src/tests/{ => components}/embedding_test.py (100%) rename src/tests/{ => components}/llm_test.py (100%) rename src/tests/{ => components}/multivec_retriever_test.py (100%) rename src/tests/{ => components}/parse_pdf_test.py (100%) rename src/tests/{ => components}/prompt_test.py (100%) create mode 100644 src/tests/rag/__init__.py rename src/tests/{ => rag}/basic_rag_test.py (100%) diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tests/__init__.py b/src/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tests/chroma_async_speed_compare.py b/src/tests/chroma_async_speed_compare.py deleted file mode 100644 index c01794a..0000000 --- a/src/tests/chroma_async_speed_compare.py +++ /dev/null @@ -1,55 +0,0 @@ -import asyncio - -# add code folder to sys path -import os -import time -from pathlib import Path - -import numpy as np -from grag.components.chroma_client import ChromaClient -from tqdm import tqdm - -data_path = Path(os.getcwd()).parents[1] / 'data' / 'Gutenberg' / 'txt' # "data/Gutenberg/txt" - - -def main(): - docs = load_split_dir(data_path) - print(f'Total Number of docs: {len(docs)}') - - client = ChromaClient() - - print('Before Adding Docs...') - print(f'The {client.collection_name} has {client.collection.count()} documents') - - n_docs = 100 - n_steps = 10 - if n_steps * n_docs > len(docs): - raise Exception('Not enough docs') - - sync_times = [] - async_times = [] - - for step in tqdm(range(n_steps), desc='Sync test'): - start = time.perf_counter() - client.add_docs(docs[step:n_docs * step]) - sync_times.append(time.perf_counter() - start) - - print(f'Avg Sync times {np.mean(sync_times)}') - print(f'Min Sync time {np.min(sync_times)}') - print(f'Max Sync time {np.max(sync_times)}') - - for step in tqdm(range(n_steps), desc='Async test'): - start = time.perf_counter() - asyncio.run(client.aadd_docs(docs[step:n_docs * step])) - async_times.append(time.perf_counter() - start) - - print(f'Avg Async times {np.mean(async_times)}') - print(f'Min Async time {np.min(async_times)}') - print(f'Max Async time {np.max(async_times)}') - - print('After Adding Docs...') - print(f'The {client.collection_name} has {client.collection.count()} documents') - - -if __name__ == "__main__": - main() diff --git a/src/tests/components/__init__.py b/src/tests/components/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tests/chroma_test.py b/src/tests/components/chroma_test.py similarity index 100% rename from src/tests/chroma_test.py rename to src/tests/components/chroma_test.py diff --git a/src/tests/embedding_test.py b/src/tests/components/embedding_test.py similarity index 100% rename from src/tests/embedding_test.py rename to src/tests/components/embedding_test.py diff --git a/src/tests/llm_test.py b/src/tests/components/llm_test.py similarity index 100% rename from src/tests/llm_test.py rename to src/tests/components/llm_test.py diff --git a/src/tests/multivec_retriever_test.py b/src/tests/components/multivec_retriever_test.py similarity index 100% rename from src/tests/multivec_retriever_test.py rename to src/tests/components/multivec_retriever_test.py diff --git a/src/tests/parse_pdf_test.py b/src/tests/components/parse_pdf_test.py similarity index 100% rename from src/tests/parse_pdf_test.py rename to src/tests/components/parse_pdf_test.py diff --git a/src/tests/prompt_test.py b/src/tests/components/prompt_test.py similarity index 100% rename from src/tests/prompt_test.py rename to src/tests/components/prompt_test.py diff --git a/src/tests/rag/__init__.py b/src/tests/rag/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tests/basic_rag_test.py b/src/tests/rag/basic_rag_test.py similarity index 100% rename from src/tests/basic_rag_test.py rename to src/tests/rag/basic_rag_test.py From 2e09499bbd4064751db5f500632252e32ebe2f1e Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 17:06:57 -0400 Subject: [PATCH 15/53] Rename chroma_test to chroma_client_test --- src/tests/components/{chroma_test.py => chroma_client_test.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/tests/components/{chroma_test.py => chroma_client_test.py} (100%) diff --git a/src/tests/components/chroma_test.py b/src/tests/components/chroma_client_test.py similarity index 100% rename from src/tests/components/chroma_test.py rename to src/tests/components/chroma_client_test.py From 43dd7b876be901e332fabf3c5f3fdc6499786ee3 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 17:07:39 -0400 Subject: [PATCH 16/53] Remove not relevant tests --- .../components/multivec_retriever_test.py | 120 +++++++++--------- src/tests/components/parse_pdf_test.py | 82 ++++++------ 2 files changed, 101 insertions(+), 101 deletions(-) diff --git a/src/tests/components/multivec_retriever_test.py b/src/tests/components/multivec_retriever_test.py index e8af9d1..6c94882 100644 --- a/src/tests/components/multivec_retriever_test.py +++ b/src/tests/components/multivec_retriever_test.py @@ -1,62 +1,62 @@ -# add code folder to sys path -import os -from pathlib import Path - -from grag.components.multivec_retriever import Retriever -from langchain_community.document_loaders import DirectoryLoader, TextLoader - -# %%% -# data_path = "data/pdf/9809" -data_path = Path(os.getcwd()).parents[1] / 'data' / 'Gutenberg' / 'txt' # "data/Gutenberg/txt" -# %% -retriever = Retriever(top_k=3) - -new_docs = True - -if new_docs: - # loading text files from data_path - loader = DirectoryLoader(data_path, - glob="*.txt", - loader_cls=TextLoader, - show_progress=True, - use_multithreading=True) - print('Loading Files: ') - docs = loader.load() - # %% - # limit docs for testing - docs = docs[:100] - - # %% - # adding chunks and parent doc - retriever.add_docs(docs) -# %% -# testing retrival -query = 'Thomas H. Huxley' - -# Retrieving the 3 most relevant small chunk -chunk_result = retriever.get_chunk(query) - -# Retrieving the most relevant document -doc_result = retriever.get_doc(query) - -# Ensuring that the length of chunk is smaller than length of doc -chunk_len = [len(chunk.page_content) for chunk in chunk_result] -print(f'Length of chunks : {chunk_len}') -doc_len = [len(doc.page_content) for doc in doc_result] -print(f'Length of doc : {doc_len}') -len_test = [c_len < d_len for c_len, d_len in zip(chunk_len, doc_len)] -print(f'Is len of chunk less than len of doc?: {len_test} ') - -# Ensuring both the chunk and document match the source -chunk_sources = [chunk.metadata['source'] for chunk in chunk_result] -doc_sources = [doc.metadata['source'] for doc in doc_result] -source_test = [source[0] == source[1] for source in zip(chunk_sources, doc_sources)] -print(f'Does source of chunk and doc match? : {source_test}') - -# # Ensuring both the chunk and document match the source -# source_test = chunk_result.metadata['source'] == doc_result.metadata['source'] -# print(f'Does source of chunk and doc match? : {source_test}') +# # add code folder to sys path +# import os +# from pathlib import Path +# +# from grag.components.multivec_retriever import Retriever +# from langchain_community.document_loaders import DirectoryLoader, TextLoader +# +# # %%% +# # data_path = "data/pdf/9809" +# data_path = Path(os.getcwd()).parents[1] / 'data' / 'Gutenberg' / 'txt' # "data/Gutenberg/txt" +# # %% +# retriever = Retriever(top_k=3) +# +# new_docs = True +# +# if new_docs: +# # loading text files from data_path +# loader = DirectoryLoader(data_path, +# glob="*.txt", +# loader_cls=TextLoader, +# show_progress=True, +# use_multithreading=True) +# print('Loading Files: ') +# docs = loader.load() +# # %% +# # limit docs for testing +# docs = docs[:100] +# +# # %% +# # adding chunks and parent doc +# retriever.add_docs(docs) +# # %% +# # testing retrival +# query = 'Thomas H. Huxley' +# +# # Retrieving the 3 most relevant small chunk +# chunk_result = retriever.get_chunk(query) +# +# # Retrieving the most relevant document +# doc_result = retriever.get_doc(query) +# # # Ensuring that the length of chunk is smaller than length of doc -# len_test = chunk_len <= doc_len +# chunk_len = [len(chunk.page_content) for chunk in chunk_result] +# print(f'Length of chunks : {chunk_len}') +# doc_len = [len(doc.page_content) for doc in doc_result] +# print(f'Length of doc : {doc_len}') +# len_test = [c_len < d_len for c_len, d_len in zip(chunk_len, doc_len)] # print(f'Is len of chunk less than len of doc?: {len_test} ') -# %% +# +# # Ensuring both the chunk and document match the source +# chunk_sources = [chunk.metadata['source'] for chunk in chunk_result] +# doc_sources = [doc.metadata['source'] for doc in doc_result] +# source_test = [source[0] == source[1] for source in zip(chunk_sources, doc_sources)] +# print(f'Does source of chunk and doc match? : {source_test}') +# +# # # Ensuring both the chunk and document match the source +# # source_test = chunk_result.metadata['source'] == doc_result.metadata['source'] +# # print(f'Does source of chunk and doc match? : {source_test}') +# # # Ensuring that the length of chunk is smaller than length of doc +# # len_test = chunk_len <= doc_len +# # print(f'Is len of chunk less than len of doc?: {len_test} ') +# # %% diff --git a/src/tests/components/parse_pdf_test.py b/src/tests/components/parse_pdf_test.py index 3561958..668f8f1 100644 --- a/src/tests/components/parse_pdf_test.py +++ b/src/tests/components/parse_pdf_test.py @@ -1,41 +1,41 @@ -# add code folder to sys path -import time -from pathlib import Path - -from grag.components.parse_pdf import ParsePDF -from grag.components.utils import get_config - -data_path = Path(get_config()['data']['data_path']) -# %% -data_path = data_path / 'test' / 'pdf' # "data/test/pdf" - - -def main(filename): - file_path = data_path / filename - pdf_parser = ParsePDF() - start_time = time.time() - docs_dict = pdf_parser.load_file(file_path) - time_taken = time.time() - start_time - - print(f'Parsed pdf in {time_taken:2f} secs') - - print('******** TEXT ********') - for doc in docs_dict['Text']: - print(doc) - - print('******** TABLES ********') - for text_doc in docs_dict['Tables']: - print(text_doc) - - print('******** IMAGES ********') - for doc in docs_dict['Images']: - print(doc) - - return docs_dict - - -if __name__ == "__main__": - filename = 'he_pdsw12.pdf' - print(f'Parsing: {filename}') - docs = main(filename) - print('All Tests Passed') +# # add code folder to sys path +# import time +# from pathlib import Path +# +# from grag.components.parse_pdf import ParsePDF +# from grag.components.utils import get_config +# +# data_path = Path(get_config()['data']['data_path']) +# # %% +# data_path = data_path / 'test' / 'pdf' # "data/test/pdf" +# +# +# def main(filename): +# file_path = data_path / filename +# pdf_parser = ParsePDF() +# start_time = time.time() +# docs_dict = pdf_parser.load_file(file_path) +# time_taken = time.time() - start_time +# +# print(f'Parsed pdf in {time_taken:2f} secs') +# +# print('******** TEXT ********') +# for doc in docs_dict['Text']: +# print(doc) +# +# print('******** TABLES ********') +# for text_doc in docs_dict['Tables']: +# print(text_doc) +# +# print('******** IMAGES ********') +# for doc in docs_dict['Images']: +# print(doc) +# +# return docs_dict +# +# +# if __name__ == "__main__": +# filename = 'he_pdsw12.pdf' +# print(f'Parsing: {filename}') +# docs = main(filename) +# print('All Tests Passed') From 7552ae85d4c884baf3e7527d5c3ff392780edbca Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Tue, 19 Mar 2024 18:37:47 -0400 Subject: [PATCH 17/53] All tests passed for basic RAG --- src/config.ini | 4 ++-- src/grag/rag/basic_rag.py | 12 ++++++------ src/tests/rag/basic_rag_test.py | 23 +++++++++++++++++++++-- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/src/config.ini b/src/config.ini index b99511c..452ac04 100644 --- a/src/config.ini +++ b/src/config.ini @@ -1,5 +1,5 @@ [llm] -model_name : Llama-2-13b-chat +model_name : Llama-2-7b-chat # meta-llama/Llama-2-70b-chat-hf Mixtral-8x7B-Instruct-v0.1 quantization : Q5_K_M pipeline : llama_cpp @@ -9,7 +9,7 @@ max_new_tokens : 1024 temperature : 0.1 n_batch_gpu_cpp : 1024 n_ctx_cpp : 6000 -n_gpu_layers_cpp : 18 +n_gpu_layers_cpp : -1 # The number of layers to put on the GPU. Mixtral-18 std_out : True base_dir : ${root:root_path}/models diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index 18fbbc4..1e33ff6 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -1,14 +1,13 @@ import json from typing import List, Union -from importlib_resources import files -from langchain_core.documents import Document - from grag import prompts from grag.components.llm import LLM from grag.components.multivec_retriever import Retriever -from grag.components.prompt import FewShotPrompt, Prompt +from grag.components.prompt import Prompt, FewShotPrompt from grag.components.utils import get_config +from importlib_resources import files +from langchain_core.documents import Document conf = get_config() @@ -16,7 +15,7 @@ class BasicRAG: def __init__(self, model_name=None, - doc_chain='refine', + doc_chain='stuff', task='QA', llm_kwargs=None, retriever_kwargs=None, @@ -34,12 +33,12 @@ def __init__(self, self.llm_ = LLM(**llm_kwargs) self.prompt_path = files(prompts) + self.custom_prompt = custom_prompt self._task = 'QA' self.model_name = model_name self.doc_chain = doc_chain self.task = task - self.custom_prompt = custom_prompt if self.custom_prompt is None: self.main_prompt = Prompt.load(self.prompt_path.joinpath(self.main_prompt_name)) @@ -126,6 +125,7 @@ def output_parser_wrapper(*args, **kwargs): print('Sources: ') for index, source in enumerate(sources): print(f'\t{index}: {source}') + return response, sources return output_parser_wrapper diff --git a/src/tests/rag/basic_rag_test.py b/src/tests/rag/basic_rag_test.py index 548804f..72991d1 100644 --- a/src/tests/rag/basic_rag_test.py +++ b/src/tests/rag/basic_rag_test.py @@ -1,4 +1,23 @@ +from typing import Text, List + from grag.rag.basic_rag import BasicRAG -rag = BasicRAG() -print(rag('What is simulated annealing?')) + +def test_rag_stuff(): + rag = BasicRAG(doc_chain='stuff') + response, sources = rag('What is simulated annealing?') + assert isinstance(response, Text) + assert isinstance(sources, List) + assert all(isinstance(s, str) for s in sources) + del rag.llm + + +def test_rag_refine(): + rag = BasicRAG(doc_chain='refine') + response, sources = rag('What is simulated annealing?') + # assert isinstance(response, Text) + assert isinstance(response, List) + assert all(isinstance(s, str) for s in response) + assert isinstance(sources, List) + assert all(isinstance(s, str) for s in sources) + del rag.llm From 7ab4c3fe0dccbd464c01b3cf9f26753739c7dc78 Mon Sep 17 00:00:00 2001 From: Sanchit Vijay Date: Tue, 19 Mar 2024 19:21:39 -0400 Subject: [PATCH 18/53] Rename ruff_linting to ruff_linting.yml --- .github/workflows/{ruff_linting => ruff_linting.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{ruff_linting => ruff_linting.yml} (100%) diff --git a/.github/workflows/ruff_linting b/.github/workflows/ruff_linting.yml similarity index 100% rename from .github/workflows/ruff_linting rename to .github/workflows/ruff_linting.yml From dccd77b2a63cbd12223b5ddf21d02a06ed174db0 Mon Sep 17 00:00:00 2001 From: Sanchit Vijay Date: Tue, 19 Mar 2024 19:32:44 -0400 Subject: [PATCH 19/53] Update ruff_linting.yml --- .github/workflows/ruff_linting.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ruff_linting.yml b/.github/workflows/ruff_linting.yml index 6e52c41..802ca63 100644 --- a/.github/workflows/ruff_linting.yml +++ b/.github/workflows/ruff_linting.yml @@ -21,5 +21,5 @@ jobs: run: pip install ruff - name: Run the adopt-ruff action - uses: ScDor/adopt-ruff@master + uses: chartboost/ruff-action@v1 From 2d7c879a1232a2e72d5a51332dc00df8accd9a15 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 19:40:23 -0400 Subject: [PATCH 20/53] Create ruff_commit.yml --- .github/workflows/main.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 .github/workflows/main.yml diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000..42787bf --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,16 @@ +name: Ruff and commit +on: push + +jobs: + lint: + runs-on: ubuntu_latest + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + - run: pip install ruff + - run: | + ruff check src/ + ruff fix src/ + - uses: stefabzweifel/git-auto-commit-action@v4 + with: + commit_message: 'style fixes by ruff' From 4194cdde003d7b66b572e0cef81ef9252b1f0cea Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Tue, 19 Mar 2024 19:41:23 -0400 Subject: [PATCH 21/53] Rename main.yml to ruff_commit.yml --- .github/workflows/{main.yml => ruff_commit.yml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename .github/workflows/{main.yml => ruff_commit.yml} (100%) diff --git a/.github/workflows/main.yml b/.github/workflows/ruff_commit.yml similarity index 100% rename from .github/workflows/main.yml rename to .github/workflows/ruff_commit.yml From fb61922cef753c7600cab6cd9129ffd425936c10 Mon Sep 17 00:00:00 2001 From: Sanchit Vijay Date: Tue, 19 Mar 2024 19:44:06 -0400 Subject: [PATCH 22/53] Update ruff_commit.yml --- .github/workflows/ruff_commit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ruff_commit.yml b/.github/workflows/ruff_commit.yml index 42787bf..fe64b9d 100644 --- a/.github/workflows/ruff_commit.yml +++ b/.github/workflows/ruff_commit.yml @@ -11,6 +11,6 @@ jobs: - run: | ruff check src/ ruff fix src/ - - uses: stefabzweifel/git-auto-commit-action@v4 + - uses: stefanzweifel/git-auto-commit-action@v4 with: commit_message: 'style fixes by ruff' From 0559d19c8ef0ff3e53625c8d7d25a0eb5c64f7e9 Mon Sep 17 00:00:00 2001 From: Sanchit Vijay Date: Tue, 19 Mar 2024 19:50:02 -0400 Subject: [PATCH 23/53] Update ruff_commit.yml --- .github/workflows/ruff_commit.yml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/ruff_commit.yml b/.github/workflows/ruff_commit.yml index fe64b9d..2ffff92 100644 --- a/.github/workflows/ruff_commit.yml +++ b/.github/workflows/ruff_commit.yml @@ -8,9 +8,8 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install ruff - - run: | - ruff check src/ - ruff fix src/ + - run: ruff check src/ + - run: ruff format src/ - uses: stefanzweifel/git-auto-commit-action@v4 with: commit_message: 'style fixes by ruff' From 80bcc6891d259424d63224060056b06ceb483f39 Mon Sep 17 00:00:00 2001 From: Sanchit Vijay Date: Tue, 19 Mar 2024 20:45:49 -0400 Subject: [PATCH 24/53] Update ruff_commit.yml --- .github/workflows/ruff_commit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ruff_commit.yml b/.github/workflows/ruff_commit.yml index 2ffff92..3a5e8cc 100644 --- a/.github/workflows/ruff_commit.yml +++ b/.github/workflows/ruff_commit.yml @@ -3,7 +3,7 @@ on: push jobs: lint: - runs-on: ubuntu_latest + runs-on: self-hosted steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 From d749618f171572d90ad0c73d3397306288e2aac0 Mon Sep 17 00:00:00 2001 From: Sanchit Vijay Date: Tue, 19 Mar 2024 20:48:39 -0400 Subject: [PATCH 25/53] Update ruff_commit.yml --- .github/workflows/ruff_commit.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ruff_commit.yml b/.github/workflows/ruff_commit.yml index 3a5e8cc..2294c6d 100644 --- a/.github/workflows/ruff_commit.yml +++ b/.github/workflows/ruff_commit.yml @@ -8,7 +8,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install ruff - - run: ruff check src/ + # - run: ruff check src/ - run: ruff format src/ - uses: stefanzweifel/git-auto-commit-action@v4 with: From b378f56cd23fe065a535f51ef7bf99c20620343d Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Wed, 20 Mar 2024 00:50:42 +0000 Subject: [PATCH 26/53] style fixes by ruff --- src/grag/components/chroma_client.py | 47 +++++--- src/grag/components/embedding.py | 16 ++- src/grag/components/llm.py | 104 +++++++++-------- src/grag/components/multivec_retriever.py | 31 +++-- src/grag/components/parse_pdf.py | 109 +++++++++--------- src/grag/components/prompt.py | 61 +++++----- src/grag/components/text_splitter.py | 12 +- src/grag/components/utils.py | 28 ++--- src/grag/prompts/__init__.py | 7 +- src/grag/rag/basic_rag.py | 96 ++++++++------- src/tests/components/embedding_test.py | 34 ++++-- src/tests/components/llm_test.py | 28 +++-- .../components/multivec_retriever_test.py | 20 ++-- src/tests/components/parse_pdf_test.py | 22 ++-- src/tests/components/prompt_test.py | 19 ++- src/tests/rag/basic_rag_test.py | 8 +- 16 files changed, 354 insertions(+), 288 deletions(-) diff --git a/src/grag/components/chroma_client.py b/src/grag/components/chroma_client.py index 72b0db7..1d816bd 100644 --- a/src/grag/components/chroma_client.py +++ b/src/grag/components/chroma_client.py @@ -10,7 +10,7 @@ from grag.components.embedding import Embedding from grag.components.utils import get_config -chroma_conf = get_config()['chroma'] +chroma_conf = get_config()["chroma"] class ChromaClient: @@ -37,12 +37,14 @@ class ChromaClient: LangChain wrapper for Chroma collection """ - def __init__(self, - host=chroma_conf['host'], - port=chroma_conf['port'], - collection_name=chroma_conf['collection_name'], - embedding_type=chroma_conf['embedding_type'], - embedding_model=chroma_conf['embedding_model']): + def __init__( + self, + host=chroma_conf["host"], + port=chroma_conf["port"], + collection_name=chroma_conf["collection_name"], + embedding_type=chroma_conf["embedding_type"], + embedding_model=chroma_conf["embedding_model"], + ): """Args: host: IP Address of hosted Chroma Vectorstore, defaults to argument from config file port: port address of hosted Chroma Vectorstore, defaults to argument from config file @@ -56,14 +58,19 @@ def __init__(self, self.embedding_type: str = embedding_type self.embedding_model: str = embedding_model - self.embedding_function = Embedding(embedding_model=self.embedding_model, - embedding_type=self.embedding_type).embedding_function + self.embedding_function = Embedding( + embedding_model=self.embedding_model, embedding_type=self.embedding_type + ).embedding_function self.chroma_client = chromadb.HttpClient(host=self.host, port=self.port) - self.collection = self.chroma_client.get_or_create_collection(name=self.collection_name) - self.langchain_chroma = Chroma(client=self.chroma_client, - collection_name=self.collection_name, - embedding_function=self.embedding_function, ) + self.collection = self.chroma_client.get_or_create_collection( + name=self.collection_name + ) + self.langchain_chroma = Chroma( + client=self.chroma_client, + collection_name=self.collection_name, + embedding_function=self.embedding_function, + ) self.allowed_metadata_types = (str, int, float, bool) def test_connection(self, verbose=True): @@ -78,9 +85,9 @@ def test_connection(self, verbose=True): response = self.chroma_client.heartbeat() if verbose: if response: - print(f'Connection to {self.host}/{self.port} is alive..') + print(f"Connection to {self.host}/{self.port} is alive..") else: - print(f'Connection to {self.host}/{self.port} is not alive !!') + print(f"Connection to {self.host}/{self.port} is not alive !!") return response async def aadd_docs(self, docs: List[Document], verbose=True): @@ -100,7 +107,11 @@ async def aadd_docs(self, docs: List[Document], verbose=True): # else: # await asyncio.gather(*tasks) if verbose: - for doc in atqdm(docs, desc=f'Adding documents to {self.collection_name}', total=len(docs)): + for doc in atqdm( + docs, + desc=f"Adding documents to {self.collection_name}", + total=len(docs), + ): await self.langchain_chroma.aadd_documents([doc]) else: for doc in docs: @@ -117,7 +128,9 @@ def add_docs(self, docs: List[Document], verbose=True): None """ docs = self._filter_metadata(docs) - for doc in (tqdm(docs, desc=f'Adding to {self.collection_name}:') if verbose else docs): + for doc in ( + tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs + ): _id = self.langchain_chroma.add_documents([doc]) def _filter_metadata(self, docs: List[Document]): diff --git a/src/grag/components/embedding.py b/src/grag/components/embedding.py index ed483c7..7a9d249 100644 --- a/src/grag/components/embedding.py +++ b/src/grag/components/embedding.py @@ -20,11 +20,15 @@ def __init__(self, embedding_type: str, embedding_model: str): self.embedding_type = embedding_type self.embedding_model = embedding_model match self.embedding_type: - case 'sentence-transformers': - self.embedding_function = SentenceTransformerEmbeddings(model_name=self.embedding_model) - case 'instructor-embedding': - self.embedding_instruction = 'Represent the document for retrival' - self.embedding_function = HuggingFaceInstructEmbeddings(model_name=self.embedding_model) + case "sentence-transformers": + self.embedding_function = SentenceTransformerEmbeddings( + model_name=self.embedding_model + ) + case "instructor-embedding": + self.embedding_instruction = "Represent the document for retrival" + self.embedding_function = HuggingFaceInstructEmbeddings( + model_name=self.embedding_model + ) self.embedding_function.embed_instruction = self.embedding_instruction case _: - raise Exception('embedding_type is invalid') + raise Exception("embedding_type is invalid") diff --git a/src/grag/components/llm.py b/src/grag/components/llm.py index 5192881..20db968 100644 --- a/src/grag/components/llm.py +++ b/src/grag/components/llm.py @@ -16,7 +16,7 @@ from .utils import get_config -llm_conf = get_config()['llm'] +llm_conf = get_config()["llm"] print("CUDA: ", torch.cuda.is_available()) @@ -35,20 +35,21 @@ class LLM: n_gpu_layers (int): Number of GPU layers for CPP. """ - def __init__(self, - model_name=llm_conf["model_name"], - device_map=llm_conf["device_map"], - task=llm_conf["task"], - max_new_tokens=llm_conf["max_new_tokens"], - temperature=llm_conf["temperature"], - n_batch=llm_conf["n_batch_gpu_cpp"], - n_ctx=llm_conf["n_ctx_cpp"], - n_gpu_layers=llm_conf["n_gpu_layers_cpp"], - std_out=llm_conf["std_out"], - base_dir=llm_conf["base_dir"], - quantization=llm_conf["quantization"], - pipeline=llm_conf["pipeline"], - ): + def __init__( + self, + model_name=llm_conf["model_name"], + device_map=llm_conf["device_map"], + task=llm_conf["task"], + max_new_tokens=llm_conf["max_new_tokens"], + temperature=llm_conf["temperature"], + n_batch=llm_conf["n_batch_gpu_cpp"], + n_ctx=llm_conf["n_ctx_cpp"], + n_gpu_layers=llm_conf["n_gpu_layers_cpp"], + std_out=llm_conf["std_out"], + base_dir=llm_conf["base_dir"], + quantization=llm_conf["quantization"], + pipeline=llm_conf["pipeline"], + ): self.base_dir = Path(base_dir) self._model_name = model_name self.quantization = quantization @@ -74,7 +75,8 @@ def model_name(self): def model_path(self): """Sets the model name.""" return str( - self.base_dir / self.model_name / f'ggml-model-{self.quantization}.gguf') + self.base_dir / self.model_name / f"ggml-model-{self.quantization}.gguf" + ) @model_name.setter def model_name(self, value): @@ -92,21 +94,24 @@ def hf_pipeline(self, is_local=False): else: hf_model = self.model_name match self.quantization: - case 'Q8': + case "Q8": quantization_config = BitsAndBytesConfig(load_in_8bit=True) - case 'Q4': + case "Q4": quantization_config = BitsAndBytesConfig(load_in_4bit=True) case _: raise ValueError( - f'{self.quantization} is not a valid quantization. Non-local hf_pipeline takes only Q4 and Q8.') + f"{self.quantization} is not a valid quantization. Non-local hf_pipeline takes only Q4 and Q8." + ) try: # Try to load the model without passing the token tokenizer = AutoTokenizer.from_pretrained(hf_model) - model = AutoModelForCausalLM.from_pretrained(hf_model, - quantization_config=quantization_config, - device_map=self.device_map, - torch_dtype=torch.float16, ) + model = AutoModelForCausalLM.from_pretrained( + hf_model, + quantization_config=quantization_config, + device_map=self.device_map, + torch_dtype=torch.float16, + ) except OSError: # LocalTokenNotFoundError: # If loading fails due to an auth token error, then load the token and retry load_dotenv() @@ -114,24 +119,29 @@ def hf_pipeline(self, is_local=False): if not auth_token: raise ValueError("Authentication token not provided.") tokenizer = AutoTokenizer.from_pretrained(hf_model, token=True) - model = AutoModelForCausalLM.from_pretrained(hf_model, - quantization_config=quantization_config, - device_map=self.device_map, - torch_dtype=torch.float16, - token=True) - - pipe = pipeline(self.task, - model=model, - tokenizer=tokenizer, - torch_dtype=torch.bfloat16, - device_map=self.device_map, - max_new_tokens=self.max_new_tokens, - do_sample=True, - top_k=10, - num_return_sequences=1, - eos_token_id=tokenizer.eos_token_id - ) - llm = HuggingFacePipeline(pipeline=pipe, model_kwargs={'temperature': self.temperature}) + model = AutoModelForCausalLM.from_pretrained( + hf_model, + quantization_config=quantization_config, + device_map=self.device_map, + torch_dtype=torch.float16, + token=True, + ) + + pipe = pipeline( + self.task, + model=model, + tokenizer=tokenizer, + torch_dtype=torch.bfloat16, + device_map=self.device_map, + max_new_tokens=self.max_new_tokens, + do_sample=True, + top_k=10, + num_return_sequences=1, + eos_token_id=tokenizer.eos_token_id, + ) + llm = HuggingFacePipeline( + pipeline=pipe, model_kwargs={"temperature": self.temperature} + ) return llm def llama_cpp(self): @@ -149,11 +159,9 @@ def llama_cpp(self): ) return llm - def load_model(self, - model_name=None, - pipeline=None, - quantization=None, - is_local=None): + def load_model( + self, model_name=None, pipeline=None, quantization=None, is_local=None + ): """Loads the model based on the specified pipeline and model name. Args: @@ -172,7 +180,7 @@ def load_model(self, is_local = False match self.pipeline: - case 'llama_cpp': + case "llama_cpp": return self.llama_cpp() - case 'hf': + case "hf": return self.hf_pipeline(is_local=is_local) diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index a839917..9946a3a 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -10,7 +10,7 @@ from grag.components.text_splitter import TextSplitter from grag.components.utils import get_config -multivec_retriever_conf = get_config()['multivec_retriever'] +multivec_retriever_conf = get_config()["multivec_retriever"] class Retriever: @@ -30,11 +30,13 @@ class Retriever: """ - def __init__(self, - store_path: str = multivec_retriever_conf['store_path'], - id_key: str = multivec_retriever_conf['id_key'], - namespace: str = multivec_retriever_conf['namespace'], - top_k=1): + def __init__( + self, + store_path: str = multivec_retriever_conf["store_path"], + id_key: str = multivec_retriever_conf["id_key"], + namespace: str = multivec_retriever_conf["namespace"], + top_k=1, + ): """Args: store_path: Path to the local file store, defaults to argument from config file id_key: A key prefix for identifying documents, defaults to argument from config file @@ -53,7 +55,7 @@ def __init__(self, ) self.splitter = TextSplitter() self.top_k: int = top_k - self.retriever.search_kwargs = {'k': self.top_k} + self.retriever.search_kwargs = {"k": self.top_k} def id_gen(self, doc: Document) -> str: """Takes a document and returns a unique id (uuid5) using the namespace and document source. @@ -65,7 +67,7 @@ def id_gen(self, doc: Document) -> str: Returns: string of hexadecimal uuid """ - return uuid.uuid5(self.namespace, doc.metadata['source']).hex + return uuid.uuid5(self.namespace, doc.metadata["source"]).hex def gen_doc_ids(self, docs: List[Document]) -> List[str]: """Takes a list of documents and produces a list of unique id, refer id_gen method for more details. @@ -144,15 +146,12 @@ def get_chunk(self, query: str, with_score=False, top_k=None): """ if with_score: - return self.client.langchain_chroma.similarity_search_with_relevance_scores( - query=query, - **{'k': top_k} if top_k else self.retriever.search_kwargs + query=query, **{"k": top_k} if top_k else self.retriever.search_kwargs ) else: return self.client.langchain_chroma.similarity_search( - query=query, - **{'k': top_k} if top_k else self.retriever.search_kwargs + query=query, **{"k": top_k} if top_k else self.retriever.search_kwargs ) async def aget_chunk(self, query: str, with_score=False, top_k=None): @@ -169,13 +168,11 @@ async def aget_chunk(self, query: str, with_score=False, top_k=None): """ if with_score: return await self.client.langchain_chroma.asimilarity_search_with_relevance_scores( - query=query, - **{'k': top_k} if top_k else self.retriever.search_kwargs + query=query, **{"k": top_k} if top_k else self.retriever.search_kwargs ) else: return await self.client.langchain_chroma.asimilarity_search( - query=query, - **{'k': top_k} if top_k else self.retriever.search_kwargs + query=query, **{"k": top_k} if top_k else self.retriever.search_kwargs ) def get_doc(self, query: str): diff --git a/src/grag/components/parse_pdf.py b/src/grag/components/parse_pdf.py index 00d0fa0..d918c93 100644 --- a/src/grag/components/parse_pdf.py +++ b/src/grag/components/parse_pdf.py @@ -3,39 +3,42 @@ from .utils import get_config -parser_conf = get_config()['parser'] +parser_conf = get_config()["parser"] class ParsePDF: """Parsing and partitioning PDF documents into Text, Table or Image elements. - + Attributes: single_text_out (bool): Whether to combine all text elements into a single output document. strategy (str): The strategy for PDF partitioning; default is "hi_res" for better accuracy. extract_image_block_types (list): Elements to be extracted as image blocks. infer_table_structure (bool): Whether to extract tables during partitioning. - extract_images (bool): Whether to extract images. + extract_images (bool): Whether to extract images. image_output_dir (str): Directory to save extracted images, if any. add_captions_to_text (bool): Whether to include figure captions in text output. Default is True. add_captions_to_blocks (bool): Whether to add captions to table and image blocks. Default is True. add_caption_first (bool): Whether to place captions before their corresponding image or table in the output. Default is True. """ - def __init__(self, - single_text_out=parser_conf['single_text_out'], - strategy=parser_conf['strategy'], - infer_table_structure=parser_conf['infer_table_structure'], - extract_images=parser_conf['extract_images'], - image_output_dir=parser_conf['image_output_dir'], - add_captions_to_text=parser_conf['add_captions_to_text'], - add_captions_to_blocks=parser_conf['add_captions_to_blocks'], - table_as_html=parser_conf['table_as_html'] - - ): + def __init__( + self, + single_text_out=parser_conf["single_text_out"], + strategy=parser_conf["strategy"], + infer_table_structure=parser_conf["infer_table_structure"], + extract_images=parser_conf["extract_images"], + image_output_dir=parser_conf["image_output_dir"], + add_captions_to_text=parser_conf["add_captions_to_text"], + add_captions_to_blocks=parser_conf["add_captions_to_blocks"], + table_as_html=parser_conf["table_as_html"], + ): # Instantialize instance variables with parameters self.strategy = strategy if extract_images: # by default always extract Table - self.extract_image_block_types = ["Image", "Table"] # extracting Image and Table as image blocks + self.extract_image_block_types = [ + "Image", + "Table", + ] # extracting Image and Table as image blocks else: self.extract_image_block_types = ["Table"] self.infer_table_structure = infer_table_structure @@ -63,7 +66,7 @@ def partition(self, path: str): extract_image_block_types=self.extract_image_block_types, infer_table_structure=self.infer_table_structure, extract_image_block_to_payload=False, - extract_image_block_output_dir=self.image_output_dir + extract_image_block_output_dir=self.image_output_dir, ) return partitions @@ -78,43 +81,42 @@ def classify(self, partitions): dict: A dictionary with keys 'Text', 'Tables', and 'Images', each containing a list of corresponding elements. """ # Initialize lists for each type of element - classified_elements = { - 'Text': [], - 'Tables': [], - 'Images': [] - } + classified_elements = {"Text": [], "Tables": [], "Images": []} for i, element in enumerate(partitions): # enumerate, classify and add element + caption (when available) to respective list if element.category == "Table": if self.add_captions_to_blocks and i + 1 < len(partitions): - if partitions[i + 1].category == "FigureCaption": # check for caption + if ( + partitions[i + 1].category == "FigureCaption" + ): # check for caption caption_element = partitions[i + 1] else: caption_element = None - classified_elements['Tables'].append((element, caption_element)) + classified_elements["Tables"].append((element, caption_element)) else: - classified_elements['Tables'].append((element, None)) + classified_elements["Tables"].append((element, None)) elif element.category == "Image": if self.add_captions_to_blocks and i + 1 < len(partitions): - if partitions[i + 1].category == "FigureCaption": # check for caption + if ( + partitions[i + 1].category == "FigureCaption" + ): # check for caption caption_element = partitions[i + 1] else: caption_element = None - classified_elements['Images'].append((element, caption_element)) + classified_elements["Images"].append((element, caption_element)) else: - classified_elements['Images'].append((element, None)) + classified_elements["Images"].append((element, None)) else: if not self.add_captions_to_text: - if element.category != 'FigureCaption': - classified_elements['Text'].append(element) + if element.category != "FigureCaption": + classified_elements["Text"].append(element) else: - classified_elements['Text'].append(element) + classified_elements["Text"].append(element) return classified_elements def text_concat(self, elements) -> str: - for current_element, next_element in zip(elements, elements[1:]): curr_type = current_element.category next_type = next_element.category @@ -122,22 +124,22 @@ def text_concat(self, elements) -> str: # if curr_type in ["FigureCaption", "NarrativeText", "Title", "Address", 'Table', "UncategorizedText", "Formula"]: # full_text += str(current_element) + "\n\n" - if curr_type == "Title" and next_type == 'NarrativeText': - full_text += str(current_element) + '\n' - elif curr_type == 'NarrativeText' and next_type == 'NarrativeText': - full_text += str(current_element) + '\n' + if curr_type == "Title" and next_type == "NarrativeText": + full_text += str(current_element) + "\n" + elif curr_type == "NarrativeText" and next_type == "NarrativeText": + full_text += str(current_element) + "\n" elif curr_type == "ListItem": full_text += "- " + str(current_element) + "\n" - if next_element == 'Title': - full_text += '\n' - elif next_element == 'Title': - full_text = str(current_element) + '\n\n' + if next_element == "Title": + full_text += "\n" + elif next_element == "Title": + full_text = str(current_element) + "\n\n" elif curr_type in ["Header", "Footer", "PageBreak"]: full_text += str(current_element) + "\n\n\n" else: - full_text += '\n' + full_text += "\n" return full_text @@ -151,14 +153,13 @@ def process_text(self, elements): docs (list): A list of Document instances containing the extracted Text content and their metadata. """ if self.single_text_out: - metadata = {'source': self.file_path} # Check for more metadata + metadata = {"source": self.file_path} # Check for more metadata text = "\n\n".join([str(el) for el in elements]) docs = [Document(page_content=text, metadata=metadata)] else: docs = [] for element in elements: - metadata = {'source': self.file_path, - 'category': element.category} + metadata = {"source": self.file_path, "category": element.category} metadata.update(element.metadata.to_dict()) docs.append(Document(page_content=str(element), metadata=metadata)) return docs @@ -170,13 +171,12 @@ def process_tables(self, elements): elements (list): The list of table elements (and optional captions) to be processed. Returns: - docs (list): A list of Document instances containing Tables, their captions and metadata. + docs (list): A list of Document instances containing Tables, their captions and metadata. """ docs = [] for block_element, caption_element in elements: - metadata = {'source': self.file_path, - 'category': block_element.category} + metadata = {"source": self.file_path, "category": block_element.category} metadata.update(block_element.metadata.to_dict()) if self.table_as_html: table_data = block_element.metadata.text_as_html @@ -184,7 +184,9 @@ def process_tables(self, elements): table_data = str(block_element) if caption_element: - if self.add_caption_first: # if there is a caption, add that before the element + if ( + self.add_caption_first + ): # if there is a caption, add that before the element content = "\n\n".join([str(caption_element), table_data]) else: content = "\n\n".join([table_data, str(caption_element)]) @@ -204,8 +206,7 @@ def process_images(self, elements): """ docs = [] for block_element, caption_element in elements: - metadata = {'source': self.file_path, - 'category': block_element.category} + metadata = {"source": self.file_path, "category": block_element.category} metadata.update(block_element.metadata.to_dict()) if caption_element: # if there is a caption, add that before the element if self.add_caption_first: @@ -228,9 +229,7 @@ def load_file(self, path): """ partitions = self.partition(str(path)) classified_elements = self.classify(partitions) - text_docs = self.process_text(classified_elements['Text']) - table_docs = self.process_tables(classified_elements['Tables']) - image_docs = self.process_images(classified_elements['Images']) - return {'Text': text_docs, - 'Tables': table_docs, - 'Images': image_docs} + text_docs = self.process_text(classified_elements["Text"]) + table_docs = self.process_tables(classified_elements["Tables"]) + image_docs = self.process_images(classified_elements["Images"]) + return {"Text": text_docs, "Tables": table_docs, "Images": image_docs} diff --git a/src/grag/components/prompt.py b/src/grag/components/prompt.py index 3c20be9..ecefa71 100644 --- a/src/grag/components/prompt.py +++ b/src/grag/components/prompt.py @@ -9,16 +9,16 @@ Example = Dict[str, Any] SUPPORTED_TASKS = ["QA"] -SUPPORTED_DOC_CHAINS = ["stuff", 'refine'] +SUPPORTED_DOC_CHAINS = ["stuff", "refine"] class Prompt(BaseModel): - name: str = Field(default='custom_prompt') - llm_type: str = Field(default='None') - task: str = Field(default='QA') - source: str = Field(default='NoSource') - doc_chain: str = Field(default='stuff') - language: str = 'en' + name: str = Field(default="custom_prompt") + llm_type: str = Field(default="None") + task: str = Field(default="QA") + source: str = Field(default="NoSource") + doc_chain: str = Field(default="stuff") + language: str = "en" filepath: Optional[str] = Field(default=None, exclude=True) input_keys: List[str] template: str @@ -28,7 +28,7 @@ class Prompt(BaseModel): @classmethod def validate_input_keys(cls, v) -> List[str]: if v is None or v == []: - raise ValueError('input_keys cannot be empty') + raise ValueError("input_keys cannot be empty") return v @field_validator("doc_chain") @@ -36,14 +36,17 @@ def validate_input_keys(cls, v) -> List[str]: def validate_doc_chain(cls, v: str) -> str: if v not in SUPPORTED_DOC_CHAINS: raise ValueError( - f'The provided doc_chain, {v} is not supported, supported doc_chains are {SUPPORTED_DOC_CHAINS}') + f"The provided doc_chain, {v} is not supported, supported doc_chains are {SUPPORTED_DOC_CHAINS}" + ) return v @field_validator("task") @classmethod def validate_task(cls, v: str) -> str: if v not in SUPPORTED_TASKS: - raise ValueError(f'The provided task, {v} is not supported, supported tasks are {SUPPORTED_TASKS}') + raise ValueError( + f"The provided task, {v} is not supported, supported tasks are {SUPPORTED_TASKS}" + ) return v # @model_validator(mode='after') @@ -51,21 +54,21 @@ def validate_task(cls, v: str) -> str: # self.prompt = ChatPromptTemplate.from_template(self.template) def __init__(self, **kwargs): super().__init__(**kwargs) - self.prompt = PromptTemplate(input_variables=self.input_keys, template=self.template) - - def save(self, filepath: Union[Path, str, None], overwrite=False) -> Union[None, ValueError]: - dump = self.model_dump_json( - indent=2, - exclude_defaults=True, - exclude_none=True + self.prompt = PromptTemplate( + input_variables=self.input_keys, template=self.template ) + + def save( + self, filepath: Union[Path, str, None], overwrite=False + ) -> Union[None, ValueError]: + dump = self.model_dump_json(indent=2, exclude_defaults=True, exclude_none=True) if filepath is None: - filepath = f'{self.name}.json' + filepath = f"{self.name}.json" if overwrite: if self.filepath is None: - return ValueError('filepath does not exist in instance') + return ValueError("filepath does not exist in instance") filepath = self.filepath - with open(filepath, 'w') as f: + with open(filepath, "w") as f: f.write(dump) return None @@ -87,12 +90,16 @@ class FewShotPrompt(Prompt): prefix: str suffix: str example_template: str - prompt: Optional[FewShotPromptTemplate] = Field(exclude=True, repr=False, default=None) + prompt: Optional[FewShotPromptTemplate] = Field( + exclude=True, repr=False, default=None + ) def __init__(self, **kwargs): super().__init__(**kwargs) - eg_formatter = PromptTemplate(input_vars=self.input_keys + self.output_keys, - template=self.example_template) + eg_formatter = PromptTemplate( + input_vars=self.input_keys + self.output_keys, + template=self.example_template, + ) self.prompt = FewShotPromptTemplate( examples=self.examples, example_prompt=eg_formatter, @@ -105,14 +112,14 @@ def __init__(self, **kwargs): @classmethod def validate_output_keys(cls, v) -> List[str]: if v is None or v == []: - raise ValueError('output_keys cannot be empty') + raise ValueError("output_keys cannot be empty") return v - @field_validator('examples') + @field_validator("examples") @classmethod def validate_examples(cls, v) -> List[Dict[str, Any]]: if v is None or v == []: - raise ValueError('examples cannot be empty') + raise ValueError("examples cannot be empty") for eg in v: if not all(key in eg for key in cls.input_keys): raise ValueError(f"input key(s) not in example {eg}") @@ -121,5 +128,5 @@ def validate_examples(cls, v) -> List[Dict[str, Any]]: return v -if __name__ == '__main__': +if __name__ == "__main__": p = Prompt.load("../prompts/Llama-2_QA_1.json") diff --git a/src/grag/components/text_splitter.py b/src/grag/components/text_splitter.py index 4b5b334..cff3c7c 100644 --- a/src/grag/components/text_splitter.py +++ b/src/grag/components/text_splitter.py @@ -2,13 +2,15 @@ from .utils import get_config -text_splitter_conf = get_config()['text_splitter'] +text_splitter_conf = get_config()["text_splitter"] # %% class TextSplitter: def __init__(self): - self.text_splitter = RecursiveCharacterTextSplitter(chunk_size=int(text_splitter_conf['chunk_size']), - chunk_overlap=int(text_splitter_conf['chunk_overlap']), - length_function=len, - is_separator_regex=False, ) + self.text_splitter = RecursiveCharacterTextSplitter( + chunk_size=int(text_splitter_conf["chunk_size"]), + chunk_overlap=int(text_splitter_conf["chunk_overlap"]), + length_function=len, + is_separator_regex=False, + ) diff --git a/src/grag/components/utils.py b/src/grag/components/utils.py index ea3c041..cb64258 100644 --- a/src/grag/components/utils.py +++ b/src/grag/components/utils.py @@ -16,7 +16,7 @@ def stuff_docs(docs: List[Document]) -> str: Returns: string of document page content joined by '\n\n' """ - return '\n\n'.join([doc.page_content for doc in docs]) + return "\n\n".join([doc.page_content for doc in docs]) def reformat_text_with_line_breaks(input_text, max_width=110): @@ -31,13 +31,15 @@ def reformat_text_with_line_breaks(input_text, max_width=110): str: The reformatted text with preserved line breaks and adjusted line width. """ # Divide the text into separate lines - original_lines = input_text.split('\n') + original_lines = input_text.split("\n") # Apply wrapping to each individual line - reformatted_lines = [textwrap.fill(line, width=max_width) for line in original_lines] + reformatted_lines = [ + textwrap.fill(line, width=max_width) for line in original_lines + ] # Combine the lines back into a single text block - reformatted_text = '\n'.join(reformatted_lines) + reformatted_text = "\n".join(reformatted_lines) return reformatted_text @@ -49,14 +51,14 @@ def display_llm_output_and_sources(response_from_llm): response_from_llm (dict): The response object from an LLM which includes the result and source documents. """ # Display the main result from the LLM response - print(response_from_llm['result']) + print(response_from_llm["result"]) # Separator for clarity - print('\nSources:') + print("\nSources:") # Loop through each source document and print its source for source in response_from_llm["source_documents"]: - print(source.metadata['source']) + print(source.metadata["source"]) def load_prompt(json_file: str | os.PathLike, return_input_vars=False): @@ -72,9 +74,9 @@ def load_prompt(json_file: str | os.PathLike, return_input_vars=False): """ with open(f"{json_file}", "r") as f: prompt_json = json.load(f) - prompt_template = ChatPromptTemplate.from_template(prompt_json['template']) + prompt_template = ChatPromptTemplate.from_template(prompt_json["template"]) - input_vars = prompt_json['input_variables'] + input_vars = prompt_json["input_variables"] return (prompt_template, input_vars) if return_input_vars else prompt_template @@ -94,7 +96,7 @@ def find_config_path(current_path: Path) -> Path: Raises: FileNotFoundError: If 'config.ini' cannot be found in any of the parent directories. """ - config_path = Path('src/config.ini') + config_path = Path("src/config.ini") while not (current_path / config_path).exists(): current_path = current_path.parent if current_path == current_path.parent: @@ -113,11 +115,11 @@ def get_config() -> ConfigParser: """ # Assuming this script is somewhere inside your project directory script_location = Path(__file__).resolve() - if os.environ.get('CONFIG_PATH'): - config_path = os.environ.get('CONFIG_PATH') + if os.environ.get("CONFIG_PATH"): + config_path = os.environ.get("CONFIG_PATH") else: config_path = find_config_path(script_location) - os.environ['CONFIG_PATH'] = str(config_path) + os.environ["CONFIG_PATH"] = str(config_path) print(f"Loaded config from {config_path}.") # Initialize parser and read config config = ConfigParser(interpolation=ExtendedInterpolation()) diff --git a/src/grag/prompts/__init__.py b/src/grag/prompts/__init__.py index 4c869db..cf6b3bc 100644 --- a/src/grag/prompts/__init__.py +++ b/src/grag/prompts/__init__.py @@ -1,10 +1,7 @@ { - "input_keys": [ - "context", - "question" - ], + "input_keys": ["context", "question"], "template": "[INST] <>\nYou are a helpful, respectful and honest assistant.\n\nAlways answer based only on the provided context. If the question can not be answered from the provided context, just say that you don't know, don't try to make up an answer.\n<>\n\nUse the following pieces of context to answer the question at the end:\n\n\n{context}\n\n\nQuestion: {question}\n\nHelpful Answer: [/INST]", "llm_type": "Llama-2", "source": "https://github.com/hwchase17/langchain-hub/blob/master/prompts/vector_db_qa/prompt.json", - "task": "QA" + "task": "QA", } diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index 1e33ff6..9589920 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -13,15 +13,15 @@ class BasicRAG: - def __init__(self, - model_name=None, - doc_chain='stuff', - task='QA', - llm_kwargs=None, - retriever_kwargs=None, - custom_prompt: Union[Prompt, FewShotPrompt, None] = None - ): - + def __init__( + self, + model_name=None, + doc_chain="stuff", + task="QA", + llm_kwargs=None, + retriever_kwargs=None, + custom_prompt: Union[Prompt, FewShotPrompt, None] = None, + ): if retriever_kwargs is None: self.retriever = Retriever() else: @@ -35,16 +35,20 @@ def __init__(self, self.prompt_path = files(prompts) self.custom_prompt = custom_prompt - self._task = 'QA' + self._task = "QA" self.model_name = model_name self.doc_chain = doc_chain self.task = task if self.custom_prompt is None: - self.main_prompt = Prompt.load(self.prompt_path.joinpath(self.main_prompt_name)) - - if self.doc_chain == 'refine': - self.refine_prompt = Prompt.load(self.prompt_path.joinpath(self.refine_prompt_name)) + self.main_prompt = Prompt.load( + self.prompt_path.joinpath(self.main_prompt_name) + ) + + if self.doc_chain == "refine": + self.refine_prompt = Prompt.load( + self.prompt_path.joinpath(self.refine_prompt_name) + ) else: self.main_prompt = self.custom_prompt @@ -56,7 +60,7 @@ def model_name(self): def model_name(self, value): if value is None: self.llm = self.llm_.load_model() - self._model_name = conf['llm']['model_name'] + self._model_name = conf["llm"]["model_name"] else: self._model_name = value self.llm = self.llm_.load_model(model_name=self.model_name) @@ -67,14 +71,17 @@ def doc_chain(self): @doc_chain.setter def doc_chain(self, value): - _allowed_doc_chains = ['refine', 'stuff'] + _allowed_doc_chains = ["refine", "stuff"] if value not in _allowed_doc_chains: - raise ValueError(f'Doc chain {value} is not allowed. Available choices: {_allowed_doc_chains}') + raise ValueError( + f"Doc chain {value} is not allowed. Available choices: {_allowed_doc_chains}" + ) self._doc_chain = value - if value == 'refine': + if value == "refine": if self.custom_prompt is not None: assert len(self.custom_prompt) == 2, ValueError( - f"Refine chain needs 2 custom prompts. {len(self.custom_prompt)} custom prompts were given.") + f"Refine chain needs 2 custom prompts. {len(self.custom_prompt)} custom prompts were given." + ) self.prompt_matcher() @property @@ -83,27 +90,35 @@ def task(self): @task.setter def task(self, value): - _allowed_tasks = ['QA'] + _allowed_tasks = ["QA"] if value not in _allowed_tasks: - raise ValueError(f'Task {value} is not allowed. Available tasks: {_allowed_tasks}') + raise ValueError( + f"Task {value} is not allowed. Available tasks: {_allowed_tasks}" + ) self._task = value self.prompt_matcher() def prompt_matcher(self): - matcher_path = self.prompt_path.joinpath('matcher.json') + matcher_path = self.prompt_path.joinpath("matcher.json") with open(f"{matcher_path}", "r") as f: matcher_dict = json.load(f) try: self.model_type = matcher_dict[self.model_name] except KeyError: - raise ValueError(f'Prompt for {self.model_name} not found in {matcher_path}') + raise ValueError( + f"Prompt for {self.model_name} not found in {matcher_path}" + ) - self.main_prompt_name = f'{self.model_type}_{self.task}_1.json' - self.refine_prompt_name = f'{self.model_type}_{self.task}-refine_1.json' + self.main_prompt_name = f"{self.model_type}_{self.task}_1.json" + self.refine_prompt_name = f"{self.model_type}_{self.task}-refine_1.json" if self.custom_prompt is None: - self.main_prompt = Prompt.load(self.prompt_path.joinpath(self.main_prompt_name)) - if self.doc_chain == 'refine': - self.refine_prompt = Prompt.load(self.prompt_path.joinpath(self.refine_prompt_name)) + self.main_prompt = Prompt.load( + self.prompt_path.joinpath(self.main_prompt_name) + ) + if self.doc_chain == "refine": + self.refine_prompt = Prompt.load( + self.prompt_path.joinpath(self.refine_prompt_name) + ) @staticmethod def stuff_docs(docs: List[Document]) -> str: @@ -113,18 +128,18 @@ def stuff_docs(docs: List[Document]) -> str: Returns: string of document page content joined by '\n\n' """ - return '\n\n'.join([doc.page_content for doc in docs]) + return "\n\n".join([doc.page_content for doc in docs]) @staticmethod def output_parser(call_func): def output_parser_wrapper(*args, **kwargs): response, sources = call_func(*args, **kwargs) - if conf['llm']['std_out'] == 'False': + if conf["llm"]["std_out"] == "False": # if self.llm_.callback_manager is None: print(response) - print('Sources: ') + print("Sources: ") for index, source in enumerate(sources): - print(f'\t{index}: {source}') + print(f"\t{index}: {source}") return response, sources return output_parser_wrapper @@ -145,20 +160,23 @@ def refine_call(self, query: str): responses = [] for index, doc in enumerate(retrieved_docs): if index == 0: - prompt = self.main_prompt.format(context=doc.page_content, - question=query) + prompt = self.main_prompt.format( + context=doc.page_content, question=query + ) response = self.llm.invoke(prompt) responses.append(response) else: - prompt = self.refine_prompt.format(context=doc.page_content, - question=query, - existing_answer=responses[-1]) + prompt = self.refine_prompt.format( + context=doc.page_content, + question=query, + existing_answer=responses[-1], + ) response = self.llm.invoke(prompt) responses.append(response) return responses, sources def __call__(self, query: str): - if self.doc_chain == 'stuff': + if self.doc_chain == "stuff": return self.stuff_call(query) - elif self.doc_chain == 'refine': + elif self.doc_chain == "refine": return self.refine_call(query) diff --git a/src/tests/components/embedding_test.py b/src/tests/components/embedding_test.py index 6d3e45a..1eda90f 100644 --- a/src/tests/components/embedding_test.py +++ b/src/tests/components/embedding_test.py @@ -13,21 +13,37 @@ def cosine_similarity(a, b): # %% embedding_configs = [ - {'embedding_type': 'sentence-transformers', - 'embedding_model': "all-mpnet-base-v2", }, - {'embedding_type': 'instructor-embedding', - 'embedding_model': 'hkunlp/instructor-xl', } + { + "embedding_type": "sentence-transformers", + "embedding_model": "all-mpnet-base-v2", + }, + { + "embedding_type": "instructor-embedding", + "embedding_model": "hkunlp/instructor-xl", + }, ] -@pytest.mark.parametrize('embedding_config', embedding_configs) +@pytest.mark.parametrize("embedding_config", embedding_configs) def test_embeddings(embedding_config): # docs tuple format: (doc, similar to doc, asimilar to doc) - doc_sets = [('The new movie is awesome.', 'The new movie is so great.', 'The video is awful'), - ('The cat sits outside.', 'The dog plays in the garden.', 'The car is parked inside')] + doc_sets = [ + ( + "The new movie is awesome.", + "The new movie is so great.", + "The video is awful", + ), + ( + "The cat sits outside.", + "The dog plays in the garden.", + "The car is parked inside", + ), + ] embedding = Embedding(**embedding_config) for docs in doc_sets: doc_vecs = [embedding.embedding_function.embed_query(doc) for doc in docs] - similarity_scores = [cosine_similarity(doc_vecs[0], doc_vecs[1]), - cosine_similarity(doc_vecs[0], doc_vecs[2])] + similarity_scores = [ + cosine_similarity(doc_vecs[0], doc_vecs[1]), + cosine_similarity(doc_vecs[0], doc_vecs[2]), + ] assert similarity_scores[0] > similarity_scores[1] diff --git a/src/tests/components/llm_test.py b/src/tests/components/llm_test.py index 44de0dd..df0f4d9 100644 --- a/src/tests/components/llm_test.py +++ b/src/tests/components/llm_test.py @@ -3,22 +3,26 @@ import pytest from grag.components.llm import LLM -llama_models = ['Llama-2-7b-chat', - 'Llama-2-13b-chat', - 'Mixtral-8x7B-Instruct-v0.1', - 'gemma-7b-it'] -hf_models = ['meta-llama/Llama-2-7b-chat-hf', - 'meta-llama/Llama-2-13b-chat-hf', - # 'mistralai/Mixtral-8x7B-Instruct-v0.1', - 'google/gemma-7b-it'] -cpp_quantization = ['Q5_K_M', 'Q5_K_M', 'Q4_K_M', 'f16'] -hf_quantization = ['Q8', 'Q4', 'Q4'] # , 'Q4'] +llama_models = [ + "Llama-2-7b-chat", + "Llama-2-13b-chat", + "Mixtral-8x7B-Instruct-v0.1", + "gemma-7b-it", +] +hf_models = [ + "meta-llama/Llama-2-7b-chat-hf", + "meta-llama/Llama-2-13b-chat-hf", + # 'mistralai/Mixtral-8x7B-Instruct-v0.1', + "google/gemma-7b-it", +] +cpp_quantization = ["Q5_K_M", "Q5_K_M", "Q4_K_M", "f16"] +hf_quantization = ["Q8", "Q4", "Q4"] # , 'Q4'] params = [(model, quant) for model, quant in zip(hf_models, hf_quantization)] @pytest.mark.parametrize("hf_models, quantization", params) def test_hf_web_pipe(hf_models, quantization): - llm_ = LLM(quantization=quantization, model_name=hf_models, pipeline='hf') + llm_ = LLM(quantization=quantization, model_name=hf_models, pipeline="hf") model = llm_.load_model(is_local=False) response = model.invoke("Who are you?") assert isinstance(response, Text) @@ -30,7 +34,7 @@ def test_hf_web_pipe(hf_models, quantization): @pytest.mark.parametrize("model_name, quantization", params) def test_llamacpp_pipe(model_name, quantization): - llm_ = LLM(quantization=quantization, model_name=model_name, pipeline='llama_cpp') + llm_ = LLM(quantization=quantization, model_name=model_name, pipeline="llama_cpp") model = llm_.load_model() response = model.invoke("Who are you?") assert isinstance(response, Text) diff --git a/src/tests/components/multivec_retriever_test.py b/src/tests/components/multivec_retriever_test.py index 6c94882..3ccb3fb 100644 --- a/src/tests/components/multivec_retriever_test.py +++ b/src/tests/components/multivec_retriever_test.py @@ -1,18 +1,18 @@ # # add code folder to sys path # import os # from pathlib import Path -# +# # from grag.components.multivec_retriever import Retriever # from langchain_community.document_loaders import DirectoryLoader, TextLoader -# +# # # %%% # # data_path = "data/pdf/9809" # data_path = Path(os.getcwd()).parents[1] / 'data' / 'Gutenberg' / 'txt' # "data/Gutenberg/txt" # # %% # retriever = Retriever(top_k=3) -# +# # new_docs = True -# +# # if new_docs: # # loading text files from data_path # loader = DirectoryLoader(data_path, @@ -25,20 +25,20 @@ # # %% # # limit docs for testing # docs = docs[:100] -# +# # # %% # # adding chunks and parent doc # retriever.add_docs(docs) # # %% # # testing retrival # query = 'Thomas H. Huxley' -# +# # # Retrieving the 3 most relevant small chunk # chunk_result = retriever.get_chunk(query) -# +# # # Retrieving the most relevant document # doc_result = retriever.get_doc(query) -# +# # # Ensuring that the length of chunk is smaller than length of doc # chunk_len = [len(chunk.page_content) for chunk in chunk_result] # print(f'Length of chunks : {chunk_len}') @@ -46,13 +46,13 @@ # print(f'Length of doc : {doc_len}') # len_test = [c_len < d_len for c_len, d_len in zip(chunk_len, doc_len)] # print(f'Is len of chunk less than len of doc?: {len_test} ') -# +# # # Ensuring both the chunk and document match the source # chunk_sources = [chunk.metadata['source'] for chunk in chunk_result] # doc_sources = [doc.metadata['source'] for doc in doc_result] # source_test = [source[0] == source[1] for source in zip(chunk_sources, doc_sources)] # print(f'Does source of chunk and doc match? : {source_test}') -# +# # # # Ensuring both the chunk and document match the source # # source_test = chunk_result.metadata['source'] == doc_result.metadata['source'] # # print(f'Does source of chunk and doc match? : {source_test}') diff --git a/src/tests/components/parse_pdf_test.py b/src/tests/components/parse_pdf_test.py index 668f8f1..7110e21 100644 --- a/src/tests/components/parse_pdf_test.py +++ b/src/tests/components/parse_pdf_test.py @@ -1,39 +1,39 @@ # # add code folder to sys path # import time # from pathlib import Path -# +# # from grag.components.parse_pdf import ParsePDF # from grag.components.utils import get_config -# +# # data_path = Path(get_config()['data']['data_path']) # # %% # data_path = data_path / 'test' / 'pdf' # "data/test/pdf" -# -# +# +# # def main(filename): # file_path = data_path / filename # pdf_parser = ParsePDF() # start_time = time.time() # docs_dict = pdf_parser.load_file(file_path) # time_taken = time.time() - start_time -# +# # print(f'Parsed pdf in {time_taken:2f} secs') -# +# # print('******** TEXT ********') # for doc in docs_dict['Text']: # print(doc) -# +# # print('******** TABLES ********') # for text_doc in docs_dict['Tables']: # print(text_doc) -# +# # print('******** IMAGES ********') # for doc in docs_dict['Images']: # print(doc) -# +# # return docs_dict -# -# +# +# # if __name__ == "__main__": # filename = 'he_pdsw12.pdf' # print(f'Parsing: {filename}') diff --git a/src/tests/components/prompt_test.py b/src/tests/components/prompt_test.py index fee7edc..3414f59 100644 --- a/src/tests/components/prompt_test.py +++ b/src/tests/components/prompt_test.py @@ -2,16 +2,18 @@ from importlib_resources import files question = "What is the capital of France" -context = "Paris is the capital and most populous city of France. With an official estimated population of 2,102,650 \ +context = ( + "Paris is the capital and most populous city of France. With an official estimated population of 2,102,650 \ residents as of 1 January 2023 in an area of more than 105 km2 (41 sq mi), Paris is the fourth-most populated \ city in the European Union and the 30th most densely populated city in the world in 2022. Since the 17th century, \ Paris has been one of the world's major centres of finance, diplomacy, commerce, culture, fashion, and gastronomy. \ For its leading role in the arts and sciences, as well as its early and extensive system of street lighting, in the \ 19th century, it became known as the City of Light." +) def test_prompt_files(): - prompt_files = list(files('grag.prompts').glob('*.json')) + prompt_files = list(files("grag.prompts").glob("*.json")) for file in prompt_files: if file.name.startswith("matcher"): prompt_files.remove(file) @@ -21,18 +23,15 @@ def test_prompt_files(): def test_custom_prompt(): - template = '''Answer the following question based on the given context. + template = """Answer the following question based on the given context. question: {question} context: {context} answer: - ''' - correct_prompt = f'''Answer the following question based on the given context. + """ + correct_prompt = f"""Answer the following question based on the given context. question: {question} context: {context} answer: - ''' - custom_prompt = Prompt( - input_keys={"context", "question"}, - template=template - ) + """ + custom_prompt = Prompt(input_keys={"context", "question"}, template=template) assert custom_prompt.format(question=question, context=context) == correct_prompt diff --git a/src/tests/rag/basic_rag_test.py b/src/tests/rag/basic_rag_test.py index 72991d1..2249028 100644 --- a/src/tests/rag/basic_rag_test.py +++ b/src/tests/rag/basic_rag_test.py @@ -4,8 +4,8 @@ def test_rag_stuff(): - rag = BasicRAG(doc_chain='stuff') - response, sources = rag('What is simulated annealing?') + rag = BasicRAG(doc_chain="stuff") + response, sources = rag("What is simulated annealing?") assert isinstance(response, Text) assert isinstance(sources, List) assert all(isinstance(s, str) for s in sources) @@ -13,8 +13,8 @@ def test_rag_stuff(): def test_rag_refine(): - rag = BasicRAG(doc_chain='refine') - response, sources = rag('What is simulated annealing?') + rag = BasicRAG(doc_chain="refine") + response, sources = rag("What is simulated annealing?") # assert isinstance(response, Text) assert isinstance(response, List) assert all(isinstance(s, str) for s in response) From 8b6ab3fc12e329f948d5d51fa930bac8ae78cf7d Mon Sep 17 00:00:00 2001 From: Sanchit Vijay Date: Tue, 19 Mar 2024 20:54:03 -0400 Subject: [PATCH 27/53] Update ruff_linting.yml --- .github/workflows/ruff_linting.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ruff_linting.yml b/.github/workflows/ruff_linting.yml index 802ca63..ecd2e32 100644 --- a/.github/workflows/ruff_linting.yml +++ b/.github/workflows/ruff_linting.yml @@ -6,7 +6,7 @@ on: jobs: adopt-ruff: - runs-on: ubuntu-latest + runs-on: self-hosted steps: - name: Check out repository code uses: actions/checkout@v4 From f4719fae191c8bdcd093f1995f1d58934d40aafa Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Wed, 20 Mar 2024 19:03:39 -0400 Subject: [PATCH 28/53] ruff format --- src/grag/components/chroma_client.py | 5 ++--- src/grag/components/multivec_retriever.py | 7 +++---- src/grag/rag/basic_rag.py | 2 +- src/tests/rag/basic_rag_test.py | 2 +- 4 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/grag/components/chroma_client.py b/src/grag/components/chroma_client.py index 1d816bd..7efd7c3 100644 --- a/src/grag/components/chroma_client.py +++ b/src/grag/components/chroma_client.py @@ -1,15 +1,14 @@ from typing import List import chromadb +from grag.components.embedding import Embedding +from grag.components.utils import get_config from langchain_community.vectorstores import Chroma from langchain_community.vectorstores.utils import filter_complex_metadata from langchain_core.documents import Document from tqdm import tqdm from tqdm.asyncio import tqdm as atqdm -from grag.components.embedding import Embedding -from grag.components.utils import get_config - chroma_conf = get_config()["chroma"] diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index 9946a3a..18ed752 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -2,13 +2,12 @@ import uuid from typing import List -from langchain.retrievers.multi_vector import MultiVectorRetriever -from langchain.storage import LocalFileStore -from langchain_core.documents import Document - from grag.components.chroma_client import ChromaClient from grag.components.text_splitter import TextSplitter from grag.components.utils import get_config +from langchain.retrievers.multi_vector import MultiVectorRetriever +from langchain.storage import LocalFileStore +from langchain_core.documents import Document multivec_retriever_conf = get_config()["multivec_retriever"] diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index 9589920..a99ecdd 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -4,7 +4,7 @@ from grag import prompts from grag.components.llm import LLM from grag.components.multivec_retriever import Retriever -from grag.components.prompt import Prompt, FewShotPrompt +from grag.components.prompt import FewShotPrompt, Prompt from grag.components.utils import get_config from importlib_resources import files from langchain_core.documents import Document diff --git a/src/tests/rag/basic_rag_test.py b/src/tests/rag/basic_rag_test.py index 2249028..06db25e 100644 --- a/src/tests/rag/basic_rag_test.py +++ b/src/tests/rag/basic_rag_test.py @@ -1,4 +1,4 @@ -from typing import Text, List +from typing import List, Text from grag.rag.basic_rag import BasicRAG From c151a502a7013d494014aba96a58b9fe515b0d94 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Thu, 21 Mar 2024 14:08:14 -0400 Subject: [PATCH 29/53] Refactor attributes from multivec_retriever for consistency. --- projects/Retriver-GUI/retriever_app.py | 14 +++---- src/grag/components/multivec_retriever.py | 45 +++++++++-------------- src/grag/rag/basic_rag.py | 2 +- src/tests/rag/basic_rag_test.py | 2 +- 4 files changed, 26 insertions(+), 37 deletions(-) diff --git a/projects/Retriver-GUI/retriever_app.py b/projects/Retriver-GUI/retriever_app.py index f55c0c6..9f4198c 100644 --- a/projects/Retriver-GUI/retriever_app.py +++ b/projects/Retriver-GUI/retriever_app.py @@ -46,7 +46,7 @@ def render_search_results(self): st.write(result.metadata) def check_connection(self): - response = self.app.retriever.client.test_connection() + response = self.app.retriever.vectordb.test_connection() if response: return True else: @@ -55,14 +55,14 @@ def check_connection(self): def render_stats(self): st.write(f''' **Chroma Client Details:** \n - Host Address : {self.app.retriever.client.host}:{self.app.retriever.client.port} \n - Collection Name : {self.app.retriever.client.collection_name} \n - Embeddings Type : {self.app.retriever.client.embedding_type} \n - Embeddings Model: {self.app.retriever.client.embedding_model} \n - Number of docs : {self.app.retriever.client.collection.count()} \n + Host Address : {self.app.retriever.vectordb.host}:{self.app.retriever.vectordb.port} \n + Collection Name : {self.app.retriever.vectordb.collection_name} \n + Embeddings Type : {self.app.retriever.vectordb.embedding_type} \n + Embeddings Model: {self.app.retriever.vectordb.embedding_model} \n + Number of docs : {self.app.retriever.vectordb.collection.count()} \n ''') if st.button('Check Connection'): - response = self.app.retriever.client.test_connection() + response = self.app.retriever.vectordb.test_connection() if response: st.write(':green[Connection Active]') else: diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index 18ed752..b57a67f 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -2,9 +2,10 @@ import uuid from typing import List -from grag.components.chroma_client import ChromaClient from grag.components.text_splitter import TextSplitter from grag.components.utils import get_config +from grag.components.vectordb.base import VectorDB +from grag.components.vectordb.chroma_client import ChromaClient from langchain.retrievers.multi_vector import MultiVectorRetriever from langchain.storage import LocalFileStore from langchain_core.documents import Document @@ -20,7 +21,7 @@ class Retriever: Attributes: store_path: Path to the local file store id_key: A key prefix for identifying documents - client: ChromaClient class instance from components.chroma_client + vectordb: ChromaClient class instance from components.client store: langchain.storage.LocalFileStore object, stores the key value pairs of document id and parent file retriever: langchain.retrievers.multi_vector.MultiVectorRetriever class instance, langchain's multi-vector retriever splitter: TextSplitter class instance from components.text_splitter @@ -30,11 +31,11 @@ class Retriever: """ def __init__( - self, - store_path: str = multivec_retriever_conf["store_path"], - id_key: str = multivec_retriever_conf["id_key"], - namespace: str = multivec_retriever_conf["namespace"], - top_k=1, + self, + store_path: str = multivec_retriever_conf["store_path"], + id_key: str = multivec_retriever_conf["id_key"], + namespace: str = multivec_retriever_conf["namespace"], + top_k=1, ): """Args: store_path: Path to the local file store, defaults to argument from config file @@ -45,10 +46,10 @@ def __init__( self.store_path = store_path self.id_key = id_key self.namespace = uuid.UUID(namespace) - self.client = ChromaClient() + self.vectordb: VectorDB = ChromaClient() # TODO - change to init argument self.store = LocalFileStore(self.store_path) self.retriever = MultiVectorRetriever( - vectorstore=self.client.langchain_chroma, + vectorstore=self.vectordb.langchain_client, byte_store=self.store, id_key=self.id_key, ) @@ -113,7 +114,7 @@ def add_docs(self, docs: List[Document]): """ chunks = self.split_docs(docs) doc_ids = self.gen_doc_ids(docs) - self.client.add_docs(chunks) + self.vectordb.add_docs(chunks) self.retriever.docstore.mset(list(zip(doc_ids, docs))) async def aadd_docs(self, docs: List[Document]): @@ -129,11 +130,11 @@ async def aadd_docs(self, docs: List[Document]): """ chunks = self.split_docs(docs) doc_ids = self.gen_doc_ids(docs) - await asyncio.run(self.client.aadd_docs(chunks)) + await asyncio.run(self.vectordb.aadd_docs(chunks)) self.retriever.docstore.mset(list(zip(doc_ids))) def get_chunk(self, query: str, with_score=False, top_k=None): - """Returns the most (cosine) similar chunks from the vector database. + """Returns the most similar chunks from the vector database. Args: query: A query string @@ -144,14 +145,8 @@ def get_chunk(self, query: str, with_score=False, top_k=None): list of Documents """ - if with_score: - return self.client.langchain_chroma.similarity_search_with_relevance_scores( - query=query, **{"k": top_k} if top_k else self.retriever.search_kwargs - ) - else: - return self.client.langchain_chroma.similarity_search( - query=query, **{"k": top_k} if top_k else self.retriever.search_kwargs - ) + _top_k = top_k if top_k else self.retriever.search_kwargs['k'] + return self.vectordb.get_chunk(query=query, top_k=_top_k, with_score=with_score) async def aget_chunk(self, query: str, with_score=False, top_k=None): """Returns the most (cosine) similar chunks from the vector database, asynchronously. @@ -165,14 +160,8 @@ async def aget_chunk(self, query: str, with_score=False, top_k=None): list of Documents """ - if with_score: - return await self.client.langchain_chroma.asimilarity_search_with_relevance_scores( - query=query, **{"k": top_k} if top_k else self.retriever.search_kwargs - ) - else: - return await self.client.langchain_chroma.asimilarity_search( - query=query, **{"k": top_k} if top_k else self.retriever.search_kwargs - ) + _top_k = top_k if top_k else self.retriever.search_kwargs['k'] + return await self.vectordb.aget_chunk(query=query, top_k=_top_k, with_score=with_score) def get_doc(self, query: str): """Returns the parent document of the most (cosine) similar chunk from the vector database. diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index a99ecdd..9589920 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -4,7 +4,7 @@ from grag import prompts from grag.components.llm import LLM from grag.components.multivec_retriever import Retriever -from grag.components.prompt import FewShotPrompt, Prompt +from grag.components.prompt import Prompt, FewShotPrompt from grag.components.utils import get_config from importlib_resources import files from langchain_core.documents import Document diff --git a/src/tests/rag/basic_rag_test.py b/src/tests/rag/basic_rag_test.py index 06db25e..2249028 100644 --- a/src/tests/rag/basic_rag_test.py +++ b/src/tests/rag/basic_rag_test.py @@ -1,4 +1,4 @@ -from typing import List, Text +from typing import Text, List from grag.rag.basic_rag import BasicRAG From 5e72ad990c9926d850c00d35d30cb54021e30b86 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Thu, 21 Mar 2024 14:08:38 -0400 Subject: [PATCH 30/53] DeepLake client, vectordb --- pyproject.toml | 1 + src/grag/components/vectordb/__init__.py | 0 src/grag/components/vectordb/base.py | 64 +++++++ src/grag/components/vectordb/chroma_client.py | 170 ++++++++++++++++++ .../components/vectordb/deeplake_client.py | 132 ++++++++++++++ 5 files changed, 367 insertions(+) create mode 100644 src/grag/components/vectordb/__init__.py create mode 100644 src/grag/components/vectordb/base.py create mode 100644 src/grag/components/vectordb/chroma_client.py create mode 100644 src/grag/components/vectordb/deeplake_client.py diff --git a/pyproject.toml b/pyproject.toml index 897ab02..58c2fe0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,6 +42,7 @@ dependencies = [ "huggingface_hub>=0.20.2", "pydantic>=2.5.0", "rouge-score>=0.1.2", + "deeplake>=3.8.27" ] [project.urls] diff --git a/src/grag/components/vectordb/__init__.py b/src/grag/components/vectordb/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/grag/components/vectordb/base.py b/src/grag/components/vectordb/base.py new file mode 100644 index 0000000..67bc5be --- /dev/null +++ b/src/grag/components/vectordb/base.py @@ -0,0 +1,64 @@ +from abc import ABC, abstractmethod +from typing import List + +from langchain_community.vectorstores.utils import filter_complex_metadata +from langchain_core.documents import Document + + +class VectorDB(ABC): + @abstractmethod + def add_docs(self, docs: List[Document], verbose: bool = True): + """Adds documents to the vector database. + + Args: + docs: List of Documents + verbose: Show progress bar + + Returns: + None + """ + ... + + @abstractmethod + async def aadd_docs(self, docs: List[Document], verbose: bool = True): + """Adds documents to the vector database (asynchronous). + + Args: + docs: List of Documents + verbose: Show progress bar + + Returns: + None + """ + ... + + @abstractmethod + def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): + """Returns the most similar chunks from the vector database. + + Args: + query: A query string + with_score: Outputs scores of returned chunks + top_k: Number of top similar chunks to return, if None defaults to self.top_k + + Returns: + list of Documents + """ + ... + + @abstractmethod + async def aget_chunk(self, query: str, with_score: bool = False, top_k: int = None): + """Returns the most similar chunks from the vector database. (asynchronous) + + Args: + query: A query string + with_score: Outputs scores of returned chunks + top_k: Number of top similar chunks to return, if None defaults to self.top_k + + Returns: + list of Documents + """ + ... + + def _filter_metadata(self, docs: List[Document]): + return filter_complex_metadata(docs, allowed_types=self.allowed_metadata_types) diff --git a/src/grag/components/vectordb/chroma_client.py b/src/grag/components/vectordb/chroma_client.py new file mode 100644 index 0000000..53f5547 --- /dev/null +++ b/src/grag/components/vectordb/chroma_client.py @@ -0,0 +1,170 @@ +from typing import List + +import chromadb +from grag.components.embedding import Embedding +from grag.components.utils import get_config +from grag.components.vectordb.base import VectorDB +from langchain_community.vectorstores import Chroma +from langchain_core.documents import Document +from tqdm import tqdm +from tqdm.asyncio import tqdm as atqdm + +chroma_conf = get_config()["chroma"] + + +class ChromaClient(VectorDB): + """A class for connecting to a hosted Chroma Vectorstore collection. + + Attributes: + host : str + IP Address of hosted Chroma Vectorstore + port : str + port address of hosted Chroma Vectorstore + collection_name : str + name of the collection in the Chroma Vectorstore, each ChromaClient connects to a single collection + embedding_type : str + type of embedding used, supported 'sentence-transformers' and 'instructor-embedding' + embedding_model : str + model name of embedding used, should correspond to the embedding_type + embedding_function + a function of the embedding model, derived from the embedding_type and embedding_modelname + client: chromadb.HttpClient + Chroma API for client + collection + Chroma API for the collection + langchain_client: langchain_community.vectorstores.Chroma + LangChain wrapper for Chroma collection + """ + + def __init__( + self, + host=chroma_conf["host"], + port=chroma_conf["port"], + collection_name=chroma_conf["collection_name"], + embedding_type=chroma_conf["embedding_type"], + embedding_model=chroma_conf["embedding_model"], + ): + """Args: + host: IP Address of hosted Chroma Vectorstore, defaults to argument from config file + port: port address of hosted Chroma Vectorstore, defaults to argument from config file + collection_name: name of the collection in the Chroma Vectorstore, defaults to argument from config file + embedding_type: type of embedding used, supported 'sentence-transformers' and 'instructor-embedding', defaults to argument from config file + embedding_model: model name of embedding used, should correspond to the embedding_type, defaults to argument from config file + """ + self.host: str = host + self.port: str = port + self.collection_name: str = collection_name + self.embedding_type: str = embedding_type + self.embedding_model: str = embedding_model + + self.embedding_function = Embedding( + embedding_model=self.embedding_model, embedding_type=self.embedding_type + ).embedding_function + + self.client = chromadb.HttpClient(host=self.host, port=self.port) + self.collection = self.client.get_or_create_collection( + name=self.collection_name + ) + self.langchain_client = Chroma( + client=self.client, + collection_name=self.collection_name, + embedding_function=self.embedding_function, + ) + self.allowed_metadata_types = (str, int, float, bool) + + def test_connection(self, verbose=True): + """Tests connection with Chroma Vectorstore + + Args: + verbose: if True, prints connection status + + Returns: + A random integer if connection is alive else None + """ + response = self.client.heartbeat() + if verbose: + if response: + print(f"Connection to {self.host}/{self.port} is alive..") + else: + print(f"Connection to {self.host}/{self.port} is not alive !!") + return response + + def add_docs(self, docs: List[Document], verbose=True): + """Adds documents to chroma vectorstore + + Args: + docs: List of Documents + verbose: Show progress bar + + Returns: + None + """ + docs = self._filter_metadata(docs) + for doc in ( + tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs + ): + _id = self.langchain_client.add_documents([doc]) + + async def aadd_docs(self, docs: List[Document], verbose=True): + """Asynchronously adds documents to chroma vectorstore + + Args: + docs: List of Documents + verbose: Show progress bar + + Returns: + None + """ + docs = self._filter_metadata(docs) + if verbose: + for doc in atqdm( + docs, + desc=f"Adding documents to {self.collection_name}", + total=len(docs), + ): + await self.langchain_client.aadd_documents([doc]) + else: + for doc in docs: + await self.langchain_client.aadd_documents([doc]) + + def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): + """Returns the most similar chunks from the chroma database. + + Args: + query: A query string + with_score: Outputs scores of returned chunks + top_k: Number of top similar chunks to return, if None defaults to self.top_k + + Returns: + list of Documents + + """ + if with_score: + return self.langchain_client.similarity_search_with_relevance_scores( + query=query, **{"k": top_k} if top_k else 1 + ) + else: + return self.langchain_client.similarity_search( + query=query, **{"k": top_k} if top_k else 1 + ) + + async def aget_chunk(self, query: str, with_score=False, top_k=None): + """Returns the most (cosine) similar chunks from the vector database, asynchronously. + + Args: + query: A query string + with_score: Outputs scores of returned chunks + top_k: Number of top similar chunks to return, if None defaults to self.top_k + + Returns: + list of Documents + + """ + if with_score: + return await self.langchain_client.asimilarity_search_with_relevance_scores( + query=query, **{"k": top_k} if top_k else 1 + ) + else: + return await self.langchain_client.asimilarity_search( + query=query, **{"k": top_k} if top_k else 1 + ) diff --git a/src/grag/components/vectordb/deeplake_client.py b/src/grag/components/vectordb/deeplake_client.py new file mode 100644 index 0000000..75d6058 --- /dev/null +++ b/src/grag/components/vectordb/deeplake_client.py @@ -0,0 +1,132 @@ +from pathlib import Path +from typing import List, Union + +from deeplake.core.vectorstore import VectorStore +from grag.components.embedding import Embedding +from grag.components.utils import get_config +from grag.components.vectordb.base import VectorDB +from langchain_community.vectorstores import DeepLake +from langchain_core.documents import Document +from tqdm import tqdm +from tqdm.asyncio import tqdm as atqdm + +deeplake_conf = get_config()["deeplake"] + + +class DeepLakeClient(VectorDB): + """A class for connecting to a DeepLake Vectorstore + + Attributes: + store_path : str, Path + The path to store the DeepLake vectorstore. + embedding_type : str + type of embedding used, supported 'sentence-transformers' and 'instructor-embedding' + embedding_model : str + model name of embedding used, should correspond to the embedding_type + embedding_function + a function of the embedding model, derived from the embedding_type and embedding_modelname + client: deeplake.core.vectorstore.VectorStore + DeepLake API + collection + Chroma API for the collection + langchain_client: langchain_community.vectorstores.DeepLake + LangChain wrapper for DeepLake API + """ + + def __init__(self, + store_path: Union[str, Path], + embedding_model: str, + embedding_type: str, + ): + self.store_path = Path(store_path) + self.embedding_type: str = embedding_type + self.embedding_model: str = embedding_model + + self.embedding_function = Embedding( + embedding_model=self.embedding_model, embedding_type=self.embedding_type + ).embedding_function + + self.client = VectorStore(path=self.store_path) + self.langchain_client = DeepLake(path=self.store_path, + embedding=self.embedding_function) + self.allowed_metadata_types = (str, int, float, bool) + + def add_docs(self, docs: List[Document], verbose=True): + """Adds documents to deeplake vectorstore + + Args: + docs: List of Documents + verbose: Show progress bar + + Returns: + None + """ + docs = self._filter_metadata(docs) + for doc in ( + tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs + ): + _id = self.langchain_chroma.add_documents([doc]) + + async def aadd_docs(self, docs: List[Document], verbose=True): + """Asynchronously adds documents to chroma vectorstore + + Args: + docs: List of Documents + verbose: Show progress bar + + Returns: + None + """ + docs = self._filter_metadata(docs) + if verbose: + for doc in atqdm( + docs, + desc=f"Adding documents to {self.collection_name}", + total=len(docs), + ): + await self.langchain_deeplake.aadd_documents([doc]) + else: + for doc in docs: + await self.langchain_deeplake.aadd_documents([doc]) + + def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): + """Returns the most similar chunks from the deeplake database. + + Args: + query: A query string + with_score: Outputs scores of returned chunks + top_k: Number of top similar chunks to return, if None defaults to self.top_k + + Returns: + list of Documents + + """ + if with_score: + return self.langchain_client.similarity_search_with_relevance_scores( + query=query, **{"k": top_k} if top_k else 1 + ) + else: + return self.langchain_client.similarity_search( + query=query, **{"k": top_k} if top_k else 1 + ) + + async def aget_chunk(self, query: str, with_score=False, top_k=None): + """Returns the most similar chunks from the deeplake database, asynchronously. + + Args: + query: A query string + with_score: Outputs scores of returned chunks + top_k: Number of top similar chunks to return, if None defaults to self.top_k + + Returns: + list of Documents + + """ + if with_score: + return await self.langchain_client.asimilarity_search_with_relevance_scores( + query=query, **{"k": top_k} if top_k else 1 + ) + else: + return await self.langchain_client.asimilarity_search( + query=query, **{"k": top_k} if top_k else 1 + ) From 820702f3a8dfc9c73d1eaa3251942894e16a42b0 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Thu, 21 Mar 2024 16:35:10 -0400 Subject: [PATCH 31/53] Remove old chroma_client --- src/grag/components/chroma_client.py | 136 --------------------------- 1 file changed, 136 deletions(-) delete mode 100644 src/grag/components/chroma_client.py diff --git a/src/grag/components/chroma_client.py b/src/grag/components/chroma_client.py deleted file mode 100644 index 7efd7c3..0000000 --- a/src/grag/components/chroma_client.py +++ /dev/null @@ -1,136 +0,0 @@ -from typing import List - -import chromadb -from grag.components.embedding import Embedding -from grag.components.utils import get_config -from langchain_community.vectorstores import Chroma -from langchain_community.vectorstores.utils import filter_complex_metadata -from langchain_core.documents import Document -from tqdm import tqdm -from tqdm.asyncio import tqdm as atqdm - -chroma_conf = get_config()["chroma"] - - -class ChromaClient: - """A class for connecting to a hosted Chroma Vectorstore collection. - - Attributes: - host : str - IP Address of hosted Chroma Vectorstore - port : str - port address of hosted Chroma Vectorstore - collection_name : str - name of the collection in the Chroma Vectorstore, each ChromaClient connects to a single collection - embedding_type : str - type of embedding used, supported 'sentence-transformers' and 'instructor-embedding' - embedding_modelname : str - model name of embedding used, should correspond to the embedding_type - embedding_function - a function of the embedding model, derived from the embedding_type and embedding_modelname - chroma_client - Chroma API for client - collection - Chroma API for the collection - langchain_chroma - LangChain wrapper for Chroma collection - """ - - def __init__( - self, - host=chroma_conf["host"], - port=chroma_conf["port"], - collection_name=chroma_conf["collection_name"], - embedding_type=chroma_conf["embedding_type"], - embedding_model=chroma_conf["embedding_model"], - ): - """Args: - host: IP Address of hosted Chroma Vectorstore, defaults to argument from config file - port: port address of hosted Chroma Vectorstore, defaults to argument from config file - collection_name: name of the collection in the Chroma Vectorstore, defaults to argument from config file - embedding_type: type of embedding used, supported 'sentence-transformers' and 'instructor-embedding', defaults to argument from config file - embedding_model: model name of embedding used, should correspond to the embedding_type, defaults to argument from config file - """ - self.host: str = host - self.port: str = port - self.collection_name: str = collection_name - self.embedding_type: str = embedding_type - self.embedding_model: str = embedding_model - - self.embedding_function = Embedding( - embedding_model=self.embedding_model, embedding_type=self.embedding_type - ).embedding_function - - self.chroma_client = chromadb.HttpClient(host=self.host, port=self.port) - self.collection = self.chroma_client.get_or_create_collection( - name=self.collection_name - ) - self.langchain_chroma = Chroma( - client=self.chroma_client, - collection_name=self.collection_name, - embedding_function=self.embedding_function, - ) - self.allowed_metadata_types = (str, int, float, bool) - - def test_connection(self, verbose=True): - """Tests connection with Chroma Vectorstore - - Args: - verbose: if True, prints connection status - - Returns: - A random integer if connection is alive else None - """ - response = self.chroma_client.heartbeat() - if verbose: - if response: - print(f"Connection to {self.host}/{self.port} is alive..") - else: - print(f"Connection to {self.host}/{self.port} is not alive !!") - return response - - async def aadd_docs(self, docs: List[Document], verbose=True): - """Asynchronously adds documents to chroma vectorstore - - Args: - docs: List of Documents - verbose: Show progress bar - - Returns: - None - """ - docs = self._filter_metadata(docs) - # tasks = [self.langchain_chroma.aadd_documents([doc]) for doc in docs] - # if verbose: - # await tqdm_asyncio.gather(*tasks, desc=f'Adding to {self.collection_name}') - # else: - # await asyncio.gather(*tasks) - if verbose: - for doc in atqdm( - docs, - desc=f"Adding documents to {self.collection_name}", - total=len(docs), - ): - await self.langchain_chroma.aadd_documents([doc]) - else: - for doc in docs: - await self.langchain_chroma.aadd_documents([doc]) - - def add_docs(self, docs: List[Document], verbose=True): - """Adds documents to chroma vectorstore - - Args: - docs: List of Documents - verbose: Show progress bar - - Returns: - None - """ - docs = self._filter_metadata(docs) - for doc in ( - tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs - ): - _id = self.langchain_chroma.add_documents([doc]) - - def _filter_metadata(self, docs: List[Document]): - return filter_complex_metadata(docs, allowed_types=self.allowed_metadata_types) From 7729d32647b29cce059d462d891995d00e427038 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Thu, 21 Mar 2024 16:37:14 -0400 Subject: [PATCH 32/53] Bug fix: top_k --- src/grag/components/vectordb/chroma_client.py | 8 ++++---- src/grag/components/vectordb/deeplake_client.py | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/grag/components/vectordb/chroma_client.py b/src/grag/components/vectordb/chroma_client.py index 53f5547..3e73b04 100644 --- a/src/grag/components/vectordb/chroma_client.py +++ b/src/grag/components/vectordb/chroma_client.py @@ -141,11 +141,11 @@ def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): """ if with_score: return self.langchain_client.similarity_search_with_relevance_scores( - query=query, **{"k": top_k} if top_k else 1 + query=query, k=top_k if top_k else 1 ) else: return self.langchain_client.similarity_search( - query=query, **{"k": top_k} if top_k else 1 + query=query, k=top_k if top_k else 1 ) async def aget_chunk(self, query: str, with_score=False, top_k=None): @@ -162,9 +162,9 @@ async def aget_chunk(self, query: str, with_score=False, top_k=None): """ if with_score: return await self.langchain_client.asimilarity_search_with_relevance_scores( - query=query, **{"k": top_k} if top_k else 1 + query=query, k=top_k if top_k else 1 ) else: return await self.langchain_client.asimilarity_search( - query=query, **{"k": top_k} if top_k else 1 + query=query, k=top_k if top_k else 1 ) diff --git a/src/grag/components/vectordb/deeplake_client.py b/src/grag/components/vectordb/deeplake_client.py index 75d6058..bb88255 100644 --- a/src/grag/components/vectordb/deeplake_client.py +++ b/src/grag/components/vectordb/deeplake_client.py @@ -103,11 +103,11 @@ def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): """ if with_score: return self.langchain_client.similarity_search_with_relevance_scores( - query=query, **{"k": top_k} if top_k else 1 + query=query, k=top_k if top_k else 1 ) else: return self.langchain_client.similarity_search( - query=query, **{"k": top_k} if top_k else 1 + query=query, k=top_k if top_k else 1 ) async def aget_chunk(self, query: str, with_score=False, top_k=None): @@ -124,9 +124,9 @@ async def aget_chunk(self, query: str, with_score=False, top_k=None): """ if with_score: return await self.langchain_client.asimilarity_search_with_relevance_scores( - query=query, **{"k": top_k} if top_k else 1 + query=query, k=top_k if top_k else 1 ) else: return await self.langchain_client.asimilarity_search( - query=query, **{"k": top_k} if top_k else 1 + query=query, k=top_k if top_k else 1 ) From 2f05d98c37d6358c9140a33c09d78877b845557e Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Thu, 21 Mar 2024 16:37:47 -0400 Subject: [PATCH 33/53] Update chroma_client_test --- src/tests/components/vectordb/__init__.py | 0 .../{ => vectordb}/chroma_client_test.py | 79 +++++++++++++++---- 2 files changed, 64 insertions(+), 15 deletions(-) create mode 100644 src/tests/components/vectordb/__init__.py rename src/tests/components/{ => vectordb}/chroma_client_test.py (58%) diff --git a/src/tests/components/vectordb/__init__.py b/src/tests/components/vectordb/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tests/components/chroma_client_test.py b/src/tests/components/vectordb/chroma_client_test.py similarity index 58% rename from src/tests/components/chroma_client_test.py rename to src/tests/components/vectordb/chroma_client_test.py index 1596dd3..6f0e925 100644 --- a/src/tests/components/chroma_client_test.py +++ b/src/tests/components/vectordb/chroma_client_test.py @@ -1,12 +1,13 @@ import asyncio -from grag.components.chroma_client import ChromaClient +import pytest +from grag.components.vectordb.chroma_client import ChromaClient from langchain_core.documents import Document def test_chroma_connection(): - client = ChromaClient() - response = client.test_connection() + chroma_client = ChromaClient() + response = chroma_client.test_connection() assert isinstance(response, int) @@ -45,13 +46,13 @@ def test_chroma_add_docs(): storm-clouds was split to the blinding zigzag of lightning, and the thunder rolled and boomed, like the Colorado in flood.""", ] - client = ChromaClient(collection_name="test") - if client.collection.count() > 0: - client.chroma_client.delete_collection("test") - client = ChromaClient(collection_name="test") + chroma_client = ChromaClient(collection_name="test") + if chroma_client.collection.count() > 0: + chroma_client.client.delete_collection("test") + chroma_client = ChromaClient(collection_name="test") docs = [Document(page_content=doc) for doc in docs] - client.add_docs(docs) - collection_count = client.collection.count() + chroma_client.add_docs(docs) + collection_count = chroma_client.collection.count() assert collection_count == len(docs) @@ -90,11 +91,59 @@ def test_chroma_aadd_docs(): storm-clouds was split to the blinding zigzag of lightning, and the thunder rolled and boomed, like the Colorado in flood.""", ] - client = ChromaClient(collection_name="test") - if client.collection.count() > 0: - client.chroma_client.delete_collection("test") - client = ChromaClient(collection_name="test") + chroma_client = ChromaClient(collection_name="test") + if chroma_client.collection.count() > 0: + chroma_client.client.delete_collection("test") + chroma_client = ChromaClient(collection_name="test") docs = [Document(page_content=doc) for doc in docs] loop = asyncio.get_event_loop() - loop.run_until_complete(client.aadd_docs(docs)) - assert client.collection.count() == len(docs) + loop.run_until_complete(chroma_client.aadd_docs(docs)) + assert chroma_client.collection.count() == len(docs) + + +chrome_get_chunk_params = [(1, False), (1, True), (2, False), (2, True)] + + +@pytest.mark.parametrize("top_k,with_score", chrome_get_chunk_params) +def test_chroma_get_chunk(top_k, with_score): + query = """Slone and Lucy never rode down so far as the stately monuments, though + these held memories as hauntingly sweet as others were poignantly + bitter. Lucy never rode the King again. But Slone rode him, learned to + love him. And Lucy did not race any more. When Slone tried to stir in + her the old spirit all the response he got was a wistful shake of head + or a laugh that hid the truth or an excuse that the strain on her + ankles from Joel Creech's lasso had never mended. The girl was + unutterably happy, but it was possible that she would never race a + horse again.""" + chroma_client = ChromaClient(collection_name="test") + retrieved_chunks = chroma_client.get_chunk(query=query, top_k=top_k, with_score=with_score) + assert len(retrieved_chunks) == top_k + if with_score: + assert all(isinstance(doc[0], Document) for doc in retrieved_chunks) + assert all(isinstance(doc[1], float) for doc in retrieved_chunks) + else: + assert all(isinstance(doc, Document) for doc in retrieved_chunks) + + +@pytest.mark.parametrize("top_k,with_score", chrome_get_chunk_params) +def test_chroma_aget_chunk(top_k, with_score): + query = """Slone and Lucy never rode down so far as the stately monuments, though + these held memories as hauntingly sweet as others were poignantly + bitter. Lucy never rode the King again. But Slone rode him, learned to + love him. And Lucy did not race any more. When Slone tried to stir in + her the old spirit all the response he got was a wistful shake of head + or a laugh that hid the truth or an excuse that the strain on her + ankles from Joel Creech's lasso had never mended. The girl was + unutterably happy, but it was possible that she would never race a + horse again.""" + chroma_client = ChromaClient(collection_name="test") + loop = asyncio.get_event_loop() + retrieved_chunks = loop.run_until_complete( + chroma_client.aget_chunk(query=query, top_k=top_k, with_score=with_score) + ) + assert len(retrieved_chunks) == top_k + if with_score: + assert all(isinstance(doc[0], Document) for doc in retrieved_chunks) + assert all(isinstance(doc[1], float) for doc in retrieved_chunks) + else: + assert all(isinstance(doc, Document) for doc in retrieved_chunks) From 41b2bcf4c89658ab7bd184864805457bc0752232 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Fri, 22 Mar 2024 16:02:30 -0400 Subject: [PATCH 34/53] Deeplake tests, typing --- src/grag/components/vectordb/base.py | 24 ++- src/grag/components/vectordb/chroma_client.py | 28 +++- .../components/vectordb/deeplake_client.py | 47 +++--- .../components/vectordb/chroma_client_test.py | 15 +- .../vectordb/deeplake_client_test.py | 144 ++++++++++++++++++ 5 files changed, 220 insertions(+), 38 deletions(-) create mode 100644 src/tests/components/vectordb/deeplake_client_test.py diff --git a/src/grag/components/vectordb/base.py b/src/grag/components/vectordb/base.py index 67bc5be..ab63fcb 100644 --- a/src/grag/components/vectordb/base.py +++ b/src/grag/components/vectordb/base.py @@ -1,13 +1,23 @@ from abc import ABC, abstractmethod -from typing import List +from typing import List, Tuple, Union from langchain_community.vectorstores.utils import filter_complex_metadata from langchain_core.documents import Document class VectorDB(ABC): + + @abstractmethod + def __len__(self) -> int: + """Number of chunks in the vector database.""" + ... + + @abstractmethod + def delete(self) -> None: + """Delete all chunks in the vector database.""" + @abstractmethod - def add_docs(self, docs: List[Document], verbose: bool = True): + def add_docs(self, docs: List[Document], verbose: bool = True) -> None: """Adds documents to the vector database. Args: @@ -20,7 +30,7 @@ def add_docs(self, docs: List[Document], verbose: bool = True): ... @abstractmethod - async def aadd_docs(self, docs: List[Document], verbose: bool = True): + async def aadd_docs(self, docs: List[Document], verbose: bool = True) -> None: """Adds documents to the vector database (asynchronous). Args: @@ -33,7 +43,8 @@ async def aadd_docs(self, docs: List[Document], verbose: bool = True): ... @abstractmethod - def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): + def get_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> Union[ + List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the vector database. Args: @@ -47,7 +58,8 @@ def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): ... @abstractmethod - async def aget_chunk(self, query: str, with_score: bool = False, top_k: int = None): + async def aget_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> Union[ + List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the vector database. (asynchronous) Args: @@ -60,5 +72,5 @@ async def aget_chunk(self, query: str, with_score: bool = False, top_k: int = No """ ... - def _filter_metadata(self, docs: List[Document]): + def _filter_metadata(self, docs: List[Document]) -> List[Document]: return filter_complex_metadata(docs, allowed_types=self.allowed_metadata_types) diff --git a/src/grag/components/vectordb/chroma_client.py b/src/grag/components/vectordb/chroma_client.py index 3e73b04..e97323d 100644 --- a/src/grag/components/vectordb/chroma_client.py +++ b/src/grag/components/vectordb/chroma_client.py @@ -1,4 +1,4 @@ -from typing import List +from typing import List, Tuple, Union import chromadb from grag.components.embedding import Embedding @@ -72,7 +72,21 @@ def __init__( ) self.allowed_metadata_types = (str, int, float, bool) - def test_connection(self, verbose=True): + def __len__(self) -> int: + return self.collection.count() + + def delete(self) -> None: + self.client.delete_collection(self.collection_name) + self.collection = self.client.get_or_create_collection( + name=self.collection_name + ) + self.langchain_client = Chroma( + client=self.client, + collection_name=self.collection_name, + embedding_function=self.embedding_function, + ) + + def test_connection(self, verbose=True) -> int: """Tests connection with Chroma Vectorstore Args: @@ -89,7 +103,7 @@ def test_connection(self, verbose=True): print(f"Connection to {self.host}/{self.port} is not alive !!") return response - def add_docs(self, docs: List[Document], verbose=True): + def add_docs(self, docs: List[Document], verbose=True) -> None: """Adds documents to chroma vectorstore Args: @@ -105,7 +119,7 @@ def add_docs(self, docs: List[Document], verbose=True): ): _id = self.langchain_client.add_documents([doc]) - async def aadd_docs(self, docs: List[Document], verbose=True): + async def aadd_docs(self, docs: List[Document], verbose=True) -> None: """Asynchronously adds documents to chroma vectorstore Args: @@ -127,7 +141,8 @@ async def aadd_docs(self, docs: List[Document], verbose=True): for doc in docs: await self.langchain_client.aadd_documents([doc]) - def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): + def get_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> Union[ + List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the chroma database. Args: @@ -148,7 +163,8 @@ def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): query=query, k=top_k if top_k else 1 ) - async def aget_chunk(self, query: str, with_score=False, top_k=None): + async def aget_chunk(self, query: str, with_score=False, top_k=None) -> Union[ + List[Document], List[Tuple[Document, float]]]: """Returns the most (cosine) similar chunks from the vector database, asynchronously. Args: diff --git a/src/grag/components/vectordb/deeplake_client.py b/src/grag/components/vectordb/deeplake_client.py index bb88255..28fc606 100644 --- a/src/grag/components/vectordb/deeplake_client.py +++ b/src/grag/components/vectordb/deeplake_client.py @@ -1,7 +1,6 @@ from pathlib import Path -from typing import List, Union +from typing import List, Tuple, Union -from deeplake.core.vectorstore import VectorStore from grag.components.embedding import Embedding from grag.components.utils import get_config from grag.components.vectordb.base import VectorDB @@ -34,11 +33,15 @@ class DeepLakeClient(VectorDB): """ def __init__(self, - store_path: Union[str, Path], - embedding_model: str, - embedding_type: str, + collection_name: str = deeplake_conf["collection_name"], + store_path: Union[str, Path] = deeplake_conf["store_path"], + embedding_type: str = deeplake_conf["embedding_type"], + embedding_model: str = deeplake_conf["embedding_model"], + read_only: bool = False ): self.store_path = Path(store_path) + self.collection_name = collection_name + self.read_only = read_only self.embedding_type: str = embedding_type self.embedding_model: str = embedding_model @@ -46,12 +49,20 @@ def __init__(self, embedding_model=self.embedding_model, embedding_type=self.embedding_type ).embedding_function - self.client = VectorStore(path=self.store_path) - self.langchain_client = DeepLake(path=self.store_path, - embedding=self.embedding_function) + # self.client = VectorStore(path=self.store_path / self.collection_name) + self.langchain_client = DeepLake(dataset_path=str(self.store_path / self.collection_name), + embedding=self.embedding_function, + read_only=self.read_only) + self.client = self.langchain_client.vectorstore self.allowed_metadata_types = (str, int, float, bool) - def add_docs(self, docs: List[Document], verbose=True): + def __len__(self) -> int: + return self.client.__len__() + + def delete(self) -> None: + self.client.delete(delete_all=True) + + def add_docs(self, docs: List[Document], verbose=True) -> None: """Adds documents to deeplake vectorstore Args: @@ -65,9 +76,9 @@ def add_docs(self, docs: List[Document], verbose=True): for doc in ( tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs ): - _id = self.langchain_chroma.add_documents([doc]) + _id = self.langchain_client.add_documents([doc]) - async def aadd_docs(self, docs: List[Document], verbose=True): + async def aadd_docs(self, docs: List[Document], verbose=True) -> None: """Asynchronously adds documents to chroma vectorstore Args: @@ -84,12 +95,13 @@ async def aadd_docs(self, docs: List[Document], verbose=True): desc=f"Adding documents to {self.collection_name}", total=len(docs), ): - await self.langchain_deeplake.aadd_documents([doc]) + await self.langchain_client.aadd_documents([doc]) else: for doc in docs: - await self.langchain_deeplake.aadd_documents([doc]) + await self.langchain_client.aadd_documents([doc]) - def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): + def get_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> Union[ + List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the deeplake database. Args: @@ -102,7 +114,7 @@ def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): """ if with_score: - return self.langchain_client.similarity_search_with_relevance_scores( + return self.langchain_client.similarity_search_with_score( query=query, k=top_k if top_k else 1 ) else: @@ -110,7 +122,8 @@ def get_chunk(self, query: str, with_score: bool = False, top_k: int = None): query=query, k=top_k if top_k else 1 ) - async def aget_chunk(self, query: str, with_score=False, top_k=None): + async def aget_chunk(self, query: str, with_score=False, top_k=None) -> Union[ + List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the deeplake database, asynchronously. Args: @@ -123,7 +136,7 @@ async def aget_chunk(self, query: str, with_score=False, top_k=None): """ if with_score: - return await self.langchain_client.asimilarity_search_with_relevance_scores( + return await self.langchain_client.asimilarity_search_with_score( query=query, k=top_k if top_k else 1 ) else: diff --git a/src/tests/components/vectordb/chroma_client_test.py b/src/tests/components/vectordb/chroma_client_test.py index 6f0e925..ecffa22 100644 --- a/src/tests/components/vectordb/chroma_client_test.py +++ b/src/tests/components/vectordb/chroma_client_test.py @@ -47,13 +47,11 @@ def test_chroma_add_docs(): thunder rolled and boomed, like the Colorado in flood.""", ] chroma_client = ChromaClient(collection_name="test") - if chroma_client.collection.count() > 0: - chroma_client.client.delete_collection("test") - chroma_client = ChromaClient(collection_name="test") + if len(chroma_client) > 0: + chroma_client.delete() docs = [Document(page_content=doc) for doc in docs] chroma_client.add_docs(docs) - collection_count = chroma_client.collection.count() - assert collection_count == len(docs) + assert len(chroma_client) == len(docs) def test_chroma_aadd_docs(): @@ -92,13 +90,12 @@ def test_chroma_aadd_docs(): thunder rolled and boomed, like the Colorado in flood.""", ] chroma_client = ChromaClient(collection_name="test") - if chroma_client.collection.count() > 0: - chroma_client.client.delete_collection("test") - chroma_client = ChromaClient(collection_name="test") + if len(chroma_client) > 0: + chroma_client.delete() docs = [Document(page_content=doc) for doc in docs] loop = asyncio.get_event_loop() loop.run_until_complete(chroma_client.aadd_docs(docs)) - assert chroma_client.collection.count() == len(docs) + assert len(chroma_client) == len(docs) chrome_get_chunk_params = [(1, False), (1, True), (2, False), (2, True)] diff --git a/src/tests/components/vectordb/deeplake_client_test.py b/src/tests/components/vectordb/deeplake_client_test.py new file mode 100644 index 0000000..921bd18 --- /dev/null +++ b/src/tests/components/vectordb/deeplake_client_test.py @@ -0,0 +1,144 @@ +import asyncio + +import pytest +from grag.components.vectordb.deeplake_client import DeepLakeClient +from langchain_core.documents import Document + + +def test_deeplake_add_docs(): + docs = [ + """And so on this rainbow day, with storms all around them, and blue sky + above, they rode only as far as the valley. But from there, before they + turned to go back, the monuments appeared close, and they loomed + grandly with the background of purple bank and creamy cloud and shafts + of golden lightning. They seemed like sentinels--guardians of a great + and beautiful love born under their lofty heights, in the lonely + silence of day, in the star-thrown shadow of night. They were like that + love. And they held Lucy and Slone, calling every day, giving a + nameless and tranquil content, binding them true to love, true to the + sage and the open, true to that wild upland home.""", + """Slone and Lucy never rode down so far as the stately monuments, though + these held memories as hauntingly sweet as others were poignantly + bitter. Lucy never rode the King again. But Slone rode him, learned to + love him. And Lucy did not race any more. When Slone tried to stir in + her the old spirit all the response he got was a wistful shake of head + or a laugh that hid the truth or an excuse that the strain on her + ankles from Joel Creech's lasso had never mended. The girl was + unutterably happy, but it was possible that she would never race a + horse again.""", + """Bostil wanted to be alone, to welcome the King, to lead him back to the + home corral, perhaps to hide from all eyes the change and the uplift + that would forever keep him from wronging another man. + + The late rains came and like magic, in a few days, the sage grew green + and lustrous and fresh, the gray turning to purple. + + Every morning the sun rose white and hot in a blue and cloudless sky. + And then soon the horizon line showed creamy clouds that rose and + spread and darkened. Every afternoon storms hung along the ramparts and + rainbows curved down beautiful and ethereal. The dim blackness of the + storm-clouds was split to the blinding zigzag of lightning, and the + thunder rolled and boomed, like the Colorado in flood.""", + ] + deeplake_client = DeepLakeClient(collection_name="test") + if len(deeplake_client) > 0: + deeplake_client.delete() + docs = [Document(page_content=doc) for doc in docs] + deeplake_client.add_docs(docs) + assert len(deeplake_client) == len(docs) + del (deeplake_client) + + +def test_chroma_aadd_docs(): + docs = [ + """And so on this rainbow day, with storms all around them, and blue sky + above, they rode only as far as the valley. But from there, before they + turned to go back, the monuments appeared close, and they loomed + grandly with the background of purple bank and creamy cloud and shafts + of golden lightning. They seemed like sentinels--guardians of a great + and beautiful love born under their lofty heights, in the lonely + silence of day, in the star-thrown shadow of night. They were like that + love. And they held Lucy and Slone, calling every day, giving a + nameless and tranquil content, binding them true to love, true to the + sage and the open, true to that wild upland home.""", + """Slone and Lucy never rode down so far as the stately monuments, though + these held memories as hauntingly sweet as others were poignantly + bitter. Lucy never rode the King again. But Slone rode him, learned to + love him. And Lucy did not race any more. When Slone tried to stir in + her the old spirit all the response he got was a wistful shake of head + or a laugh that hid the truth or an excuse that the strain on her + ankles from Joel Creech's lasso had never mended. The girl was + unutterably happy, but it was possible that she would never race a + horse again.""", + """Bostil wanted to be alone, to welcome the King, to lead him back to the + home corral, perhaps to hide from all eyes the change and the uplift + that would forever keep him from wronging another man. + + The late rains came and like magic, in a few days, the sage grew green + and lustrous and fresh, the gray turning to purple. + + Every morning the sun rose white and hot in a blue and cloudless sky. + And then soon the horizon line showed creamy clouds that rose and + spread and darkened. Every afternoon storms hung along the ramparts and + rainbows curved down beautiful and ethereal. The dim blackness of the + storm-clouds was split to the blinding zigzag of lightning, and the + thunder rolled and boomed, like the Colorado in flood.""", + ] + deeplake_client = DeepLakeClient(collection_name="test") + if len(deeplake_client) > 0: + deeplake_client.delete() + docs = [Document(page_content=doc) for doc in docs] + loop = asyncio.get_event_loop() + loop.run_until_complete(deeplake_client.aadd_docs(docs)) + assert len(deeplake_client) == len(docs) + del (deeplake_client) + + +deeplake_get_chunk_params = [(1, False), (1, True), (2, False), (2, True)] + + +@pytest.mark.parametrize("top_k,with_score", deeplake_get_chunk_params) +def test_deeplake_get_chunk(top_k, with_score): + query = """Slone and Lucy never rode down so far as the stately monuments, though + these held memories as hauntingly sweet as others were poignantly + bitter. Lucy never rode the King again. But Slone rode him, learned to + love him. And Lucy did not race any more. When Slone tried to stir in + her the old spirit all the response he got was a wistful shake of head + or a laugh that hid the truth or an excuse that the strain on her + ankles from Joel Creech's lasso had never mended. The girl was + unutterably happy, but it was possible that she would never race a + horse again.""" + deeplake_client = DeepLakeClient(collection_name="test", read_only=True) + retrieved_chunks = deeplake_client.get_chunk(query=query, top_k=top_k, with_score=with_score) + assert len(retrieved_chunks) == top_k + if with_score: + assert all(isinstance(doc[0], Document) for doc in retrieved_chunks) + assert all(isinstance(doc[1], float) for doc in retrieved_chunks) + else: + assert all(isinstance(doc, Document) for doc in retrieved_chunks) + del (deeplake_client) + + +@pytest.mark.parametrize("top_k,with_score", deeplake_get_chunk_params) +def test_deeplake_aget_chunk(top_k, with_score): + query = """Slone and Lucy never rode down so far as the stately monuments, though + these held memories as hauntingly sweet as others were poignantly + bitter. Lucy never rode the King again. But Slone rode him, learned to + love him. And Lucy did not race any more. When Slone tried to stir in + her the old spirit all the response he got was a wistful shake of head + or a laugh that hid the truth or an excuse that the strain on her + ankles from Joel Creech's lasso had never mended. The girl was + unutterably happy, but it was possible that she would never race a + horse again.""" + deeplake_client = DeepLakeClient(collection_name="test", read_only=True) + loop = asyncio.get_event_loop() + retrieved_chunks = loop.run_until_complete( + deeplake_client.aget_chunk(query=query, top_k=top_k, with_score=with_score) + ) + assert len(retrieved_chunks) == top_k + if with_score: + assert all(isinstance(doc[0], Document) for doc in retrieved_chunks) + assert all(isinstance(doc[1], float) for doc in retrieved_chunks) + else: + assert all(isinstance(doc, Document) for doc in retrieved_chunks) + del (deeplake_client) From 428c634e73c7134b4507f35d8df94fef6477902e Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Fri, 22 Mar 2024 18:02:54 -0400 Subject: [PATCH 35/53] quantization --- src/config.ini | 5 ++- src/grag/quantize/quantize.py | 76 +++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) create mode 100644 src/grag/quantize/quantize.py diff --git a/src/config.ini b/src/config.ini index 452ac04..74ab6c4 100644 --- a/src/config.ini +++ b/src/config.ini @@ -51,4 +51,7 @@ table_as_html : True data_path : ${root:root_path}/data [root] -root_path : /home/ubuntu/volume_2k/Capstone_5 \ No newline at end of file +root_path : /home/ubuntu/volume_2k/Capstone_5 + +[quantize] +llama_cpp_path : ${root:root_path} \ No newline at end of file diff --git a/src/grag/quantize/quantize.py b/src/grag/quantize/quantize.py new file mode 100644 index 0000000..2728e13 --- /dev/null +++ b/src/grag/quantize/quantize.py @@ -0,0 +1,76 @@ +import os +import subprocess + +from grag.components.utils import get_config +from huggingface_hub import snapshot_download + +original_dir = os.getcwd() +config = get_config() +root_path = config['quantize']['llama_cpp_path'] + + +def get_llamacpp_repo(): + if os.path.exists(f"{root_path}/llama.cpp"): + subprocess.run([f"cd {root_path}/llama.cpp && git pull"], check=True, shell=True) + else: + subprocess.run( + [f"cd {root_path} && git clone https://github.com/ggerganov/llama.cpp.git"], + check=True, shell=True) + + +def building_llama(): + os.chdir(f"{root_path}/llama.cpp/") + try: + subprocess.run(['which', 'make'], check=True, stdout=subprocess.DEVNULL) + subprocess.run(['make', 'LLAMA_CUBLAS=1'], check=True) + print('Llama.cpp build successfull.') + except subprocess.CalledProcessError: + try: + subprocess.run(['which', 'cmake'], check=True, stdout=subprocess.DEVNULL) + subprocess.run(['mkdir', 'build'], check=True) + subprocess.run( + ['cd', 'build', '&&', 'cmake', '..', '-DLLAMA_CUBLAS=ON', '&&', 'cmake', '--build', '.', '--config', + 'Release'], shell=True, check=True) + print('Llama.cpp build successfull.') + except subprocess.CalledProcessError: + print("Unable to build, cannot find make or cmake.") + os.chdir(original_dir) + + +def fetch_model_repo(): + response = input("Do you want us to download the model? (yes/no) [Enter for yes]: ").strip().lower() + if response == "no": + print("Please copy the model folder to 'llama.cpp/models/' folder.") + elif response == "yes" or response == "": + repo_id = input('Please enter the repo_id for the model (you can check on https://huggingface.co/models): ') + local_dir = f"{root_path}/llama.cpp/model/{repo_id.split('/')[1]}" + os.mkdir(local_dir) + snapshot_download(repo_id=repo_id, local_dir=local_dir, + local_dir_use_symlinks=False) + print(f"Model downloaded in {local_dir}") + + +def quantize_model(quantization): + os.chdir(f"{root_path}/llama.cpp/") + subprocess.run(["python3", "convert.py", f"models/{model_dir_path}/"], check=True) + + model_file = f"models/{model_dir_path}/ggml-model-f16.gguf" + quantized_model_file = f"models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" + subprocess.run(["llm_quantize", model_file, quantized_model_file, quantization], check=True) + print(f"Quantized model present at {root_path}/llama.cpp/{quantized_model_file}") + os.chdir(original_dir) + + +if __name__ == "__main__": + get_llamacpp_repo() + building_llama() + fetch_model_repo() + + quantization = input("Enter quantization: ") + quantize_model(quantization) + # if len(sys.argv) < 2 or len(sys.argv) > 3: + # print("Usage: python script.py []") + # sys.exit(1) + # model_dir_path = sys.argv[1] + # quantization = sys.argv[2] if len(sys.argv) == 3 else None + # execute_commands(model_dir_path, quantization) From 698efbd1e0c77a2c7e78be4f6080d96b8a0cd912 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Fri, 22 Mar 2024 18:03:14 -0400 Subject: [PATCH 36/53] Update to remove ruff errors --- pyproject.toml | 4 ++ src/config.ini | 10 ++++- src/grag/components/embedding.py | 8 ++++ src/grag/components/llm.py | 30 +++++++------- src/grag/components/multivec_retriever.py | 38 ++++++++++------- src/grag/components/parse_pdf.py | 36 +++++++++------- src/grag/components/prompt.py | 50 ++++++++++++++++++++++- src/grag/components/text_splitter.py | 22 ++++++++-- src/grag/components/utils.py | 17 ++++++-- 9 files changed, 163 insertions(+), 52 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 897ab02..f7c2d4f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -101,9 +101,13 @@ exclude_lines = [ [tool.ruff] line-length = 88 indent-width = 4 +extend-exclude = ["tests", "others"] [tool.ruff.lint] select = ["E4", "E7", "E9", "F", "I", "D"] +ignore = ["D104"] +exclude = ["__about__.py"] + [tool.ruff.format] quote-style = "double" diff --git a/src/config.ini b/src/config.ini index 452ac04..54990bf 100644 --- a/src/config.ini +++ b/src/config.ini @@ -25,6 +25,14 @@ embedding_model : hkunlp/instructor-xl store_path : ${data:data_path}/vectordb allow_reset : True +[deeplake] +collection_name : arxiv +# embedding_type : sentence-transformers +# embedding_model : "all-mpnet-base-v2" +embedding_type : instructor-embedding +embedding_model : hkunlp/instructor-xl +store_path : ${data:data_path}/vectordb + [text_splitter] chunk_size : 5000 chunk_overlap : 400 @@ -51,4 +59,4 @@ table_as_html : True data_path : ${root:root_path}/data [root] -root_path : /home/ubuntu/volume_2k/Capstone_5 \ No newline at end of file +root_path : /home/ubuntu/CapStone/Capstone_5 diff --git a/src/grag/components/embedding.py b/src/grag/components/embedding.py index 7a9d249..73202e0 100644 --- a/src/grag/components/embedding.py +++ b/src/grag/components/embedding.py @@ -1,3 +1,9 @@ +"""Class for embedding. + +This module provies: +- Embedding +""" + from langchain_community.embeddings import HuggingFaceInstructEmbeddings from langchain_community.embeddings.sentence_transformer import ( SentenceTransformerEmbeddings, @@ -6,6 +12,7 @@ class Embedding: """A class for vector embeddings. + Supports: huggingface sentence transformers -> model_type = 'sentence-transformers' huggingface instructor embeddings -> model_type = 'instructor-embedding' @@ -17,6 +24,7 @@ class Embedding: """ def __init__(self, embedding_type: str, embedding_model: str): + """Initialize the embedding with embedding_type and embedding_model.""" self.embedding_type = embedding_type self.embedding_model = embedding_model match self.embedding_type: diff --git a/src/grag/components/llm.py b/src/grag/components/llm.py index 20db968..23d2a26 100644 --- a/src/grag/components/llm.py +++ b/src/grag/components/llm.py @@ -1,3 +1,4 @@ +"""Class for LLM.""" import os from pathlib import Path @@ -36,20 +37,21 @@ class LLM: """ def __init__( - self, - model_name=llm_conf["model_name"], - device_map=llm_conf["device_map"], - task=llm_conf["task"], - max_new_tokens=llm_conf["max_new_tokens"], - temperature=llm_conf["temperature"], - n_batch=llm_conf["n_batch_gpu_cpp"], - n_ctx=llm_conf["n_ctx_cpp"], - n_gpu_layers=llm_conf["n_gpu_layers_cpp"], - std_out=llm_conf["std_out"], - base_dir=llm_conf["base_dir"], - quantization=llm_conf["quantization"], - pipeline=llm_conf["pipeline"], + self, + model_name=llm_conf["model_name"], + device_map=llm_conf["device_map"], + task=llm_conf["task"], + max_new_tokens=llm_conf["max_new_tokens"], + temperature=llm_conf["temperature"], + n_batch=llm_conf["n_batch_gpu_cpp"], + n_ctx=llm_conf["n_ctx_cpp"], + n_gpu_layers=llm_conf["n_gpu_layers_cpp"], + std_out=llm_conf["std_out"], + base_dir=llm_conf["base_dir"], + quantization=llm_conf["quantization"], + pipeline=llm_conf["pipeline"], ): + """Initialize the LLM class using the given parameters.""" self.base_dir = Path(base_dir) self._model_name = model_name self.quantization = quantization @@ -160,7 +162,7 @@ def llama_cpp(self): return llm def load_model( - self, model_name=None, pipeline=None, quantization=None, is_local=None + self, model_name=None, pipeline=None, quantization=None, is_local=None ): """Loads the model based on the specified pipeline and model name. diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index 18ed752..253cb31 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -1,3 +1,8 @@ +"""Class for retriever. + +This module provides: +- Retriever +""" import asyncio import uuid from typing import List @@ -13,9 +18,11 @@ class Retriever: - """A class for multi vector retriever, it connects to a vector database and a local file store. - It is used to return most similar chunks from a vector store but has the additional funcationality - to return a linked document, chunk, etc. + """A class for multi vector retriever. + + It connects to a vector database and a local file store. + It is used to return most similar chunks from a vector store but has the additional functionality to return a + linked document, chunk, etc. Attributes: store_path: Path to the local file store @@ -30,13 +37,15 @@ class Retriever: """ def __init__( - self, - store_path: str = multivec_retriever_conf["store_path"], - id_key: str = multivec_retriever_conf["id_key"], - namespace: str = multivec_retriever_conf["namespace"], - top_k=1, + self, + store_path: str = multivec_retriever_conf["store_path"], + id_key: str = multivec_retriever_conf["id_key"], + namespace: str = multivec_retriever_conf["namespace"], + top_k=1, ): - """Args: + """Initialize the Retriever. + + Args: store_path: Path to the local file store, defaults to argument from config file id_key: A key prefix for identifying documents, defaults to argument from config file namespace: A namespace for producing unique id, defaults to argument from congig file @@ -58,6 +67,7 @@ def __init__( def id_gen(self, doc: Document) -> str: """Takes a document and returns a unique id (uuid5) using the namespace and document source. + This ensures that a single document always gets the same unique id. Args: @@ -81,7 +91,9 @@ def gen_doc_ids(self, docs: List[Document]) -> List[str]: return [self.id_gen(doc) for doc in docs] def split_docs(self, docs: List[Document]) -> List[Document]: - """Takes a list of documents and splits them into smaller chunks using TextSplitter from compoenents.text_splitter + """Takes a list of documents and splits them into smaller chunks. + + Using TextSplitter from components.text_splitter Also adds the unique parent document id into metadata Args: @@ -101,8 +113,7 @@ def split_docs(self, docs: List[Document]) -> List[Document]: return chunks def add_docs(self, docs: List[Document]): - """Takes a list of documents, splits them using the split_docs method and then adds them into the vector database - and adds the parent document into the file store. + """Adds given documents into the vector database also adds the parent document into the file store. Args: docs: List of langchain_core.documents.Document @@ -117,8 +128,7 @@ def add_docs(self, docs: List[Document]): self.retriever.docstore.mset(list(zip(doc_ids, docs))) async def aadd_docs(self, docs: List[Document]): - """Takes a list of documents, splits them using the split_docs method and then adds them into the vector database - and adds the parent document into the file store. + """Adds given documents into the vector database also adds the parent document into the file store. Args: docs: List of langchain_core.documents.Document diff --git a/src/grag/components/parse_pdf.py b/src/grag/components/parse_pdf.py index d918c93..9ab2205 100644 --- a/src/grag/components/parse_pdf.py +++ b/src/grag/components/parse_pdf.py @@ -1,3 +1,8 @@ +"""Classes for parsing files. + +This module provides: +- ParsePDF +""" from langchain_core.documents import Document from unstructured.partition.pdf import partition_pdf @@ -22,17 +27,17 @@ class ParsePDF: """ def __init__( - self, - single_text_out=parser_conf["single_text_out"], - strategy=parser_conf["strategy"], - infer_table_structure=parser_conf["infer_table_structure"], - extract_images=parser_conf["extract_images"], - image_output_dir=parser_conf["image_output_dir"], - add_captions_to_text=parser_conf["add_captions_to_text"], - add_captions_to_blocks=parser_conf["add_captions_to_blocks"], - table_as_html=parser_conf["table_as_html"], + self, + single_text_out=parser_conf["single_text_out"], + strategy=parser_conf["strategy"], + infer_table_structure=parser_conf["infer_table_structure"], + extract_images=parser_conf["extract_images"], + image_output_dir=parser_conf["image_output_dir"], + add_captions_to_text=parser_conf["add_captions_to_text"], + add_captions_to_blocks=parser_conf["add_captions_to_blocks"], + table_as_html=parser_conf["table_as_html"], ): - # Instantialize instance variables with parameters + """Initialize instance variables with parameters.""" self.strategy = strategy if extract_images: # by default always extract Table self.extract_image_block_types = [ @@ -72,7 +77,8 @@ def partition(self, path: str): def classify(self, partitions): """Classifies the partitioned elements into Text, Tables, and Images list in a dictionary. - Add captions for each element (if available). + + Also adds captions for each element (if available). Parameters: partitions (list): The list of partitioned elements from the PDF document. @@ -88,7 +94,7 @@ def classify(self, partitions): if element.category == "Table": if self.add_captions_to_blocks and i + 1 < len(partitions): if ( - partitions[i + 1].category == "FigureCaption" + partitions[i + 1].category == "FigureCaption" ): # check for caption caption_element = partitions[i + 1] else: @@ -99,7 +105,7 @@ def classify(self, partitions): elif element.category == "Image": if self.add_captions_to_blocks and i + 1 < len(partitions): if ( - partitions[i + 1].category == "FigureCaption" + partitions[i + 1].category == "FigureCaption" ): # check for caption caption_element = partitions[i + 1] else: @@ -117,6 +123,8 @@ def classify(self, partitions): return classified_elements def text_concat(self, elements) -> str: + """Context aware concatenates all elements into a single string.""" + full_text = "" for current_element, next_element in zip(elements, elements[1:]): curr_type = current_element.category next_type = next_element.category @@ -185,7 +193,7 @@ def process_tables(self, elements): if caption_element: if ( - self.add_caption_first + self.add_caption_first ): # if there is a caption, add that before the element content = "\n\n".join([str(caption_element), table_data]) else: diff --git a/src/grag/components/prompt.py b/src/grag/components/prompt.py index ecefa71..86bf8df 100644 --- a/src/grag/components/prompt.py +++ b/src/grag/components/prompt.py @@ -1,3 +1,9 @@ +"""Classes for prompts. + +This module provides: +- Prompt - for generic prompts +- FewShotPrompt - for few-shot prompts +""" import json from pathlib import Path from typing import Any, Dict, List, Optional, Union @@ -13,6 +19,19 @@ class Prompt(BaseModel): + """A class for generic prompts. + + Attributes: + name (str): The prompt name (Optional, defaults to "custom_prompt") + llm_type (str): The type of llm, llama2, etc (Optional, defaults to "None") + task (str): The task (Optional, defaults to QA) + source (str): The source of the prompt (Optional, defaults to "NoSource") + doc_chain (str): The doc chain for the prompt ("stuff", "refine") (Optional, defaults to "stuff") + language (str): The language of the prompt (Optional, defaults to "en") + filepath (str): The filepath of the prompt (Optional) + input_keys (List[str]): The input keys for the prompt + template (str): The template for the prompt + """ name: str = Field(default="custom_prompt") llm_type: str = Field(default="None") task: str = Field(default="QA") @@ -27,6 +46,7 @@ class Prompt(BaseModel): @field_validator("input_keys") @classmethod def validate_input_keys(cls, v) -> List[str]: + """Validate the input_keys field.""" if v is None or v == []: raise ValueError("input_keys cannot be empty") return v @@ -34,6 +54,7 @@ def validate_input_keys(cls, v) -> List[str]: @field_validator("doc_chain") @classmethod def validate_doc_chain(cls, v: str) -> str: + """Validate the doc_chain field.""" if v not in SUPPORTED_DOC_CHAINS: raise ValueError( f"The provided doc_chain, {v} is not supported, supported doc_chains are {SUPPORTED_DOC_CHAINS}" @@ -43,6 +64,7 @@ def validate_doc_chain(cls, v: str) -> str: @field_validator("task") @classmethod def validate_task(cls, v: str) -> str: + """Validate the task field.""" if v not in SUPPORTED_TASKS: raise ValueError( f"The provided task, {v} is not supported, supported tasks are {SUPPORTED_TASKS}" @@ -53,14 +75,16 @@ def validate_task(cls, v: str) -> str: # def load_template(self): # self.prompt = ChatPromptTemplate.from_template(self.template) def __init__(self, **kwargs): + """Initialize the prompt.""" super().__init__(**kwargs) self.prompt = PromptTemplate( input_variables=self.input_keys, template=self.template ) def save( - self, filepath: Union[Path, str, None], overwrite=False + self, filepath: Union[Path, str, None], overwrite=False ) -> Union[None, ValueError]: + """Saves the prompt class into a json file.""" dump = self.model_dump_json(indent=2, exclude_defaults=True, exclude_none=True) if filepath is None: filepath = f"{self.name}.json" @@ -74,17 +98,36 @@ def save( @classmethod def load(cls, filepath: Union[Path, str]): + """Loads a json file and returns a Prompt class.""" with open(f"{filepath}", "r") as f: prompt_json = json.load(f) _prompt = cls(**prompt_json) _prompt.filepath = str(filepath) return _prompt - def format(self, **kwargs): + def format(self, **kwargs) -> str: + """Formats the prompt with provided keys and returns a string.""" return self.prompt.format(**kwargs) class FewShotPrompt(Prompt): + """A class for generic prompts. + + Attributes: + name (str): The prompt name (Optional, defaults to "custom_prompt") (Parent Class) + llm_type (str): The type of llm, llama2, etc (Optional, defaults to "None") (Parent Class) + task (str): The task (Optional, defaults to QA) (Parent Class) + source (str): The source of the prompt (Optional, defaults to "NoSource") (Parent Class) + doc_chain (str): The doc chain for the prompt ("stuff", "refine") (Optional, defaults to "stuff") (Parent Class) + language (str): The language of the prompt (Optional, defaults to "en") (Parent Class) + filepath (str): The filepath of the prompt (Optional) (Parent Class) + input_keys (List[str]): The input keys for the prompt (Parent Class) + input_keys (List[str]): The output keys for the prompt + prefix (str): The template prefix for the prompt + suffix (str): The template suffix for the prompt + example_template (str): The template for formatting the examples + examples (List[Dict[str, Any]]): The list of examples, each example is a dictionary with respective keys + """ output_keys: List[str] examples: List[Dict[str, Any]] prefix: str @@ -95,6 +138,7 @@ class FewShotPrompt(Prompt): ) def __init__(self, **kwargs): + """Initialize the prompt.""" super().__init__(**kwargs) eg_formatter = PromptTemplate( input_vars=self.input_keys + self.output_keys, @@ -111,6 +155,7 @@ def __init__(self, **kwargs): @field_validator("output_keys") @classmethod def validate_output_keys(cls, v) -> List[str]: + """Validate the output_keys field.""" if v is None or v == []: raise ValueError("output_keys cannot be empty") return v @@ -118,6 +163,7 @@ def validate_output_keys(cls, v) -> List[str]: @field_validator("examples") @classmethod def validate_examples(cls, v) -> List[Dict[str, Any]]: + """Validate the examples field.""" if v is None or v == []: raise ValueError("examples cannot be empty") for eg in v: diff --git a/src/grag/components/text_splitter.py b/src/grag/components/text_splitter.py index cff3c7c..a0ecfd9 100644 --- a/src/grag/components/text_splitter.py +++ b/src/grag/components/text_splitter.py @@ -1,3 +1,8 @@ +"""Class for splitting/chunking text. + +This module provides: +- TextSplitter +""" from langchain.text_splitter import RecursiveCharacterTextSplitter from .utils import get_config @@ -7,10 +12,21 @@ # %% class TextSplitter: - def __init__(self): + """Class for recursively chunking text, it prioritizes '/n/n then '/n' and so on. + + Attributes: + chunk_size: maximum size of chunk + chunk_overlap: chunk overlap size + """ + + def __init__(self, + chunk_size: int = text_splitter_conf["chunk_size"], + chunk_overlap: int = text_splitter_conf["chunk_overlap"]): + """Initialize TextSplitter.""" self.text_splitter = RecursiveCharacterTextSplitter( - chunk_size=int(text_splitter_conf["chunk_size"]), - chunk_overlap=int(text_splitter_conf["chunk_overlap"]), + chunk_size=int(chunk_size), + chunk_overlap=int(chunk_overlap), length_function=len, is_separator_regex=False, ) + """Initialize TextSplitter using chunk_size and chunk_overlap""" diff --git a/src/grag/components/utils.py b/src/grag/components/utils.py index cb64258..0233d32 100644 --- a/src/grag/components/utils.py +++ b/src/grag/components/utils.py @@ -1,3 +1,11 @@ +"""Utils functions. + +This module provides: +- stuff_docs: concats langchain documents into string +- load_prompt: loads json prompt to langchain prompt +- find_config_path: finds the path of the 'config.ini' file by traversing up the directory tree from the current path. +- get_config: retrieves and parses the configuration settings from the 'config.ini' file. +""" import json import os import textwrap @@ -10,7 +18,9 @@ def stuff_docs(docs: List[Document]) -> str: - """Args: + r"""Concatenates langchain documents into a string using '\n\n' seperator. + + Args: docs: List of langchain_core.documents.Document Returns: @@ -20,8 +30,7 @@ def stuff_docs(docs: List[Document]) -> str: def reformat_text_with_line_breaks(input_text, max_width=110): - """Reformat the given text to ensure each line does not exceed a specific width, - preserving existing line breaks. + """Reformat the given text to ensure each line does not exceed a specific width, preserving existing line breaks. Args: input_text (str): The text to be reformatted. @@ -62,7 +71,7 @@ def display_llm_output_and_sources(response_from_llm): def load_prompt(json_file: str | os.PathLike, return_input_vars=False): - """Loads a prompt template from json file and returns a langchain ChatPromptTemplate + """Loads a prompt template from json file and returns a langchain ChatPromptTemplate. Args: json_file: path to the prompt template json file. From acd4ba282f6c0dc821b80a4bc23a1a70849349e6 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Fri, 22 Mar 2024 18:20:14 -0400 Subject: [PATCH 37/53] Ruff bugs --- src/grag/rag/basic_rag.py | 44 ++++++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 8 deletions(-) diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index a99ecdd..05a7520 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -1,3 +1,8 @@ +"""Class for Basic RAG. + +This module provides: +- BasicRAG +""" import json from typing import List, Union @@ -13,15 +18,27 @@ class BasicRAG: + """Class for Basis RAG. + + Attributes: + model_name (str): Name of the llm model + doc_chain (str): Name of the document chain, ("stuff", "refine"), defaults to "stuff" + task (str): Name of task, defaults to "QA" + llm_kwargs (dict): Keyword arguments for LLM class + retriever_kwargs (dict): Keyword arguments for Retriever class + custom_prompt (Prompt): Prompt, defaults to None + """ + def __init__( - self, - model_name=None, - doc_chain="stuff", - task="QA", - llm_kwargs=None, - retriever_kwargs=None, - custom_prompt: Union[Prompt, FewShotPrompt, None] = None, + self, + model_name=None, + doc_chain="stuff", + task="QA", + llm_kwargs=None, + retriever_kwargs=None, + custom_prompt: Union[Prompt, FewShotPrompt, List[Prompt, FewShotPrompt], None] = None, ): + """Initialize BasicRAG.""" if retriever_kwargs is None: self.retriever = Retriever() else: @@ -54,6 +71,7 @@ def __init__( @property def model_name(self): + """Return the name of the model.""" return self._model_name @model_name.setter @@ -67,6 +85,7 @@ def model_name(self, value): @property def doc_chain(self): + """Returns the doc_chain.""" return self._doc_chain @doc_chain.setter @@ -86,6 +105,7 @@ def doc_chain(self, value): @property def task(self): + """Returns the task.""" return self._task @task.setter @@ -99,6 +119,7 @@ def task(self, value): self.prompt_matcher() def prompt_matcher(self): + """Matches relvant prompt using model, task and doc_chain.""" matcher_path = self.prompt_path.joinpath("matcher.json") with open(f"{matcher_path}", "r") as f: matcher_dict = json.load(f) @@ -122,7 +143,9 @@ def prompt_matcher(self): @staticmethod def stuff_docs(docs: List[Document]) -> str: - """Args: + r"""Concatenates docs into a string seperated by '\n\n'. + + Args: docs: List of langchain_core.documents.Document Returns: @@ -132,6 +155,8 @@ def stuff_docs(docs: List[Document]) -> str: @staticmethod def output_parser(call_func): + """Decorator to format llm output.""" + def output_parser_wrapper(*args, **kwargs): response, sources = call_func(*args, **kwargs) if conf["llm"]["std_out"] == "False": @@ -146,6 +171,7 @@ def output_parser_wrapper(*args, **kwargs): @output_parser def stuff_call(self, query: str): + """Call function for stuff chain.""" retrieved_docs = self.retriever.get_chunk(query) context = self.stuff_docs(retrieved_docs) prompt = self.main_prompt.format(context=context, question=query) @@ -155,6 +181,7 @@ def stuff_call(self, query: str): @output_parser def refine_call(self, query: str): + """Call function for refine chain.""" retrieved_docs = self.retriever.get_chunk(query) sources = [doc.metadata["source"] for doc in retrieved_docs] responses = [] @@ -176,6 +203,7 @@ def refine_call(self, query: str): return responses, sources def __call__(self, query: str): + """Call function for the class.""" if self.doc_chain == "stuff": return self.stuff_call(query) elif self.doc_chain == "refine": From 016011747380dbd57fb45f674447a204eda7efc1 Mon Sep 17 00:00:00 2001 From: arjbingly Date: Fri, 22 Mar 2024 22:23:27 +0000 Subject: [PATCH 38/53] style fixes by ruff --- src/grag/components/multivec_retriever.py | 18 ++++--- src/grag/components/vectordb/base.py | 13 ++--- src/grag/components/vectordb/chroma_client.py | 30 ++++++----- .../components/vectordb/deeplake_client.py | 51 ++++++++++--------- .../components/vectordb/chroma_client_test.py | 4 +- .../vectordb/deeplake_client_test.py | 12 +++-- 6 files changed, 71 insertions(+), 57 deletions(-) diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index b57a67f..98b3e6e 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -31,11 +31,11 @@ class Retriever: """ def __init__( - self, - store_path: str = multivec_retriever_conf["store_path"], - id_key: str = multivec_retriever_conf["id_key"], - namespace: str = multivec_retriever_conf["namespace"], - top_k=1, + self, + store_path: str = multivec_retriever_conf["store_path"], + id_key: str = multivec_retriever_conf["id_key"], + namespace: str = multivec_retriever_conf["namespace"], + top_k=1, ): """Args: store_path: Path to the local file store, defaults to argument from config file @@ -145,7 +145,7 @@ def get_chunk(self, query: str, with_score=False, top_k=None): list of Documents """ - _top_k = top_k if top_k else self.retriever.search_kwargs['k'] + _top_k = top_k if top_k else self.retriever.search_kwargs["k"] return self.vectordb.get_chunk(query=query, top_k=_top_k, with_score=with_score) async def aget_chunk(self, query: str, with_score=False, top_k=None): @@ -160,8 +160,10 @@ async def aget_chunk(self, query: str, with_score=False, top_k=None): list of Documents """ - _top_k = top_k if top_k else self.retriever.search_kwargs['k'] - return await self.vectordb.aget_chunk(query=query, top_k=_top_k, with_score=with_score) + _top_k = top_k if top_k else self.retriever.search_kwargs["k"] + return await self.vectordb.aget_chunk( + query=query, top_k=_top_k, with_score=with_score + ) def get_doc(self, query: str): """Returns the parent document of the most (cosine) similar chunk from the vector database. diff --git a/src/grag/components/vectordb/base.py b/src/grag/components/vectordb/base.py index ab63fcb..c474232 100644 --- a/src/grag/components/vectordb/base.py +++ b/src/grag/components/vectordb/base.py @@ -6,7 +6,6 @@ class VectorDB(ABC): - @abstractmethod def __len__(self) -> int: """Number of chunks in the vector database.""" @@ -19,7 +18,7 @@ def delete(self) -> None: @abstractmethod def add_docs(self, docs: List[Document], verbose: bool = True) -> None: """Adds documents to the vector database. - + Args: docs: List of Documents verbose: Show progress bar @@ -43,8 +42,9 @@ async def aadd_docs(self, docs: List[Document], verbose: bool = True) -> None: ... @abstractmethod - def get_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> Union[ - List[Document], List[Tuple[Document, float]]]: + def get_chunk( + self, query: str, with_score: bool = False, top_k: int = None + ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the vector database. Args: @@ -58,8 +58,9 @@ def get_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> ... @abstractmethod - async def aget_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> Union[ - List[Document], List[Tuple[Document, float]]]: + async def aget_chunk( + self, query: str, with_score: bool = False, top_k: int = None + ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the vector database. (asynchronous) Args: diff --git a/src/grag/components/vectordb/chroma_client.py b/src/grag/components/vectordb/chroma_client.py index e97323d..ef9091f 100644 --- a/src/grag/components/vectordb/chroma_client.py +++ b/src/grag/components/vectordb/chroma_client.py @@ -37,12 +37,12 @@ class ChromaClient(VectorDB): """ def __init__( - self, - host=chroma_conf["host"], - port=chroma_conf["port"], - collection_name=chroma_conf["collection_name"], - embedding_type=chroma_conf["embedding_type"], - embedding_model=chroma_conf["embedding_model"], + self, + host=chroma_conf["host"], + port=chroma_conf["port"], + collection_name=chroma_conf["collection_name"], + embedding_type=chroma_conf["embedding_type"], + embedding_model=chroma_conf["embedding_model"], ): """Args: host: IP Address of hosted Chroma Vectorstore, defaults to argument from config file @@ -115,7 +115,7 @@ def add_docs(self, docs: List[Document], verbose=True) -> None: """ docs = self._filter_metadata(docs) for doc in ( - tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs + tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs ): _id = self.langchain_client.add_documents([doc]) @@ -132,17 +132,18 @@ async def aadd_docs(self, docs: List[Document], verbose=True) -> None: docs = self._filter_metadata(docs) if verbose: for doc in atqdm( - docs, - desc=f"Adding documents to {self.collection_name}", - total=len(docs), + docs, + desc=f"Adding documents to {self.collection_name}", + total=len(docs), ): await self.langchain_client.aadd_documents([doc]) else: for doc in docs: await self.langchain_client.aadd_documents([doc]) - def get_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> Union[ - List[Document], List[Tuple[Document, float]]]: + def get_chunk( + self, query: str, with_score: bool = False, top_k: int = None + ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the chroma database. Args: @@ -163,8 +164,9 @@ def get_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> query=query, k=top_k if top_k else 1 ) - async def aget_chunk(self, query: str, with_score=False, top_k=None) -> Union[ - List[Document], List[Tuple[Document, float]]]: + async def aget_chunk( + self, query: str, with_score=False, top_k=None + ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most (cosine) similar chunks from the vector database, asynchronously. Args: diff --git a/src/grag/components/vectordb/deeplake_client.py b/src/grag/components/vectordb/deeplake_client.py index 28fc606..3a389c3 100644 --- a/src/grag/components/vectordb/deeplake_client.py +++ b/src/grag/components/vectordb/deeplake_client.py @@ -14,7 +14,7 @@ class DeepLakeClient(VectorDB): """A class for connecting to a DeepLake Vectorstore - + Attributes: store_path : str, Path The path to store the DeepLake vectorstore. @@ -32,13 +32,14 @@ class DeepLakeClient(VectorDB): LangChain wrapper for DeepLake API """ - def __init__(self, - collection_name: str = deeplake_conf["collection_name"], - store_path: Union[str, Path] = deeplake_conf["store_path"], - embedding_type: str = deeplake_conf["embedding_type"], - embedding_model: str = deeplake_conf["embedding_model"], - read_only: bool = False - ): + def __init__( + self, + collection_name: str = deeplake_conf["collection_name"], + store_path: Union[str, Path] = deeplake_conf["store_path"], + embedding_type: str = deeplake_conf["embedding_type"], + embedding_model: str = deeplake_conf["embedding_model"], + read_only: bool = False, + ): self.store_path = Path(store_path) self.collection_name = collection_name self.read_only = read_only @@ -50,9 +51,11 @@ def __init__(self, ).embedding_function # self.client = VectorStore(path=self.store_path / self.collection_name) - self.langchain_client = DeepLake(dataset_path=str(self.store_path / self.collection_name), - embedding=self.embedding_function, - read_only=self.read_only) + self.langchain_client = DeepLake( + dataset_path=str(self.store_path / self.collection_name), + embedding=self.embedding_function, + read_only=self.read_only, + ) self.client = self.langchain_client.vectorstore self.allowed_metadata_types = (str, int, float, bool) @@ -64,44 +67,45 @@ def delete(self) -> None: def add_docs(self, docs: List[Document], verbose=True) -> None: """Adds documents to deeplake vectorstore - + Args: docs: List of Documents verbose: Show progress bar - + Returns: None """ docs = self._filter_metadata(docs) for doc in ( - tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs + tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs ): _id = self.langchain_client.add_documents([doc]) async def aadd_docs(self, docs: List[Document], verbose=True) -> None: """Asynchronously adds documents to chroma vectorstore - + Args: docs: List of Documents verbose: Show progress bar - + Returns: None """ docs = self._filter_metadata(docs) if verbose: for doc in atqdm( - docs, - desc=f"Adding documents to {self.collection_name}", - total=len(docs), + docs, + desc=f"Adding documents to {self.collection_name}", + total=len(docs), ): await self.langchain_client.aadd_documents([doc]) else: for doc in docs: await self.langchain_client.aadd_documents([doc]) - def get_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> Union[ - List[Document], List[Tuple[Document, float]]]: + def get_chunk( + self, query: str, with_score: bool = False, top_k: int = None + ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the deeplake database. Args: @@ -122,8 +126,9 @@ def get_chunk(self, query: str, with_score: bool = False, top_k: int = None) -> query=query, k=top_k if top_k else 1 ) - async def aget_chunk(self, query: str, with_score=False, top_k=None) -> Union[ - List[Document], List[Tuple[Document, float]]]: + async def aget_chunk( + self, query: str, with_score=False, top_k=None + ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the deeplake database, asynchronously. Args: diff --git a/src/tests/components/vectordb/chroma_client_test.py b/src/tests/components/vectordb/chroma_client_test.py index ecffa22..c491dfd 100644 --- a/src/tests/components/vectordb/chroma_client_test.py +++ b/src/tests/components/vectordb/chroma_client_test.py @@ -113,7 +113,9 @@ def test_chroma_get_chunk(top_k, with_score): unutterably happy, but it was possible that she would never race a horse again.""" chroma_client = ChromaClient(collection_name="test") - retrieved_chunks = chroma_client.get_chunk(query=query, top_k=top_k, with_score=with_score) + retrieved_chunks = chroma_client.get_chunk( + query=query, top_k=top_k, with_score=with_score + ) assert len(retrieved_chunks) == top_k if with_score: assert all(isinstance(doc[0], Document) for doc in retrieved_chunks) diff --git a/src/tests/components/vectordb/deeplake_client_test.py b/src/tests/components/vectordb/deeplake_client_test.py index 921bd18..cea5e61 100644 --- a/src/tests/components/vectordb/deeplake_client_test.py +++ b/src/tests/components/vectordb/deeplake_client_test.py @@ -46,7 +46,7 @@ def test_deeplake_add_docs(): docs = [Document(page_content=doc) for doc in docs] deeplake_client.add_docs(docs) assert len(deeplake_client) == len(docs) - del (deeplake_client) + del deeplake_client def test_chroma_aadd_docs(): @@ -91,7 +91,7 @@ def test_chroma_aadd_docs(): loop = asyncio.get_event_loop() loop.run_until_complete(deeplake_client.aadd_docs(docs)) assert len(deeplake_client) == len(docs) - del (deeplake_client) + del deeplake_client deeplake_get_chunk_params = [(1, False), (1, True), (2, False), (2, True)] @@ -109,14 +109,16 @@ def test_deeplake_get_chunk(top_k, with_score): unutterably happy, but it was possible that she would never race a horse again.""" deeplake_client = DeepLakeClient(collection_name="test", read_only=True) - retrieved_chunks = deeplake_client.get_chunk(query=query, top_k=top_k, with_score=with_score) + retrieved_chunks = deeplake_client.get_chunk( + query=query, top_k=top_k, with_score=with_score + ) assert len(retrieved_chunks) == top_k if with_score: assert all(isinstance(doc[0], Document) for doc in retrieved_chunks) assert all(isinstance(doc[1], float) for doc in retrieved_chunks) else: assert all(isinstance(doc, Document) for doc in retrieved_chunks) - del (deeplake_client) + del deeplake_client @pytest.mark.parametrize("top_k,with_score", deeplake_get_chunk_params) @@ -141,4 +143,4 @@ def test_deeplake_aget_chunk(top_k, with_score): assert all(isinstance(doc[1], float) for doc in retrieved_chunks) else: assert all(isinstance(doc, Document) for doc in retrieved_chunks) - del (deeplake_client) + del deeplake_client From aec73771f90cdeeaa9d4fe128fc04fb5befb786e Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Fri, 22 Mar 2024 22:23:39 +0000 Subject: [PATCH 39/53] style fixes by ruff --- src/grag/quantize/quantize.py | 64 +++++++++++++++++++++++++---------- 1 file changed, 47 insertions(+), 17 deletions(-) diff --git a/src/grag/quantize/quantize.py b/src/grag/quantize/quantize.py index 2728e13..773e987 100644 --- a/src/grag/quantize/quantize.py +++ b/src/grag/quantize/quantize.py @@ -6,47 +6,73 @@ original_dir = os.getcwd() config = get_config() -root_path = config['quantize']['llama_cpp_path'] +root_path = config["quantize"]["llama_cpp_path"] def get_llamacpp_repo(): if os.path.exists(f"{root_path}/llama.cpp"): - subprocess.run([f"cd {root_path}/llama.cpp && git pull"], check=True, shell=True) + subprocess.run( + [f"cd {root_path}/llama.cpp && git pull"], check=True, shell=True + ) else: subprocess.run( [f"cd {root_path} && git clone https://github.com/ggerganov/llama.cpp.git"], - check=True, shell=True) + check=True, + shell=True, + ) def building_llama(): os.chdir(f"{root_path}/llama.cpp/") try: - subprocess.run(['which', 'make'], check=True, stdout=subprocess.DEVNULL) - subprocess.run(['make', 'LLAMA_CUBLAS=1'], check=True) - print('Llama.cpp build successfull.') + subprocess.run(["which", "make"], check=True, stdout=subprocess.DEVNULL) + subprocess.run(["make", "LLAMA_CUBLAS=1"], check=True) + print("Llama.cpp build successfull.") except subprocess.CalledProcessError: try: - subprocess.run(['which', 'cmake'], check=True, stdout=subprocess.DEVNULL) - subprocess.run(['mkdir', 'build'], check=True) + subprocess.run(["which", "cmake"], check=True, stdout=subprocess.DEVNULL) + subprocess.run(["mkdir", "build"], check=True) subprocess.run( - ['cd', 'build', '&&', 'cmake', '..', '-DLLAMA_CUBLAS=ON', '&&', 'cmake', '--build', '.', '--config', - 'Release'], shell=True, check=True) - print('Llama.cpp build successfull.') + [ + "cd", + "build", + "&&", + "cmake", + "..", + "-DLLAMA_CUBLAS=ON", + "&&", + "cmake", + "--build", + ".", + "--config", + "Release", + ], + shell=True, + check=True, + ) + print("Llama.cpp build successfull.") except subprocess.CalledProcessError: print("Unable to build, cannot find make or cmake.") os.chdir(original_dir) def fetch_model_repo(): - response = input("Do you want us to download the model? (yes/no) [Enter for yes]: ").strip().lower() + response = ( + input("Do you want us to download the model? (yes/no) [Enter for yes]: ") + .strip() + .lower() + ) if response == "no": print("Please copy the model folder to 'llama.cpp/models/' folder.") elif response == "yes" or response == "": - repo_id = input('Please enter the repo_id for the model (you can check on https://huggingface.co/models): ') + repo_id = input( + "Please enter the repo_id for the model (you can check on https://huggingface.co/models): " + ) local_dir = f"{root_path}/llama.cpp/model/{repo_id.split('/')[1]}" os.mkdir(local_dir) - snapshot_download(repo_id=repo_id, local_dir=local_dir, - local_dir_use_symlinks=False) + snapshot_download( + repo_id=repo_id, local_dir=local_dir, local_dir_use_symlinks=False + ) print(f"Model downloaded in {local_dir}") @@ -55,8 +81,12 @@ def quantize_model(quantization): subprocess.run(["python3", "convert.py", f"models/{model_dir_path}/"], check=True) model_file = f"models/{model_dir_path}/ggml-model-f16.gguf" - quantized_model_file = f"models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" - subprocess.run(["llm_quantize", model_file, quantized_model_file, quantization], check=True) + quantized_model_file = ( + f"models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" + ) + subprocess.run( + ["llm_quantize", model_file, quantized_model_file, quantization], check=True + ) print(f"Quantized model present at {root_path}/llama.cpp/{quantized_model_file}") os.chdir(original_dir) From 2df28d1c7c2cf0b640faddcd796f8888607fc182 Mon Sep 17 00:00:00 2001 From: arjbingly Date: Fri, 22 Mar 2024 22:23:56 +0000 Subject: [PATCH 40/53] style fixes by ruff --- src/grag/components/embedding.py | 2 +- src/grag/components/llm.py | 29 ++++++++++++----------- src/grag/components/multivec_retriever.py | 21 ++++++++-------- src/grag/components/parse_pdf.py | 27 +++++++++++---------- src/grag/components/prompt.py | 7 ++++-- src/grag/components/text_splitter.py | 11 +++++---- src/grag/components/utils.py | 3 ++- src/grag/rag/basic_rag.py | 21 +++++++++------- 8 files changed, 67 insertions(+), 54 deletions(-) diff --git a/src/grag/components/embedding.py b/src/grag/components/embedding.py index 73202e0..eab107f 100644 --- a/src/grag/components/embedding.py +++ b/src/grag/components/embedding.py @@ -12,7 +12,7 @@ class Embedding: """A class for vector embeddings. - + Supports: huggingface sentence transformers -> model_type = 'sentence-transformers' huggingface instructor embeddings -> model_type = 'instructor-embedding' diff --git a/src/grag/components/llm.py b/src/grag/components/llm.py index 23d2a26..6e7296c 100644 --- a/src/grag/components/llm.py +++ b/src/grag/components/llm.py @@ -1,4 +1,5 @@ """Class for LLM.""" + import os from pathlib import Path @@ -37,19 +38,19 @@ class LLM: """ def __init__( - self, - model_name=llm_conf["model_name"], - device_map=llm_conf["device_map"], - task=llm_conf["task"], - max_new_tokens=llm_conf["max_new_tokens"], - temperature=llm_conf["temperature"], - n_batch=llm_conf["n_batch_gpu_cpp"], - n_ctx=llm_conf["n_ctx_cpp"], - n_gpu_layers=llm_conf["n_gpu_layers_cpp"], - std_out=llm_conf["std_out"], - base_dir=llm_conf["base_dir"], - quantization=llm_conf["quantization"], - pipeline=llm_conf["pipeline"], + self, + model_name=llm_conf["model_name"], + device_map=llm_conf["device_map"], + task=llm_conf["task"], + max_new_tokens=llm_conf["max_new_tokens"], + temperature=llm_conf["temperature"], + n_batch=llm_conf["n_batch_gpu_cpp"], + n_ctx=llm_conf["n_ctx_cpp"], + n_gpu_layers=llm_conf["n_gpu_layers_cpp"], + std_out=llm_conf["std_out"], + base_dir=llm_conf["base_dir"], + quantization=llm_conf["quantization"], + pipeline=llm_conf["pipeline"], ): """Initialize the LLM class using the given parameters.""" self.base_dir = Path(base_dir) @@ -162,7 +163,7 @@ def llama_cpp(self): return llm def load_model( - self, model_name=None, pipeline=None, quantization=None, is_local=None + self, model_name=None, pipeline=None, quantization=None, is_local=None ): """Loads the model based on the specified pipeline and model name. diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index 253cb31..97684dd 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -3,6 +3,7 @@ This module provides: - Retriever """ + import asyncio import uuid from typing import List @@ -19,9 +20,9 @@ class Retriever: """A class for multi vector retriever. - + It connects to a vector database and a local file store. - It is used to return most similar chunks from a vector store but has the additional functionality to return a + It is used to return most similar chunks from a vector store but has the additional functionality to return a linked document, chunk, etc. Attributes: @@ -37,14 +38,14 @@ class Retriever: """ def __init__( - self, - store_path: str = multivec_retriever_conf["store_path"], - id_key: str = multivec_retriever_conf["id_key"], - namespace: str = multivec_retriever_conf["namespace"], - top_k=1, + self, + store_path: str = multivec_retriever_conf["store_path"], + id_key: str = multivec_retriever_conf["id_key"], + namespace: str = multivec_retriever_conf["namespace"], + top_k=1, ): """Initialize the Retriever. - + Args: store_path: Path to the local file store, defaults to argument from config file id_key: A key prefix for identifying documents, defaults to argument from config file @@ -67,7 +68,7 @@ def __init__( def id_gen(self, doc: Document) -> str: """Takes a document and returns a unique id (uuid5) using the namespace and document source. - + This ensures that a single document always gets the same unique id. Args: @@ -92,7 +93,7 @@ def gen_doc_ids(self, docs: List[Document]) -> List[str]: def split_docs(self, docs: List[Document]) -> List[Document]: """Takes a list of documents and splits them into smaller chunks. - + Using TextSplitter from components.text_splitter Also adds the unique parent document id into metadata diff --git a/src/grag/components/parse_pdf.py b/src/grag/components/parse_pdf.py index 9ab2205..dc30f8a 100644 --- a/src/grag/components/parse_pdf.py +++ b/src/grag/components/parse_pdf.py @@ -3,6 +3,7 @@ This module provides: - ParsePDF """ + from langchain_core.documents import Document from unstructured.partition.pdf import partition_pdf @@ -27,15 +28,15 @@ class ParsePDF: """ def __init__( - self, - single_text_out=parser_conf["single_text_out"], - strategy=parser_conf["strategy"], - infer_table_structure=parser_conf["infer_table_structure"], - extract_images=parser_conf["extract_images"], - image_output_dir=parser_conf["image_output_dir"], - add_captions_to_text=parser_conf["add_captions_to_text"], - add_captions_to_blocks=parser_conf["add_captions_to_blocks"], - table_as_html=parser_conf["table_as_html"], + self, + single_text_out=parser_conf["single_text_out"], + strategy=parser_conf["strategy"], + infer_table_structure=parser_conf["infer_table_structure"], + extract_images=parser_conf["extract_images"], + image_output_dir=parser_conf["image_output_dir"], + add_captions_to_text=parser_conf["add_captions_to_text"], + add_captions_to_blocks=parser_conf["add_captions_to_blocks"], + table_as_html=parser_conf["table_as_html"], ): """Initialize instance variables with parameters.""" self.strategy = strategy @@ -77,7 +78,7 @@ def partition(self, path: str): def classify(self, partitions): """Classifies the partitioned elements into Text, Tables, and Images list in a dictionary. - + Also adds captions for each element (if available). Parameters: @@ -94,7 +95,7 @@ def classify(self, partitions): if element.category == "Table": if self.add_captions_to_blocks and i + 1 < len(partitions): if ( - partitions[i + 1].category == "FigureCaption" + partitions[i + 1].category == "FigureCaption" ): # check for caption caption_element = partitions[i + 1] else: @@ -105,7 +106,7 @@ def classify(self, partitions): elif element.category == "Image": if self.add_captions_to_blocks and i + 1 < len(partitions): if ( - partitions[i + 1].category == "FigureCaption" + partitions[i + 1].category == "FigureCaption" ): # check for caption caption_element = partitions[i + 1] else: @@ -193,7 +194,7 @@ def process_tables(self, elements): if caption_element: if ( - self.add_caption_first + self.add_caption_first ): # if there is a caption, add that before the element content = "\n\n".join([str(caption_element), table_data]) else: diff --git a/src/grag/components/prompt.py b/src/grag/components/prompt.py index 86bf8df..4364c06 100644 --- a/src/grag/components/prompt.py +++ b/src/grag/components/prompt.py @@ -4,6 +4,7 @@ - Prompt - for generic prompts - FewShotPrompt - for few-shot prompts """ + import json from pathlib import Path from typing import Any, Dict, List, Optional, Union @@ -20,7 +21,7 @@ class Prompt(BaseModel): """A class for generic prompts. - + Attributes: name (str): The prompt name (Optional, defaults to "custom_prompt") llm_type (str): The type of llm, llama2, etc (Optional, defaults to "None") @@ -32,6 +33,7 @@ class Prompt(BaseModel): input_keys (List[str]): The input keys for the prompt template (str): The template for the prompt """ + name: str = Field(default="custom_prompt") llm_type: str = Field(default="None") task: str = Field(default="QA") @@ -82,7 +84,7 @@ def __init__(self, **kwargs): ) def save( - self, filepath: Union[Path, str, None], overwrite=False + self, filepath: Union[Path, str, None], overwrite=False ) -> Union[None, ValueError]: """Saves the prompt class into a json file.""" dump = self.model_dump_json(indent=2, exclude_defaults=True, exclude_none=True) @@ -128,6 +130,7 @@ class FewShotPrompt(Prompt): example_template (str): The template for formatting the examples examples (List[Dict[str, Any]]): The list of examples, each example is a dictionary with respective keys """ + output_keys: List[str] examples: List[Dict[str, Any]] prefix: str diff --git a/src/grag/components/text_splitter.py b/src/grag/components/text_splitter.py index a0ecfd9..d04c9a5 100644 --- a/src/grag/components/text_splitter.py +++ b/src/grag/components/text_splitter.py @@ -3,6 +3,7 @@ This module provides: - TextSplitter """ + from langchain.text_splitter import RecursiveCharacterTextSplitter from .utils import get_config @@ -13,15 +14,17 @@ # %% class TextSplitter: """Class for recursively chunking text, it prioritizes '/n/n then '/n' and so on. - + Attributes: chunk_size: maximum size of chunk chunk_overlap: chunk overlap size """ - def __init__(self, - chunk_size: int = text_splitter_conf["chunk_size"], - chunk_overlap: int = text_splitter_conf["chunk_overlap"]): + def __init__( + self, + chunk_size: int = text_splitter_conf["chunk_size"], + chunk_overlap: int = text_splitter_conf["chunk_overlap"], + ): """Initialize TextSplitter.""" self.text_splitter = RecursiveCharacterTextSplitter( chunk_size=int(chunk_size), diff --git a/src/grag/components/utils.py b/src/grag/components/utils.py index 0233d32..2e34dc9 100644 --- a/src/grag/components/utils.py +++ b/src/grag/components/utils.py @@ -6,6 +6,7 @@ - find_config_path: finds the path of the 'config.ini' file by traversing up the directory tree from the current path. - get_config: retrieves and parses the configuration settings from the 'config.ini' file. """ + import json import os import textwrap @@ -19,7 +20,7 @@ def stuff_docs(docs: List[Document]) -> str: r"""Concatenates langchain documents into a string using '\n\n' seperator. - + Args: docs: List of langchain_core.documents.Document diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index 05a7520..be055ba 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -3,6 +3,7 @@ This module provides: - BasicRAG """ + import json from typing import List, Union @@ -19,7 +20,7 @@ class BasicRAG: """Class for Basis RAG. - + Attributes: model_name (str): Name of the llm model doc_chain (str): Name of the document chain, ("stuff", "refine"), defaults to "stuff" @@ -30,13 +31,15 @@ class BasicRAG: """ def __init__( - self, - model_name=None, - doc_chain="stuff", - task="QA", - llm_kwargs=None, - retriever_kwargs=None, - custom_prompt: Union[Prompt, FewShotPrompt, List[Prompt, FewShotPrompt], None] = None, + self, + model_name=None, + doc_chain="stuff", + task="QA", + llm_kwargs=None, + retriever_kwargs=None, + custom_prompt: Union[ + Prompt, FewShotPrompt, List[Prompt, FewShotPrompt], None + ] = None, ): """Initialize BasicRAG.""" if retriever_kwargs is None: @@ -144,7 +147,7 @@ def prompt_matcher(self): @staticmethod def stuff_docs(docs: List[Document]) -> str: r"""Concatenates docs into a string seperated by '\n\n'. - + Args: docs: List of langchain_core.documents.Document From 00e2d6bcd915df648917212e2c6dd01703f20a0e Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Sat, 23 Mar 2024 15:31:37 -0400 Subject: [PATCH 41/53] Update embedding docstring --- src/grag/components/embedding.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/grag/components/embedding.py b/src/grag/components/embedding.py index eab107f..eeb0f82 100644 --- a/src/grag/components/embedding.py +++ b/src/grag/components/embedding.py @@ -1,6 +1,6 @@ """Class for embedding. -This module provies: +This module provides: - Embedding """ From 26235f561748e709cc4073cdcefddbcdc0e5e27d Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Sat, 23 Mar 2024 15:55:47 -0400 Subject: [PATCH 42/53] Update doc strings. --- src/grag/components/vectordb/base.py | 14 +++++-- src/grag/components/vectordb/chroma_client.py | 41 +++++++++++-------- .../components/vectordb/deeplake_client.py | 39 +++++++++++------- 3 files changed, 60 insertions(+), 34 deletions(-) diff --git a/src/grag/components/vectordb/base.py b/src/grag/components/vectordb/base.py index c474232..1146d77 100644 --- a/src/grag/components/vectordb/base.py +++ b/src/grag/components/vectordb/base.py @@ -1,3 +1,9 @@ +"""Abstract base class for vector database clients. + +This module provides: +- VectorDB +""" + from abc import ABC, abstractmethod from typing import List, Tuple, Union @@ -6,6 +12,8 @@ class VectorDB(ABC): + """Abstract base class for vector database clients.""" + @abstractmethod def __len__(self) -> int: """Number of chunks in the vector database.""" @@ -43,7 +51,7 @@ async def aadd_docs(self, docs: List[Document], verbose: bool = True) -> None: @abstractmethod def get_chunk( - self, query: str, with_score: bool = False, top_k: int = None + self, query: str, with_score: bool = False, top_k: int = None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the vector database. @@ -59,9 +67,9 @@ def get_chunk( @abstractmethod async def aget_chunk( - self, query: str, with_score: bool = False, top_k: int = None + self, query: str, with_score: bool = False, top_k: int = None ) -> Union[List[Document], List[Tuple[Document, float]]]: - """Returns the most similar chunks from the vector database. (asynchronous) + """Returns the most similar chunks from the vector database (asynchronous). Args: query: A query string diff --git a/src/grag/components/vectordb/chroma_client.py b/src/grag/components/vectordb/chroma_client.py index ef9091f..105882c 100644 --- a/src/grag/components/vectordb/chroma_client.py +++ b/src/grag/components/vectordb/chroma_client.py @@ -1,3 +1,8 @@ +"""Class for Chroma vector database. + +This module provides: +- ChromaClient +""" from typing import List, Tuple, Union import chromadb @@ -37,14 +42,16 @@ class ChromaClient(VectorDB): """ def __init__( - self, - host=chroma_conf["host"], - port=chroma_conf["port"], - collection_name=chroma_conf["collection_name"], - embedding_type=chroma_conf["embedding_type"], - embedding_model=chroma_conf["embedding_model"], + self, + host=chroma_conf["host"], + port=chroma_conf["port"], + collection_name=chroma_conf["collection_name"], + embedding_type=chroma_conf["embedding_type"], + embedding_model=chroma_conf["embedding_model"], ): - """Args: + """Initialize a ChromaClient object. + + Args: host: IP Address of hosted Chroma Vectorstore, defaults to argument from config file port: port address of hosted Chroma Vectorstore, defaults to argument from config file collection_name: name of the collection in the Chroma Vectorstore, defaults to argument from config file @@ -73,9 +80,11 @@ def __init__( self.allowed_metadata_types = (str, int, float, bool) def __len__(self) -> int: + """Count the number of chunks in the database.""" return self.collection.count() def delete(self) -> None: + """Delete all the chunks in the database collection.""" self.client.delete_collection(self.collection_name) self.collection = self.client.get_or_create_collection( name=self.collection_name @@ -87,7 +96,7 @@ def delete(self) -> None: ) def test_connection(self, verbose=True) -> int: - """Tests connection with Chroma Vectorstore + """Tests connection with Chroma Vectorstore. Args: verbose: if True, prints connection status @@ -104,7 +113,7 @@ def test_connection(self, verbose=True) -> int: return response def add_docs(self, docs: List[Document], verbose=True) -> None: - """Adds documents to chroma vectorstore + """Adds documents to chroma vectorstore. Args: docs: List of Documents @@ -115,12 +124,12 @@ def add_docs(self, docs: List[Document], verbose=True) -> None: """ docs = self._filter_metadata(docs) for doc in ( - tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs + tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs ): _id = self.langchain_client.add_documents([doc]) async def aadd_docs(self, docs: List[Document], verbose=True) -> None: - """Asynchronously adds documents to chroma vectorstore + """Asynchronously adds documents to chroma vectorstore. Args: docs: List of Documents @@ -132,9 +141,9 @@ async def aadd_docs(self, docs: List[Document], verbose=True) -> None: docs = self._filter_metadata(docs) if verbose: for doc in atqdm( - docs, - desc=f"Adding documents to {self.collection_name}", - total=len(docs), + docs, + desc=f"Adding documents to {self.collection_name}", + total=len(docs), ): await self.langchain_client.aadd_documents([doc]) else: @@ -142,7 +151,7 @@ async def aadd_docs(self, docs: List[Document], verbose=True) -> None: await self.langchain_client.aadd_documents([doc]) def get_chunk( - self, query: str, with_score: bool = False, top_k: int = None + self, query: str, with_score: bool = False, top_k: int = None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the chroma database. @@ -165,7 +174,7 @@ def get_chunk( ) async def aget_chunk( - self, query: str, with_score=False, top_k=None + self, query: str, with_score=False, top_k=None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most (cosine) similar chunks from the vector database, asynchronously. diff --git a/src/grag/components/vectordb/deeplake_client.py b/src/grag/components/vectordb/deeplake_client.py index 3a389c3..2cb0270 100644 --- a/src/grag/components/vectordb/deeplake_client.py +++ b/src/grag/components/vectordb/deeplake_client.py @@ -1,3 +1,9 @@ +"""Class for DeepLake vector database. + +This module provides: +- DeepLakeClient +""" + from pathlib import Path from typing import List, Tuple, Union @@ -13,7 +19,7 @@ class DeepLakeClient(VectorDB): - """A class for connecting to a DeepLake Vectorstore + """A class for connecting to a DeepLake Vectorstore. Attributes: store_path : str, Path @@ -33,13 +39,14 @@ class DeepLakeClient(VectorDB): """ def __init__( - self, - collection_name: str = deeplake_conf["collection_name"], - store_path: Union[str, Path] = deeplake_conf["store_path"], - embedding_type: str = deeplake_conf["embedding_type"], - embedding_model: str = deeplake_conf["embedding_model"], - read_only: bool = False, + self, + collection_name: str = deeplake_conf["collection_name"], + store_path: Union[str, Path] = deeplake_conf["store_path"], + embedding_type: str = deeplake_conf["embedding_type"], + embedding_model: str = deeplake_conf["embedding_model"], + read_only: bool = False, ): + """Initialize DeepLake client object.""" self.store_path = Path(store_path) self.collection_name = collection_name self.read_only = read_only @@ -60,13 +67,15 @@ def __init__( self.allowed_metadata_types = (str, int, float, bool) def __len__(self) -> int: + """Number of chunks in the vector database.""" return self.client.__len__() def delete(self) -> None: + """Delete all chunks in the vector database.""" self.client.delete(delete_all=True) def add_docs(self, docs: List[Document], verbose=True) -> None: - """Adds documents to deeplake vectorstore + """Adds documents to deeplake vectorstore. Args: docs: List of Documents @@ -77,12 +86,12 @@ def add_docs(self, docs: List[Document], verbose=True) -> None: """ docs = self._filter_metadata(docs) for doc in ( - tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs + tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs ): _id = self.langchain_client.add_documents([doc]) async def aadd_docs(self, docs: List[Document], verbose=True) -> None: - """Asynchronously adds documents to chroma vectorstore + """Asynchronously adds documents to chroma vectorstore. Args: docs: List of Documents @@ -94,9 +103,9 @@ async def aadd_docs(self, docs: List[Document], verbose=True) -> None: docs = self._filter_metadata(docs) if verbose: for doc in atqdm( - docs, - desc=f"Adding documents to {self.collection_name}", - total=len(docs), + docs, + desc=f"Adding documents to {self.collection_name}", + total=len(docs), ): await self.langchain_client.aadd_documents([doc]) else: @@ -104,7 +113,7 @@ async def aadd_docs(self, docs: List[Document], verbose=True) -> None: await self.langchain_client.aadd_documents([doc]) def get_chunk( - self, query: str, with_score: bool = False, top_k: int = None + self, query: str, with_score: bool = False, top_k: int = None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the deeplake database. @@ -127,7 +136,7 @@ def get_chunk( ) async def aget_chunk( - self, query: str, with_score=False, top_k=None + self, query: str, with_score=False, top_k=None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the deeplake database, asynchronously. From 8e78f75a4dec4a9fcebec9fb89052b05c97f62c5 Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Sat, 23 Mar 2024 18:49:45 -0400 Subject: [PATCH 43/53] quantize file --- src/grag/quantize/__init__.py | 0 src/grag/quantize/quantize.py | 104 +++++++++++----------------------- src/grag/quantize/utils.py | 76 +++++++++++++++++++++++++ 3 files changed, 109 insertions(+), 71 deletions(-) create mode 100644 src/grag/quantize/__init__.py create mode 100644 src/grag/quantize/utils.py diff --git a/src/grag/quantize/__init__.py b/src/grag/quantize/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/grag/quantize/quantize.py b/src/grag/quantize/quantize.py index 2728e13..02065a9 100644 --- a/src/grag/quantize/quantize.py +++ b/src/grag/quantize/quantize.py @@ -1,76 +1,38 @@ -import os -import subprocess - from grag.components.utils import get_config -from huggingface_hub import snapshot_download +from grag.quantize.utils import ( + building_llama, + fetch_model_repo, + get_llamacpp_repo, + quantize_model, +) -original_dir = os.getcwd() config = get_config() root_path = config['quantize']['llama_cpp_path'] - -def get_llamacpp_repo(): - if os.path.exists(f"{root_path}/llama.cpp"): - subprocess.run([f"cd {root_path}/llama.cpp && git pull"], check=True, shell=True) - else: - subprocess.run( - [f"cd {root_path} && git clone https://github.com/ggerganov/llama.cpp.git"], - check=True, shell=True) - - -def building_llama(): - os.chdir(f"{root_path}/llama.cpp/") - try: - subprocess.run(['which', 'make'], check=True, stdout=subprocess.DEVNULL) - subprocess.run(['make', 'LLAMA_CUBLAS=1'], check=True) - print('Llama.cpp build successfull.') - except subprocess.CalledProcessError: - try: - subprocess.run(['which', 'cmake'], check=True, stdout=subprocess.DEVNULL) - subprocess.run(['mkdir', 'build'], check=True) - subprocess.run( - ['cd', 'build', '&&', 'cmake', '..', '-DLLAMA_CUBLAS=ON', '&&', 'cmake', '--build', '.', '--config', - 'Release'], shell=True, check=True) - print('Llama.cpp build successfull.') - except subprocess.CalledProcessError: - print("Unable to build, cannot find make or cmake.") - os.chdir(original_dir) - - -def fetch_model_repo(): - response = input("Do you want us to download the model? (yes/no) [Enter for yes]: ").strip().lower() - if response == "no": - print("Please copy the model folder to 'llama.cpp/models/' folder.") - elif response == "yes" or response == "": - repo_id = input('Please enter the repo_id for the model (you can check on https://huggingface.co/models): ') - local_dir = f"{root_path}/llama.cpp/model/{repo_id.split('/')[1]}" - os.mkdir(local_dir) - snapshot_download(repo_id=repo_id, local_dir=local_dir, - local_dir_use_symlinks=False) - print(f"Model downloaded in {local_dir}") - - -def quantize_model(quantization): - os.chdir(f"{root_path}/llama.cpp/") - subprocess.run(["python3", "convert.py", f"models/{model_dir_path}/"], check=True) - - model_file = f"models/{model_dir_path}/ggml-model-f16.gguf" - quantized_model_file = f"models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" - subprocess.run(["llm_quantize", model_file, quantized_model_file, quantization], check=True) - print(f"Quantized model present at {root_path}/llama.cpp/{quantized_model_file}") - os.chdir(original_dir) - - -if __name__ == "__main__": - get_llamacpp_repo() - building_llama() - fetch_model_repo() - - quantization = input("Enter quantization: ") - quantize_model(quantization) - # if len(sys.argv) < 2 or len(sys.argv) > 3: - # print("Usage: python script.py []") - # sys.exit(1) - # model_dir_path = sys.argv[1] - # quantization = sys.argv[2] if len(sys.argv) == 3 else None - # execute_commands(model_dir_path, quantization) +user_input = input( + "Enter the path to the llama_cpp cloned repo, or where you'd like to clone it. Press Enter to use the default config path: ").strip() + +if user_input != "": + root_path = user_input + +res = get_llamacpp_repo(root_path) + +if "Already up to date." in res.stdout: + print("Repository is already up to date. Skipping build.") +else: + print("Updates found. Starting build...") + building_llama(root_path) + +response = input("Do you want us to download the model? (y/n) [Enter for yes]: ").strip().lower() +if response == "n": + print("Please copy the model folder to 'llama.cpp/models/' folder.") + _ = input("Enter if you have already copied the model:") + model_dir = input("Enter the model directory name: ") +elif response == "y" or response == "": + repo_id = input('Please enter the repo_id for the model (you can check on https://huggingface.co/models): ').strip() + fetch_model_repo(repo_id, root_path) + model_dir = repo_id.split('/')[1] + +quantization = input( + "Enter quantization, recommended - Q5_K_M or Q4_K_M for more check https://github.com/ggerganov/llama.cpp/blob/master/examples/quantize/quantize.cpp#L19 : ") +quantize_model(model_dir, quantization, root_path) diff --git a/src/grag/quantize/utils.py b/src/grag/quantize/utils.py new file mode 100644 index 0000000..3df3c1a --- /dev/null +++ b/src/grag/quantize/utils.py @@ -0,0 +1,76 @@ +import os +import subprocess +from pathlib import Path + +from huggingface_hub import snapshot_download + + +def get_llamacpp_repo(root_path: str) -> None: + """Clones or pulls the llama.cpp repository into the specified root path. + + Args: + root_path (str): The root directory where the llama.cpp repository will be cloned or updated. + """ + if os.path.exists(f"{root_path}/llama.cpp"): + print(f"Repo exists at: {root_path}/llama.cpp") + res = subprocess.run([f"cd {root_path}/llama.cpp && git pull"], check=True, shell=True, capture_output=True) + else: + + subprocess.run( + [f"cd {root_path} && git clone https://github.com/ggerganov/llama.cpp.git"], + check=True, shell=True) + + +def building_llama(root_path: str) -> None: + """Attempts to build the llama.cpp project using make or cmake. + + Args: + root_path (str): The root directory where the llama.cpp project is located. + """ + os.chdir(f"{root_path}/llama.cpp/") + try: + subprocess.run(['which', 'make'], check=True, stdout=subprocess.DEVNULL) + subprocess.run(['make', 'LLAMA_CUBLAS=1'], check=True) + print('Llama.cpp build successful.') + except subprocess.CalledProcessError: + try: + subprocess.run(['which', 'cmake'], check=True, stdout=subprocess.DEVNULL) + subprocess.run(['mkdir', 'build'], check=True) + subprocess.run( + ['cd', 'build', '&&', 'cmake', '..', '-DLLAMA_CUBLAS=ON', '&&', 'cmake', '--build', '.', '--config', + 'Release'], shell=True, check=True) + print('Llama.cpp build successful.') + except subprocess.CalledProcessError: + print("Unable to build, cannot find make or cmake.") + finally: + os.chdir(Path(__file__).parent) # Assuming you want to return to the root path after operation + + +def fetch_model_repo(repo_id: str, root_path: str) -> None: + """Download model from huggingface.co/models. + + Args: + repo_id (str): Repository ID of the model to download. + root_path (str): The root path where the model should be downloaded or copied. + """ + local_dir = f"{root_path}/llama.cpp/model/{repo_id.split('/')[1]}" + os.mkdir(local_dir) + snapshot_download(repo_id=repo_id, local_dir=local_dir, local_dir_use_symlinks=False) + print(f"Model downloaded in {local_dir}") + + +def quantize_model(model_dir_path: str, quantization: str, root_path: str) -> None: + """Quantizes a specified model using a given quantization level. + + Args: + model_dir_path (str): The directory path of the model to be quantized. + quantization (str): The quantization level to apply. + root_path (str): The root directory path of the project. + """ + os.chdir(f"{root_path}/llama.cpp/") + subprocess.run(["python3", "convert.py", f"models/{model_dir_path}/"], check=True) + model_file = f"models/{model_dir_path}/ggml-model-f16.gguf" + quantized_model_file = f"models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" + subprocess.run(["llm_quantize", model_file, quantized_model_file, quantization], check=True) + print(f"Quantized model present at {root_path}/llama.cpp/{quantized_model_file}") + os.chdir(Path(__file__).parent) # Return to the root path after operation From 11697c006bac3865203cc242c6841a024ec1f52a Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Sat, 23 Mar 2024 18:55:11 -0400 Subject: [PATCH 44/53] Revert "Merge branch 'quantize' of https://github.com/arjbingly/Capstone_5 into quantize" This reverts commit 79ebf3ae4bbc634f075d51791b1442569b1cd03a, reversing changes made to 8e78f75a4dec4a9fcebec9fb89052b05c97f62c5. --- src/grag/quantize/quantize.py | 102 +--------------------------------- 1 file changed, 1 insertion(+), 101 deletions(-) diff --git a/src/grag/quantize/quantize.py b/src/grag/quantize/quantize.py index c013b07..02065a9 100644 --- a/src/grag/quantize/quantize.py +++ b/src/grag/quantize/quantize.py @@ -7,70 +7,21 @@ ) config = get_config() -root_path = config["quantize"]["llama_cpp_path"] +root_path = config['quantize']['llama_cpp_path'] user_input = input( "Enter the path to the llama_cpp cloned repo, or where you'd like to clone it. Press Enter to use the default config path: ").strip() -<<<<<<< HEAD if user_input != "": root_path = user_input -======= -def get_llamacpp_repo(): - if os.path.exists(f"{root_path}/llama.cpp"): - subprocess.run( - [f"cd {root_path}/llama.cpp && git pull"], check=True, shell=True - ) - else: - subprocess.run( - [f"cd {root_path} && git clone https://github.com/ggerganov/llama.cpp.git"], - check=True, - shell=True, - ) ->>>>>>> aec73771f90cdeeaa9d4fe128fc04fb5befb786e res = get_llamacpp_repo(root_path) -<<<<<<< HEAD if "Already up to date." in res.stdout: print("Repository is already up to date. Skipping build.") else: print("Updates found. Starting build...") building_llama(root_path) -======= -def building_llama(): - os.chdir(f"{root_path}/llama.cpp/") - try: - subprocess.run(["which", "make"], check=True, stdout=subprocess.DEVNULL) - subprocess.run(["make", "LLAMA_CUBLAS=1"], check=True) - print("Llama.cpp build successfull.") - except subprocess.CalledProcessError: - try: - subprocess.run(["which", "cmake"], check=True, stdout=subprocess.DEVNULL) - subprocess.run(["mkdir", "build"], check=True) - subprocess.run( - [ - "cd", - "build", - "&&", - "cmake", - "..", - "-DLLAMA_CUBLAS=ON", - "&&", - "cmake", - "--build", - ".", - "--config", - "Release", - ], - shell=True, - check=True, - ) - print("Llama.cpp build successfull.") - except subprocess.CalledProcessError: - print("Unable to build, cannot find make or cmake.") - os.chdir(original_dir) ->>>>>>> aec73771f90cdeeaa9d4fe128fc04fb5befb786e response = input("Do you want us to download the model? (y/n) [Enter for yes]: ").strip().lower() if response == "n": @@ -82,57 +33,6 @@ def building_llama(): fetch_model_repo(repo_id, root_path) model_dir = repo_id.split('/')[1] -<<<<<<< HEAD quantization = input( "Enter quantization, recommended - Q5_K_M or Q4_K_M for more check https://github.com/ggerganov/llama.cpp/blob/master/examples/quantize/quantize.cpp#L19 : ") quantize_model(model_dir, quantization, root_path) -======= -def fetch_model_repo(): - response = ( - input("Do you want us to download the model? (yes/no) [Enter for yes]: ") - .strip() - .lower() - ) - if response == "no": - print("Please copy the model folder to 'llama.cpp/models/' folder.") - elif response == "yes" or response == "": - repo_id = input( - "Please enter the repo_id for the model (you can check on https://huggingface.co/models): " - ) - local_dir = f"{root_path}/llama.cpp/model/{repo_id.split('/')[1]}" - os.mkdir(local_dir) - snapshot_download( - repo_id=repo_id, local_dir=local_dir, local_dir_use_symlinks=False - ) - print(f"Model downloaded in {local_dir}") - - -def quantize_model(quantization): - os.chdir(f"{root_path}/llama.cpp/") - subprocess.run(["python3", "convert.py", f"models/{model_dir_path}/"], check=True) - - model_file = f"models/{model_dir_path}/ggml-model-f16.gguf" - quantized_model_file = ( - f"models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" - ) - subprocess.run( - ["llm_quantize", model_file, quantized_model_file, quantization], check=True - ) - print(f"Quantized model present at {root_path}/llama.cpp/{quantized_model_file}") - os.chdir(original_dir) - - -if __name__ == "__main__": - get_llamacpp_repo() - building_llama() - fetch_model_repo() - - quantization = input("Enter quantization: ") - quantize_model(quantization) - # if len(sys.argv) < 2 or len(sys.argv) > 3: - # print("Usage: python script.py []") - # sys.exit(1) - # model_dir_path = sys.argv[1] - # quantization = sys.argv[2] if len(sys.argv) == 3 else None - # execute_commands(model_dir_path, quantization) ->>>>>>> aec73771f90cdeeaa9d4fe128fc04fb5befb786e From 1bb12163f584150286714344082d60280113f9d1 Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Sat, 23 Mar 2024 20:12:26 -0400 Subject: [PATCH 45/53] rectified quantization, issue with llama.cpp --- src/grag/quantize/quantize.py | 2 +- src/grag/quantize/utils.py | 17 +++++++++-------- src/tests/quantize/__init__.py | 0 src/tests/quantize/quantize_test.py | 0 4 files changed, 10 insertions(+), 9 deletions(-) create mode 100644 src/tests/quantize/__init__.py create mode 100644 src/tests/quantize/quantize_test.py diff --git a/src/grag/quantize/quantize.py b/src/grag/quantize/quantize.py index 02065a9..8e42117 100644 --- a/src/grag/quantize/quantize.py +++ b/src/grag/quantize/quantize.py @@ -17,7 +17,7 @@ res = get_llamacpp_repo(root_path) -if "Already up to date." in res.stdout: +if "Already up to date." in str(res.stdout): print("Repository is already up to date. Skipping build.") else: print("Updates found. Starting build...") diff --git a/src/grag/quantize/utils.py b/src/grag/quantize/utils.py index 3df3c1a..661fb65 100644 --- a/src/grag/quantize/utils.py +++ b/src/grag/quantize/utils.py @@ -15,10 +15,11 @@ def get_llamacpp_repo(root_path: str) -> None: print(f"Repo exists at: {root_path}/llama.cpp") res = subprocess.run([f"cd {root_path}/llama.cpp && git pull"], check=True, shell=True, capture_output=True) else: - - subprocess.run( + res = subprocess.run( [f"cd {root_path} && git clone https://github.com/ggerganov/llama.cpp.git"], - check=True, shell=True) + check=True, shell=True, capture_output=True) + + return res def building_llama(root_path: str) -> None: @@ -53,9 +54,9 @@ def fetch_model_repo(repo_id: str, root_path: str) -> None: repo_id (str): Repository ID of the model to download. root_path (str): The root path where the model should be downloaded or copied. """ - local_dir = f"{root_path}/llama.cpp/model/{repo_id.split('/')[1]}" - os.mkdir(local_dir) - snapshot_download(repo_id=repo_id, local_dir=local_dir, local_dir_use_symlinks=False) + local_dir = f"{root_path}/llama.cpp/models/{repo_id.split('/')[1]}" + os.makedirs(local_dir, exist_ok=True) + snapshot_download(repo_id=repo_id, local_dir=local_dir, local_dir_use_symlinks=auto, resume_download=True) print(f"Model downloaded in {local_dir}") @@ -69,8 +70,8 @@ def quantize_model(model_dir_path: str, quantization: str, root_path: str) -> No """ os.chdir(f"{root_path}/llama.cpp/") subprocess.run(["python3", "convert.py", f"models/{model_dir_path}/"], check=True) - model_file = f"models/{model_dir_path}/ggml-model-f16.gguf" + model_file = f"models/{model_dir_path}/ggml-model-f32.gguf" quantized_model_file = f"models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" - subprocess.run(["llm_quantize", model_file, quantized_model_file, quantization], check=True) + subprocess.run(["quantize", model_file, quantized_model_file, quantization], check=True) print(f"Quantized model present at {root_path}/llama.cpp/{quantized_model_file}") os.chdir(Path(__file__).parent) # Return to the root path after operation diff --git a/src/tests/quantize/__init__.py b/src/tests/quantize/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tests/quantize/quantize_test.py b/src/tests/quantize/quantize_test.py new file mode 100644 index 0000000..e69de29 From a7354ee7be3dadeff6a596e88a4b16e36cccbb69 Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Sun, 24 Mar 2024 15:00:14 -0400 Subject: [PATCH 46/53] issue in llama.cpp --- llm_quantize/quantize.py | 4 ++-- src/grag/quantize/quantize.py | 1 + src/grag/quantize/utils.py | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/llm_quantize/quantize.py b/llm_quantize/quantize.py index 7fb1c24..708b6c8 100644 --- a/llm_quantize/quantize.py +++ b/llm_quantize/quantize.py @@ -1,6 +1,6 @@ +import os import subprocess import sys -import os def execute_commands(model_dir_path, quantization=None): @@ -13,7 +13,7 @@ def execute_commands(model_dir_path, quantization=None): if quantization: model_file = f"llama.cpp/models/{model_dir_path}/ggml-model-f16.gguf" quantized_model_file = f"llama.cpp/models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" - subprocess.run(["llama.cpp/llm_quantize", model_file, quantized_model_file, quantization], check=True) + subprocess.run(["llama.cpp/quantize", model_file, quantized_model_file, quantization], check=True) else: print("llama.cpp doesn't exist, check readme how to clone.") diff --git a/src/grag/quantize/quantize.py b/src/grag/quantize/quantize.py index 8e42117..d05990c 100644 --- a/src/grag/quantize/quantize.py +++ b/src/grag/quantize/quantize.py @@ -15,6 +15,7 @@ if user_input != "": root_path = user_input +# noinspection PyNoneFunctionAssignment res = get_llamacpp_repo(root_path) if "Already up to date." in str(res.stdout): diff --git a/src/grag/quantize/utils.py b/src/grag/quantize/utils.py index 661fb65..7e2b92f 100644 --- a/src/grag/quantize/utils.py +++ b/src/grag/quantize/utils.py @@ -72,6 +72,6 @@ def quantize_model(model_dir_path: str, quantization: str, root_path: str) -> No subprocess.run(["python3", "convert.py", f"models/{model_dir_path}/"], check=True) model_file = f"models/{model_dir_path}/ggml-model-f32.gguf" quantized_model_file = f"models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" - subprocess.run(["quantize", model_file, quantized_model_file, quantization], check=True) + subprocess.run(["./quantize", model_file, quantized_model_file, quantization], check=True) print(f"Quantized model present at {root_path}/llama.cpp/{quantized_model_file}") os.chdir(Path(__file__).parent) # Return to the root path after operation From caebf0a3eb19e681c08804e67a3cc6ce8d8ade0a Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Sun, 24 Mar 2024 15:29:54 -0400 Subject: [PATCH 47/53] Config changes for deeplake --- src/config.ini | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/config.ini b/src/config.ini index 452ac04..eb3cab2 100644 --- a/src/config.ini +++ b/src/config.ini @@ -14,6 +14,12 @@ n_gpu_layers_cpp : -1 std_out : True base_dir : ${root:root_path}/models +[deeplake] +collection_name : arxiv +embedding_type : instructor-embedding +embedding_model : hkunlp/instructor-xl +store_path : ${data:data_path}/vectordb + [chroma] host : localhost port : 8000 @@ -51,4 +57,4 @@ table_as_html : True data_path : ${root:root_path}/data [root] -root_path : /home/ubuntu/volume_2k/Capstone_5 \ No newline at end of file +root_path : /home/ubuntu/volume_2k/Capstone_5 From 66c06d0fb8e53daf69b967c7c7c102976d5bfd48 Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Sun, 24 Mar 2024 17:05:47 -0400 Subject: [PATCH 48/53] modifications and corrections after testing --- src/grag/quantize/quantize.py | 5 ++-- src/grag/quantize/utils.py | 43 +++++++++++++++++++++++------------ 2 files changed, 31 insertions(+), 17 deletions(-) diff --git a/src/grag/quantize/quantize.py b/src/grag/quantize/quantize.py index d05990c..68168a2 100644 --- a/src/grag/quantize/quantize.py +++ b/src/grag/quantize/quantize.py @@ -1,6 +1,6 @@ from grag.components.utils import get_config from grag.quantize.utils import ( - building_llama, + building_llamacpp, fetch_model_repo, get_llamacpp_repo, quantize_model, @@ -15,14 +15,13 @@ if user_input != "": root_path = user_input -# noinspection PyNoneFunctionAssignment res = get_llamacpp_repo(root_path) if "Already up to date." in str(res.stdout): print("Repository is already up to date. Skipping build.") else: print("Updates found. Starting build...") - building_llama(root_path) + building_llamacpp(root_path) response = input("Do you want us to download the model? (y/n) [Enter for yes]: ").strip().lower() if response == "n": diff --git a/src/grag/quantize/utils.py b/src/grag/quantize/utils.py index 7e2b92f..8d9d5bc 100644 --- a/src/grag/quantize/utils.py +++ b/src/grag/quantize/utils.py @@ -1,28 +1,34 @@ import os import subprocess from pathlib import Path +from typing import Optional, Union +from grag.components.utils import get_config from huggingface_hub import snapshot_download +config = get_config() -def get_llamacpp_repo(root_path: str) -> None: + +def get_llamacpp_repo(root_path: str) -> subprocess.CompletedProcess: """Clones or pulls the llama.cpp repository into the specified root path. Args: - root_path (str): The root directory where the llama.cpp repository will be cloned or updated. + root_path: The root directory where the llama.cpp repository will be cloned or updated. + + Returns: + A subprocess.CompletedProcess instance containing the result of the git operation. """ if os.path.exists(f"{root_path}/llama.cpp"): print(f"Repo exists at: {root_path}/llama.cpp") - res = subprocess.run([f"cd {root_path}/llama.cpp && git pull"], check=True, shell=True, capture_output=True) + res = subprocess.run(["git", "-C", f"{root_path}/llama.cpp", "pull"], check=True, capture_output=True) else: - res = subprocess.run( - [f"cd {root_path} && git clone https://github.com/ggerganov/llama.cpp.git"], - check=True, shell=True, capture_output=True) + res = subprocess.run(["git", "clone", "https://github.com/ggerganov/llama.cpp.git", f"{root_path}/llama.cpp"], + check=True, capture_output=True) return res -def building_llama(root_path: str) -> None: +def building_llamacpp(root_path: str) -> None: """Attempts to build the llama.cpp project using make or cmake. Args: @@ -56,22 +62,31 @@ def fetch_model_repo(repo_id: str, root_path: str) -> None: """ local_dir = f"{root_path}/llama.cpp/models/{repo_id.split('/')[1]}" os.makedirs(local_dir, exist_ok=True) - snapshot_download(repo_id=repo_id, local_dir=local_dir, local_dir_use_symlinks=auto, resume_download=True) + snapshot_download(repo_id=repo_id, local_dir=local_dir, local_dir_use_symlinks='auto', resume_download=True) print(f"Model downloaded in {local_dir}") -def quantize_model(model_dir_path: str, quantization: str, root_path: str) -> None: +def quantize_model(model_dir_path: str, quantization: str, root_path: str, + output_dir: Optional[Union[str, Path]] = None) -> None: """Quantizes a specified model using a given quantization level. Args: + output_dir (str, optional): Directory to save quantized model. Defaults to None model_dir_path (str): The directory path of the model to be quantized. quantization (str): The quantization level to apply. root_path (str): The root directory path of the project. """ os.chdir(f"{root_path}/llama.cpp/") - subprocess.run(["python3", "convert.py", f"models/{model_dir_path}/"], check=True) - model_file = f"models/{model_dir_path}/ggml-model-f32.gguf" - quantized_model_file = f"models/{model_dir_path.split('/')[-1]}/ggml-model-{quantization}.gguf" - subprocess.run(["./quantize", model_file, quantized_model_file, quantization], check=True) - print(f"Quantized model present at {root_path}/llama.cpp/{quantized_model_file}") + model_dir_path = Path(model_dir_path) + if output_dir is None: + output_dir = config['llm']['base_dir'] + + output_dir = Path(output_dir) / model_dir_path.name + os.makedirs(output_dir, exist_ok=True) + + subprocess.run(["python3", "convert.py", f"{model_dir_path}/"], check=True) + model_file = model_dir_path / "ggml-model-f32.gguf" + quantized_model_file = output_dir / f"ggml-model-{quantization}.gguf" + subprocess.run(["./quantize", str(model_file), str(quantized_model_file), quantization], check=True) + print(f"Quantized model present at {output_dir}") os.chdir(Path(__file__).parent) # Return to the root path after operation From f94114e4264eabe6952646062a6574cc954693e7 Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Sun, 24 Mar 2024 17:50:26 -0400 Subject: [PATCH 49/53] Retriever update --- projects/Basic-RAG/BasicRAG_stuff.py | 8 +- src/grag/components/multivec_retriever.py | 24 +++-- src/grag/rag/basic_rag.py | 28 +++--- .../components/multivec_retriever_test.py | 89 +++++++++++++++++++ 4 files changed, 127 insertions(+), 22 deletions(-) diff --git a/projects/Basic-RAG/BasicRAG_stuff.py b/projects/Basic-RAG/BasicRAG_stuff.py index 4bfafc3..63edeab 100644 --- a/projects/Basic-RAG/BasicRAG_stuff.py +++ b/projects/Basic-RAG/BasicRAG_stuff.py @@ -1,6 +1,10 @@ -from grag.grag.rag import BasicRAG +from grag.components.multivec_retriever import Retriever +from grag.components.vectordb.deeplake_client import DeepLakeClient +from grag.rag.basic_rag import BasicRAG -rag = BasicRAG(doc_chain="stuff") +client = DeepLakeClient(collection_name="test") +retriever = Retriever(vectordb=client) +rag = BasicRAG(doc_chain="stuff", retriever=retriever) if __name__ == "__main__": while True: diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index 98b3e6e..b0eeac7 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -1,11 +1,11 @@ import asyncio import uuid -from typing import List +from typing import Any, Dict, List, Optional from grag.components.text_splitter import TextSplitter from grag.components.utils import get_config from grag.components.vectordb.base import VectorDB -from grag.components.vectordb.chroma_client import ChromaClient +from grag.components.vectordb.deeplake_client import DeepLakeClient from langchain.retrievers.multi_vector import MultiVectorRetriever from langchain.storage import LocalFileStore from langchain_core.documents import Document @@ -31,11 +31,13 @@ class Retriever: """ def __init__( - self, - store_path: str = multivec_retriever_conf["store_path"], - id_key: str = multivec_retriever_conf["id_key"], - namespace: str = multivec_retriever_conf["namespace"], - top_k=1, + self, + vectordb: Optional[VectorDB] = None, + store_path: str = multivec_retriever_conf["store_path"], + id_key: str = multivec_retriever_conf["id_key"], + namespace: str = multivec_retriever_conf["namespace"], + top_k=1, + client_kwargs: Optional[Dict[str, Any]] = None ): """Args: store_path: Path to the local file store, defaults to argument from config file @@ -46,7 +48,13 @@ def __init__( self.store_path = store_path self.id_key = id_key self.namespace = uuid.UUID(namespace) - self.vectordb: VectorDB = ChromaClient() # TODO - change to init argument + if vectordb is None: + if client_kwargs is not None: + self.vectordb = DeepLakeClient(**client_kwargs) + else: + self.vectordb = DeepLakeClient() + else: + self.vectordb = vectordb self.store = LocalFileStore(self.store_path) self.retriever = MultiVectorRetriever( vectorstore=self.vectordb.langchain_client, diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index 9589920..1b344ea 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -1,10 +1,10 @@ import json -from typing import List, Union +from typing import List, Optional, Union from grag import prompts from grag.components.llm import LLM from grag.components.multivec_retriever import Retriever -from grag.components.prompt import Prompt, FewShotPrompt +from grag.components.prompt import FewShotPrompt, Prompt from grag.components.utils import get_config from importlib_resources import files from langchain_core.documents import Document @@ -14,18 +14,22 @@ class BasicRAG: def __init__( - self, - model_name=None, - doc_chain="stuff", - task="QA", - llm_kwargs=None, - retriever_kwargs=None, - custom_prompt: Union[Prompt, FewShotPrompt, None] = None, + self, + retriever: Optional[Retriever] = None, + model_name=None, + doc_chain="stuff", + task="QA", + llm_kwargs=None, + retriever_kwargs=None, + custom_prompt: Union[Prompt, FewShotPrompt, None] = None, ): - if retriever_kwargs is None: - self.retriever = Retriever() + if retriever is None: + if retriever_kwargs is None: + self.retriever = Retriever() + else: + self.retriever = Retriever(**retriever_kwargs) else: - self.retriever = Retriever(**retriever_kwargs) + self.retriever = retriever if llm_kwargs is None: self.llm_ = LLM() diff --git a/src/tests/components/multivec_retriever_test.py b/src/tests/components/multivec_retriever_test.py index 3ccb3fb..14dad0b 100644 --- a/src/tests/components/multivec_retriever_test.py +++ b/src/tests/components/multivec_retriever_test.py @@ -1,3 +1,92 @@ +import json + +from grag.components.multivec_retriever import Retriever +from langchain_core.documents import Document + +retriever = Retriever() # pass test collection + +doc = Document(page_content="Hello worlds", metadata={"source": "bars"}) + + +def test_retriver_id_gen(): + doc = Document(page_content="Hello world", metadata={"source": "bar"}) + id_ = retriever.id_gen(doc) + assert isinstance(id, str) + assert len(id_) == 32 + doc.page_content = doc.page_content + 'ABC' + id_1 = retriever.id_gen(doc) + assert id_ == id_1 + doc.metadata["source"] = "bars" + id_1 = retriever.id_gen(doc) + assert id_ != id_1 + + +def test_retriever_gen_doc_ids(): + docs = [Document(page_content="Hello world", metadata={"source": "bar"}), + Document(page_content="Hello", metadata={"source": "foo"})] + ids = retriever.gen_doc_ids(docs) + assert len(ids) == len(docs) + assert all(isinstance(id, str) for id in ids) + + +def test_retriever_split_docs(): + pass + + +def test_retriever_split_docs(): + pass + + +def test_retriever_add_docs(): + # small enough docs to not split. + docs = [Document(page_content= + """And so on this rainbow day, with storms all around them, and blue sky + above, they rode only as far as the valley. But from there, before they + turned to go back, the monuments appeared close, and they loomed + grandly with the background of purple bank and creamy cloud and shafts + of golden lightning. They seemed like sentinels--guardians of a great + and beautiful love born under their lofty heights, in the lonely + silence of day, in the star-thrown shadow of night. They were like that + love. And they held Lucy and Slone, calling every day, giving a + nameless and tranquil content, binding them true to love, true to the + sage and the open, true to that wild upland home""", metadata={"source": "test_doc_1"}), + Document(page_content= + """Slone and Lucy never rode down so far as the stately monuments, though + these held memories as hauntingly sweet as others were poignantly + bitter. Lucy never rode the King again. But Slone rode him, learned to + love him. And Lucy did not race any more. When Slone tried to stir in + her the old spirit all the response he got was a wistful shake of head + or a laugh that hid the truth or an excuse that the strain on her + ankles from Joel Creech's lasso had never mended. The girl was + unutterably happy, but it was possible that she would never race a + horse again.""", metadata={"source": "test_doc_2"}), + Document(page_content= + """Bostil wanted to be alone, to welcome the King, to lead him back to the + home corral, perhaps to hide from all eyes the change and the uplift + that would forever keep him from wronging another man. + + The late rains came and like magic, in a few days, the sage grew green + and lustrous and fresh, the gray turning to purple. + + Every morning the sun rose white and hot in a blue and cloudless sky. + And then soon the horizon line showed creamy clouds that rose and + spread and darkened. Every afternoon storms hung along the ramparts and + rainbows curved down beautiful and ethereal. The dim blackness of the + storm-clouds was split to the blinding zigzag of lightning, and the + thunder rolled and boomed, like the Colorado in flood.""", metadata={"source": "test_doc_3"}) + ] + ids = retriever.gen_doc_ids(docs) + retriever.add_docs(docs) + retrieved = retriever.store.mget(ids) + assert len(retrieved) == len(ids) + for i, doc in enumerate(docs): + retrieved_doc = json.loads(retrieved[i].decode()) + assert doc.metadata == retrieved_doc.metadata + + +def test_retriever_aadd_docs(): + pass + # # add code folder to sys path # import os # from pathlib import Path From b90a8823d39215226b123553802efff0e9dd26d5 Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Sun, 24 Mar 2024 17:52:50 -0400 Subject: [PATCH 50/53] quantizations all tests passed --- src/grag/quantize/quantize.py | 72 +++++++++++++---------- src/grag/quantize/utils.py | 89 +++++++++++++++++++++-------- src/tests/quantize/quantize_test.py | 37 ++++++++++++ 3 files changed, 146 insertions(+), 52 deletions(-) diff --git a/src/grag/quantize/quantize.py b/src/grag/quantize/quantize.py index 68168a2..64fba47 100644 --- a/src/grag/quantize/quantize.py +++ b/src/grag/quantize/quantize.py @@ -1,3 +1,7 @@ +"""Interactive file for quantizing models.""" + +from pathlib import Path + from grag.components.utils import get_config from grag.quantize.utils import ( building_llamacpp, @@ -7,32 +11,42 @@ ) config = get_config() -root_path = config['quantize']['llama_cpp_path'] - -user_input = input( - "Enter the path to the llama_cpp cloned repo, or where you'd like to clone it. Press Enter to use the default config path: ").strip() - -if user_input != "": - root_path = user_input - -res = get_llamacpp_repo(root_path) - -if "Already up to date." in str(res.stdout): - print("Repository is already up to date. Skipping build.") -else: - print("Updates found. Starting build...") - building_llamacpp(root_path) - -response = input("Do you want us to download the model? (y/n) [Enter for yes]: ").strip().lower() -if response == "n": - print("Please copy the model folder to 'llama.cpp/models/' folder.") - _ = input("Enter if you have already copied the model:") - model_dir = input("Enter the model directory name: ") -elif response == "y" or response == "": - repo_id = input('Please enter the repo_id for the model (you can check on https://huggingface.co/models): ').strip() - fetch_model_repo(repo_id, root_path) - model_dir = repo_id.split('/')[1] - -quantization = input( - "Enter quantization, recommended - Q5_K_M or Q4_K_M for more check https://github.com/ggerganov/llama.cpp/blob/master/examples/quantize/quantize.cpp#L19 : ") -quantize_model(model_dir, quantization, root_path) +root_path = Path(config["quantize"]["llama_cpp_path"]) + +if __name__ == "__main__": + user_input = input( + "Enter the path to the llama_cpp cloned repo, or where you'd like to clone it. Press Enter to use the default config path: " + ).strip() + + if user_input != "": + root_path = Path(user_input) + + res = get_llamacpp_repo(root_path) + + if "Already up to date." in str(res.stdout): + print("Repository is already up to date. Skipping build.") + else: + print("Updates found. Starting build...") + building_llamacpp(root_path) + + response = ( + input("Do you want us to download the model? (y/n) [Enter for yes]: ") + .strip() + .lower() + ) + if response == "n": + print("Please copy the model folder to 'llama.cpp/models/' folder.") + _ = input("Enter if you have already copied the model:") + model_dir = Path(input("Enter the model directory name: ")) + elif response == "y" or response == "": + repo_id = input( + "Please enter the repo_id for the model (you can check on https://huggingface.co/models): " + ).strip() + fetch_model_repo(repo_id, root_path) + # model_dir = repo_id.split('/')[1] + model_dir = root_path / "llama.cpp" / "models" / repo_id.split("/")[1] + + quantization = input( + "Enter quantization, recommended - Q5_K_M or Q4_K_M for more check https://github.com/ggerganov/llama.cpp/blob/master/examples/quantize/quantize.cpp#L19 : " + ) + quantize_model(model_dir, quantization, root_path) diff --git a/src/grag/quantize/utils.py b/src/grag/quantize/utils.py index 8d9d5bc..bc1d280 100644 --- a/src/grag/quantize/utils.py +++ b/src/grag/quantize/utils.py @@ -1,3 +1,5 @@ +"""Utility functions for quantization.""" + import os import subprocess from pathlib import Path @@ -9,7 +11,7 @@ config = get_config() -def get_llamacpp_repo(root_path: str) -> subprocess.CompletedProcess: +def get_llamacpp_repo(root_path: Union[str, Path]) -> subprocess.CompletedProcess: """Clones or pulls the llama.cpp repository into the specified root path. Args: @@ -20,15 +22,27 @@ def get_llamacpp_repo(root_path: str) -> subprocess.CompletedProcess: """ if os.path.exists(f"{root_path}/llama.cpp"): print(f"Repo exists at: {root_path}/llama.cpp") - res = subprocess.run(["git", "-C", f"{root_path}/llama.cpp", "pull"], check=True, capture_output=True) + res = subprocess.run( + ["git", "-C", f"{root_path}/llama.cpp", "pull"], + check=True, + capture_output=True, + ) else: - res = subprocess.run(["git", "clone", "https://github.com/ggerganov/llama.cpp.git", f"{root_path}/llama.cpp"], - check=True, capture_output=True) + res = subprocess.run( + [ + "git", + "clone", + "https://github.com/ggerganov/llama.cpp.git", + f"{root_path}/llama.cpp", + ], + check=True, + capture_output=True, + ) return res -def building_llamacpp(root_path: str) -> None: +def building_llamacpp(root_path: Union[str, Path]) -> None: """Attempts to build the llama.cpp project using make or cmake. Args: @@ -36,24 +50,41 @@ def building_llamacpp(root_path: str) -> None: """ os.chdir(f"{root_path}/llama.cpp/") try: - subprocess.run(['which', 'make'], check=True, stdout=subprocess.DEVNULL) - subprocess.run(['make', 'LLAMA_CUBLAS=1'], check=True) - print('Llama.cpp build successful.') + subprocess.run(["which", "make"], check=True, stdout=subprocess.DEVNULL) + subprocess.run(["make", "LLAMA_CUBLAS=1"], check=True) + print("Llama.cpp build successful.") except subprocess.CalledProcessError: try: - subprocess.run(['which', 'cmake'], check=True, stdout=subprocess.DEVNULL) - subprocess.run(['mkdir', 'build'], check=True) + subprocess.run(["which", "cmake"], check=True, stdout=subprocess.DEVNULL) + subprocess.run(["mkdir", "build"], check=True) subprocess.run( - ['cd', 'build', '&&', 'cmake', '..', '-DLLAMA_CUBLAS=ON', '&&', 'cmake', '--build', '.', '--config', - 'Release'], shell=True, check=True) - print('Llama.cpp build successful.') + [ + "cd", + "build", + "&&", + "cmake", + "..", + "-DLLAMA_CUBLAS=ON", + "&&", + "cmake", + "--build", + ".", + "--config", + "Release", + ], + shell=True, + check=True, + ) + print("Llama.cpp build successful.") except subprocess.CalledProcessError: print("Unable to build, cannot find make or cmake.") finally: - os.chdir(Path(__file__).parent) # Assuming you want to return to the root path after operation + os.chdir( + Path(__file__).parent + ) # Assuming you want to return to the root path after operation -def fetch_model_repo(repo_id: str, root_path: str) -> None: +def fetch_model_repo(repo_id: str, root_path: Union[str, Path]) -> None: """Download model from huggingface.co/models. Args: @@ -62,24 +93,33 @@ def fetch_model_repo(repo_id: str, root_path: str) -> None: """ local_dir = f"{root_path}/llama.cpp/models/{repo_id.split('/')[1]}" os.makedirs(local_dir, exist_ok=True) - snapshot_download(repo_id=repo_id, local_dir=local_dir, local_dir_use_symlinks='auto', resume_download=True) + snapshot_download( + repo_id=repo_id, + local_dir=local_dir, + local_dir_use_symlinks="auto", + resume_download=True, + ) print(f"Model downloaded in {local_dir}") -def quantize_model(model_dir_path: str, quantization: str, root_path: str, - output_dir: Optional[Union[str, Path]] = None) -> None: +def quantize_model( + model_dir_path: Union[str, Path], + quantization: str, + root_path: Union[str, Path], + output_dir: Optional[Union[str, Path]] = None, +) -> None: """Quantizes a specified model using a given quantization level. Args: - output_dir (str, optional): Directory to save quantized model. Defaults to None - model_dir_path (str): The directory path of the model to be quantized. + output_dir (str, Path, optional): Directory to save quantized model. Defaults to None + model_dir_path (str, Path): The directory path of the model to be quantized. quantization (str): The quantization level to apply. - root_path (str): The root directory path of the project. + root_path (str, Path): The root directory path of the project. """ os.chdir(f"{root_path}/llama.cpp/") model_dir_path = Path(model_dir_path) if output_dir is None: - output_dir = config['llm']['base_dir'] + output_dir = config["llm"]["base_dir"] output_dir = Path(output_dir) / model_dir_path.name os.makedirs(output_dir, exist_ok=True) @@ -87,6 +127,9 @@ def quantize_model(model_dir_path: str, quantization: str, root_path: str, subprocess.run(["python3", "convert.py", f"{model_dir_path}/"], check=True) model_file = model_dir_path / "ggml-model-f32.gguf" quantized_model_file = output_dir / f"ggml-model-{quantization}.gguf" - subprocess.run(["./quantize", str(model_file), str(quantized_model_file), quantization], check=True) + subprocess.run( + ["./quantize", str(model_file), str(quantized_model_file), quantization], + check=True, + ) print(f"Quantized model present at {output_dir}") os.chdir(Path(__file__).parent) # Return to the root path after operation diff --git a/src/tests/quantize/quantize_test.py b/src/tests/quantize/quantize_test.py index e69de29..f7b3c51 100644 --- a/src/tests/quantize/quantize_test.py +++ b/src/tests/quantize/quantize_test.py @@ -0,0 +1,37 @@ +import os +from pathlib import Path + +from grag.quantize.utils import ( + building_llamacpp, + fetch_model_repo, + get_llamacpp_repo, + quantize_model, +) + +root_path = Path(__file__).parent / 'test_data' +os.makedirs(root_path, exist_ok=True) + + +def test_get_llamacpp_repo(): + get_llamacpp_repo(root_path) + repo_path = root_path / 'llama.cpp' / '.git' + assert os.path.exists(repo_path) + + +def test_build_llamacpp(): + building_llamacpp(root_path) + bin_path = root_path / 'llama.cpp' / 'quantize' + assert os.path.exists(bin_path) + + +def test_fetch_model_repo(): + fetch_model_repo('meta-llama/Llama-2-7b-chat', root_path) + model_dir_path = root_path / 'llama.cpp' / 'models' / 'Llama-2-7b-chat' + assert os.path.exists(model_dir_path) + + +def test_quantize_model(): + model_dir_path = root_path / 'llama.cpp' / 'models' / 'Llama-2-7b-chat' + quantize_model(model_dir_path, 'Q3_K_M', root_path, output_dir=model_dir_path.parent) + gguf_file_path = model_dir_path / "ggml-model-Q3_K_M.gguf" + assert os.path.exists(gguf_file_path) From 14ca30db4b806996307c0e1de482e482c06b2826 Mon Sep 17 00:00:00 2001 From: sanchitvj Date: Sun, 24 Mar 2024 21:57:48 +0000 Subject: [PATCH 51/53] style fixes by ruff --- src/tests/quantize/quantize_test.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/src/tests/quantize/quantize_test.py b/src/tests/quantize/quantize_test.py index f7b3c51..af0e9dd 100644 --- a/src/tests/quantize/quantize_test.py +++ b/src/tests/quantize/quantize_test.py @@ -8,30 +8,32 @@ quantize_model, ) -root_path = Path(__file__).parent / 'test_data' +root_path = Path(__file__).parent / "test_data" os.makedirs(root_path, exist_ok=True) def test_get_llamacpp_repo(): get_llamacpp_repo(root_path) - repo_path = root_path / 'llama.cpp' / '.git' + repo_path = root_path / "llama.cpp" / ".git" assert os.path.exists(repo_path) def test_build_llamacpp(): building_llamacpp(root_path) - bin_path = root_path / 'llama.cpp' / 'quantize' + bin_path = root_path / "llama.cpp" / "quantize" assert os.path.exists(bin_path) def test_fetch_model_repo(): - fetch_model_repo('meta-llama/Llama-2-7b-chat', root_path) - model_dir_path = root_path / 'llama.cpp' / 'models' / 'Llama-2-7b-chat' + fetch_model_repo("meta-llama/Llama-2-7b-chat", root_path) + model_dir_path = root_path / "llama.cpp" / "models" / "Llama-2-7b-chat" assert os.path.exists(model_dir_path) def test_quantize_model(): - model_dir_path = root_path / 'llama.cpp' / 'models' / 'Llama-2-7b-chat' - quantize_model(model_dir_path, 'Q3_K_M', root_path, output_dir=model_dir_path.parent) + model_dir_path = root_path / "llama.cpp" / "models" / "Llama-2-7b-chat" + quantize_model( + model_dir_path, "Q3_K_M", root_path, output_dir=model_dir_path.parent + ) gguf_file_path = model_dir_path / "ggml-model-Q3_K_M.gguf" assert os.path.exists(gguf_file_path) From 454bb5d4639ea212757307020439df87f0638196 Mon Sep 17 00:00:00 2001 From: arjbingly Date: Sun, 24 Mar 2024 21:57:50 +0000 Subject: [PATCH 52/53] style fixes by ruff --- src/grag/components/multivec_retriever.py | 14 +++++----- src/grag/components/vectordb/base.py | 4 +-- src/grag/components/vectordb/chroma_client.py | 27 ++++++++++--------- .../components/vectordb/deeplake_client.py | 24 ++++++++--------- src/grag/rag/basic_rag.py | 16 +++++------ 5 files changed, 43 insertions(+), 42 deletions(-) diff --git a/src/grag/components/multivec_retriever.py b/src/grag/components/multivec_retriever.py index 9062e69..9fd8664 100644 --- a/src/grag/components/multivec_retriever.py +++ b/src/grag/components/multivec_retriever.py @@ -39,13 +39,13 @@ class Retriever: """ def __init__( - self, - vectordb: Optional[VectorDB] = None, - store_path: str = multivec_retriever_conf["store_path"], - id_key: str = multivec_retriever_conf["id_key"], - namespace: str = multivec_retriever_conf["namespace"], - top_k=1, - client_kwargs: Optional[Dict[str, Any]] = None + self, + vectordb: Optional[VectorDB] = None, + store_path: str = multivec_retriever_conf["store_path"], + id_key: str = multivec_retriever_conf["id_key"], + namespace: str = multivec_retriever_conf["namespace"], + top_k=1, + client_kwargs: Optional[Dict[str, Any]] = None, ): """Initialize the Retriever. diff --git a/src/grag/components/vectordb/base.py b/src/grag/components/vectordb/base.py index 1146d77..b0b0623 100644 --- a/src/grag/components/vectordb/base.py +++ b/src/grag/components/vectordb/base.py @@ -51,7 +51,7 @@ async def aadd_docs(self, docs: List[Document], verbose: bool = True) -> None: @abstractmethod def get_chunk( - self, query: str, with_score: bool = False, top_k: int = None + self, query: str, with_score: bool = False, top_k: int = None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the vector database. @@ -67,7 +67,7 @@ def get_chunk( @abstractmethod async def aget_chunk( - self, query: str, with_score: bool = False, top_k: int = None + self, query: str, with_score: bool = False, top_k: int = None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the vector database (asynchronous). diff --git a/src/grag/components/vectordb/chroma_client.py b/src/grag/components/vectordb/chroma_client.py index 105882c..cac8ab3 100644 --- a/src/grag/components/vectordb/chroma_client.py +++ b/src/grag/components/vectordb/chroma_client.py @@ -3,6 +3,7 @@ This module provides: - ChromaClient """ + from typing import List, Tuple, Union import chromadb @@ -42,15 +43,15 @@ class ChromaClient(VectorDB): """ def __init__( - self, - host=chroma_conf["host"], - port=chroma_conf["port"], - collection_name=chroma_conf["collection_name"], - embedding_type=chroma_conf["embedding_type"], - embedding_model=chroma_conf["embedding_model"], + self, + host=chroma_conf["host"], + port=chroma_conf["port"], + collection_name=chroma_conf["collection_name"], + embedding_type=chroma_conf["embedding_type"], + embedding_model=chroma_conf["embedding_model"], ): """Initialize a ChromaClient object. - + Args: host: IP Address of hosted Chroma Vectorstore, defaults to argument from config file port: port address of hosted Chroma Vectorstore, defaults to argument from config file @@ -124,7 +125,7 @@ def add_docs(self, docs: List[Document], verbose=True) -> None: """ docs = self._filter_metadata(docs) for doc in ( - tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs + tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs ): _id = self.langchain_client.add_documents([doc]) @@ -141,9 +142,9 @@ async def aadd_docs(self, docs: List[Document], verbose=True) -> None: docs = self._filter_metadata(docs) if verbose: for doc in atqdm( - docs, - desc=f"Adding documents to {self.collection_name}", - total=len(docs), + docs, + desc=f"Adding documents to {self.collection_name}", + total=len(docs), ): await self.langchain_client.aadd_documents([doc]) else: @@ -151,7 +152,7 @@ async def aadd_docs(self, docs: List[Document], verbose=True) -> None: await self.langchain_client.aadd_documents([doc]) def get_chunk( - self, query: str, with_score: bool = False, top_k: int = None + self, query: str, with_score: bool = False, top_k: int = None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the chroma database. @@ -174,7 +175,7 @@ def get_chunk( ) async def aget_chunk( - self, query: str, with_score=False, top_k=None + self, query: str, with_score=False, top_k=None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most (cosine) similar chunks from the vector database, asynchronously. diff --git a/src/grag/components/vectordb/deeplake_client.py b/src/grag/components/vectordb/deeplake_client.py index 2cb0270..f0d5ba5 100644 --- a/src/grag/components/vectordb/deeplake_client.py +++ b/src/grag/components/vectordb/deeplake_client.py @@ -39,12 +39,12 @@ class DeepLakeClient(VectorDB): """ def __init__( - self, - collection_name: str = deeplake_conf["collection_name"], - store_path: Union[str, Path] = deeplake_conf["store_path"], - embedding_type: str = deeplake_conf["embedding_type"], - embedding_model: str = deeplake_conf["embedding_model"], - read_only: bool = False, + self, + collection_name: str = deeplake_conf["collection_name"], + store_path: Union[str, Path] = deeplake_conf["store_path"], + embedding_type: str = deeplake_conf["embedding_type"], + embedding_model: str = deeplake_conf["embedding_model"], + read_only: bool = False, ): """Initialize DeepLake client object.""" self.store_path = Path(store_path) @@ -86,7 +86,7 @@ def add_docs(self, docs: List[Document], verbose=True) -> None: """ docs = self._filter_metadata(docs) for doc in ( - tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs + tqdm(docs, desc=f"Adding to {self.collection_name}:") if verbose else docs ): _id = self.langchain_client.add_documents([doc]) @@ -103,9 +103,9 @@ async def aadd_docs(self, docs: List[Document], verbose=True) -> None: docs = self._filter_metadata(docs) if verbose: for doc in atqdm( - docs, - desc=f"Adding documents to {self.collection_name}", - total=len(docs), + docs, + desc=f"Adding documents to {self.collection_name}", + total=len(docs), ): await self.langchain_client.aadd_documents([doc]) else: @@ -113,7 +113,7 @@ async def aadd_docs(self, docs: List[Document], verbose=True) -> None: await self.langchain_client.aadd_documents([doc]) def get_chunk( - self, query: str, with_score: bool = False, top_k: int = None + self, query: str, with_score: bool = False, top_k: int = None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the deeplake database. @@ -136,7 +136,7 @@ def get_chunk( ) async def aget_chunk( - self, query: str, with_score=False, top_k=None + self, query: str, with_score=False, top_k=None ) -> Union[List[Document], List[Tuple[Document, float]]]: """Returns the most similar chunks from the deeplake database, asynchronously. diff --git a/src/grag/rag/basic_rag.py b/src/grag/rag/basic_rag.py index cdad471..da461b6 100644 --- a/src/grag/rag/basic_rag.py +++ b/src/grag/rag/basic_rag.py @@ -31,14 +31,14 @@ class BasicRAG: """ def __init__( - self, - retriever: Optional[Retriever] = None, - model_name=None, - doc_chain="stuff", - task="QA", - llm_kwargs=None, - retriever_kwargs=None, - custom_prompt: Union[Prompt, FewShotPrompt, None] = None, + self, + retriever: Optional[Retriever] = None, + model_name=None, + doc_chain="stuff", + task="QA", + llm_kwargs=None, + retriever_kwargs=None, + custom_prompt: Union[Prompt, FewShotPrompt, None] = None, ): if retriever is None: if retriever_kwargs is None: From 685403f303bddec7eff4adace5968f2a3ed9621d Mon Sep 17 00:00:00 2001 From: Arjun Bingly Date: Sun, 24 Mar 2024 22:00:45 -0400 Subject: [PATCH 53/53] Create LICENSE --- LICENSE | 661 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 661 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +.