Gourisankar Padihary commited on
Commit
bd69eee
·
1 Parent(s): 44ca925

Added logging and generated response

Browse files
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ venv/
2
+ __pycache__/
data/load_dataset.py CHANGED
@@ -1,4 +1,8 @@
 
1
  from datasets import load_dataset
2
 
3
  def load_data():
4
- return load_dataset("rungalileo/ragbench", 'covidqa', split="train")
 
 
 
 
1
+ import logging
2
  from datasets import load_dataset
3
 
4
  def load_data():
5
+ logging.info("Loading dataset")
6
+ dataset = load_dataset("rungalileo/ragbench", 'covidqa', split="train")
7
+ logging.info("Dataset loaded successfully")
8
+ return dataset
generator/create_prompt.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.docstore.document import Document
2
+
3
+ def create_prompt(documents, question, response):
4
+ prompt = f""" I asked someone to answer a question based on one or more documents. Your task is to review their response and assess whether or not each sentence in that response is supported by text in the documents. If supported, identify which sentences in the documents provide that support. Additionally, identify which documents contain useful information for answering the question, and which documents the answer was sourced from.
5
+
6
+ Here are the documents, each split into sentences with associated keys:
7
+ {documents}
8
+
9
+ The question was:
10
+ {question}
11
+
12
+ Here is their response, split into sentences with associated keys:
13
+ {response}
14
+
15
+ Provide a JSON response with an answer , relevance_explanation, all_relevant_sentence_keys, overall_supported_explanation, overall_supported, sentence_support_information(this can be a json inside a json and with these fields response_sentence_key, explanation, supporting_sentence_keys, fully_supported) and all_utilized_sentence_keys below are the definitions
16
+
17
+ You must respond with a JSON object matching this schema:
18
+
19
+ {{
20
+ "answer": "string",
21
+ "relevance_explanation": "string",
22
+ "all_relevant_sentence_keys": ["string"],
23
+ "overall_supported_explanation": "string",
24
+ "overall_supported": "boolean",
25
+ "sentence_support_information": [
26
+ {{
27
+ "response_sentence_key": "string",
28
+ "explanation": "string",
29
+ "supporting_sentence_keys": ["string"],
30
+ "fully_supported": "boolean"
31
+ }},
32
+ ],
33
+ "all_utilized_sentence_keys": ["string"]
34
+ }}
35
+
36
+ The relevance_explanation field is a string explaining which documents
37
+ contain useful information for answering the question. Provide a step-by-step
38
+ breakdown of information provided in the documents and how it is useful for
39
+ answering the question.
40
+ The all_relevant_sentence_keys field is a list of all document sentences keys
41
+ (e.g. ’0a’) that are revant to the question. Include every sentence that is
42
+ useful and relevant to the question, even if it was not used in the response,
43
+ or if only parts of the sentence are useful. Ignore the provided response when
44
+ making this judgement and base your judgement solely on the provided documents
45
+ and question. Omit sentences that, if removed from the document, would not
46
+ impact someone’s ability to answer the question.
47
+ The overall_supported_explanation field is a string explaining why the response
48
+ *as a whole* is or is not supported by the documents. In this field, provide a
49
+ step-by-step breakdown of the claims made in the response and the support (or
50
+ lack thereof) for those claims in the documents. Begin by assessing each claim
51
+ separately, one by one; don’t make any remarks about the response as a whole
52
+ until you have assessed all the claims in isolation.
53
+ The overall_supported field is a boolean indicating whether the response as a
54
+ whole is supported by the documents. This value should reflect the conclusion
55
+ you drew at the end of your step-by-step breakdown in overall_supported_explanation.
56
+ In the sentence_support_information field, provide information about the support
57
+ *for each sentence* in the response.
58
+ The sentence_support_information field is a list of objects, one for each sentence
59
+ in the response. Each object MUST have the following fields:
60
+ - response_sentence_key: a string identifying the sentence in the response.
61
+ This key is the same as the one used in the response above.
62
+ 16
63
+ - explanation: a string explaining why the sentence is or is not supported by the
64
+ documents.
65
+ - supporting_sentence_keys: keys (e.g. ’0a’) of sentences from the documents that
66
+ support the response sentence. If the sentence is not supported, this list MUST
67
+ be empty. If the sentence is supported, this list MUST contain one or more keys.
68
+ In special cases where the sentence is supported, but not by any specific sentence,
69
+ you can use the string "supported_without_sentence" to indicate that the sentence
70
+ is generally supported by the documents. Consider cases where the sentence is
71
+ expressing inability to answer the question due to lack of relevant information in
72
+ the provided contex as "supported_without_sentence". In cases where the sentence
73
+ is making a general statement (e.g. outlining the steps to produce an answer, or
74
+ summarizing previously stated sentences, or a transition sentence), use the
75
+ sting "general".In cases where the sentence is correctly stating a well-known fact,
76
+ like a mathematical formula, use the string "well_known_fact". In cases where the
77
+ sentence is performing numerical reasoning (e.g. addition, multiplication), use
78
+ the string "numerical_reasoning".
79
+ - fully_supported: a boolean indicating whether the sentence is fully supported by
80
+ the documents.
81
+ - This value should reflect the conclusion you drew at the end of your step-by-step
82
+ breakdown in explanation.
83
+ - If supporting_sentence_keys is an empty list, then fully_supported must be false.
84
+ - Otherwise, use fully_supported to clarify whether everything in the response
85
+ sentence is fully supported by the document text indicated in supporting_sentence_keys
86
+ (fully_supported = true), or whether the sentence is only partially or incompletely
87
+ supported by that document text (fully_supported = false).
88
+ The all_utilized_sentence_keys field is a list of all sentences keys (e.g. ’0a’) that
89
+ were used to construct the answer. Include every sentence that either directly supported
90
+ the answer, or was implicitly used to construct the answer, even if it was not used
91
+ in its entirety. Omit sentences that were not used, and could have been removed from
92
+ the documents without affecting the answer.
93
+ You must respond with a valid JSON string. Use escapes for quotes, e.g. ‘\\"‘, and
94
+ newlines, e.g. ‘\\n‘. Do not write anything before or after the JSON string. Do not
95
+ wrap the JSON string in backticks like ‘‘‘ or ‘‘‘json.
96
+ As a reminder: your task is to review the response and assess which documents contain
97
+ useful information pertaining to the question, and how each sentence in the response
98
+ is supported by the text in the documents.
99
+
100
+ """
101
+ return prompt
102
+ prompt = f""" I asked someone to answer a question based on one or more documents. Your task is to review their response and assess whether or not each sentence in that response is supported by text in the documents. If supported, identify which sentences in the documents provide that support. Additionally, identify which documents contain useful information for answering the question, and which documents the answer was sourced from.
103
+
104
+ Here are the documents, each split into sentences with associated keys:
105
+ {documents}
106
+
107
+ The question was:
108
+ {question}
109
+
110
+ Here is their response, split into sentences with associated keys:
111
+ {response}
112
+
113
+ Provide a JSON response with an answer , relevance_explanation, all_relevant_sentence_keys, overall_supported_explanation, overall_supported, sentence_support_information(this can be a json inside a json and with these fields response_sentence_key, explanation, supporting_sentence_keys, fully_supported) and all_utilized_sentence_keys below are the definitions
114
+
115
+ You must respond with a JSON object matching this schema:
116
+
117
+ {{
118
+ "answer": "string",
119
+ "relevance_explanation": "string",
120
+ "all_relevant_sentence_keys": ["string"],
121
+ "overall_supported_explanation": "string",
122
+ "overall_supported": "boolean",
123
+ "sentence_support_information": [
124
+ {{
125
+ "response_sentence_key": "string",
126
+ "explanation": "string",
127
+ "supporting_sentence_keys": ["string"],
128
+ "fully_supported": "boolean"
129
+ }},
130
+ ],
131
+ "all_utilized_sentence_keys": ["string"]
132
+ }}
133
+ """
134
+ return prompt
generator/extract_attributes.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from generator.create_prompt import create_prompt
3
+ from generator.initialize_llm import initialize_llm
4
+
5
+ # Initialize the LLM
6
+ llm = initialize_llm()
7
+
8
+ # Function to extract attributes
9
+ def extract_attributes(question, relevant_docs, response):
10
+ # Format documents into a string by accessing the `page_content` attribute of each Document
11
+ formatted_documents = "\n".join([f"Doc {i+1}: {doc.page_content}" for i, doc in enumerate(relevant_docs)])
12
+
13
+ attribute_prompt = create_prompt(formatted_documents, question, response)
14
+
15
+ # Instead of using BaseMessage, pass the formatted prompt directly to invoke
16
+ result = llm.invoke(attribute_prompt)
17
+
18
+ return result
generator/generate_response.py CHANGED
@@ -1,6 +1,7 @@
1
  from langchain.chains import RetrievalQA
2
 
3
  def generate_response(llm, vector_store, question):
 
4
  qa_chain = RetrievalQA.from_chain_type(
5
  llm=llm,
6
  retriever=vector_store.as_retriever(),
 
1
  from langchain.chains import RetrievalQA
2
 
3
  def generate_response(llm, vector_store, question):
4
+ # Create a retrieval-based question-answering chain using the relevant documents
5
  qa_chain = RetrievalQA.from_chain_type(
6
  llm=llm,
7
  retriever=vector_store.as_retriever(),
main.py CHANGED
@@ -1,35 +1,70 @@
 
1
  from data.load_dataset import load_data
2
  from retriever.chunk_documents import chunk_documents
3
  from retriever.embed_documents import embed_documents
4
  from retriever.retrieve_documents import retrieve_top_k_documents
5
  from generator.initialize_llm import initialize_llm
6
  from generator.generate_response import generate_response
 
 
 
 
7
 
8
  def main():
 
 
9
  # Load the dataset
10
  dataset = load_data()
11
-
 
12
  # Chunk the dataset
13
  documents = chunk_documents(dataset)
14
-
 
15
  # Embed the documents
16
  vector_store = embed_documents(documents)
17
-
 
18
  # Initialize the LLM
19
  llm = initialize_llm()
20
-
 
21
  # Sample question
22
  sample_question = dataset[0]['question']
23
-
 
24
  # Retrieve relevant documents
25
  relevant_docs = retrieve_top_k_documents(vector_store, sample_question, top_k=5)
26
-
27
- # Generate a response
 
 
 
 
28
  response, source_docs = generate_response(llm, vector_store, sample_question)
29
-
 
30
  # Print the response
31
  print(f"Response: {response}")
32
  print(f"Source Documents: {source_docs}")
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  if __name__ == "__main__":
35
  main()
 
1
+ import logging, json
2
  from data.load_dataset import load_data
3
  from retriever.chunk_documents import chunk_documents
4
  from retriever.embed_documents import embed_documents
5
  from retriever.retrieve_documents import retrieve_top_k_documents
6
  from generator.initialize_llm import initialize_llm
7
  from generator.generate_response import generate_response
8
+ from generator.extract_attributes import extract_attributes
9
+
10
+ # Configure logging
11
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
12
 
13
  def main():
14
+ logging.info("Starting the RAG pipeline")
15
+
16
  # Load the dataset
17
  dataset = load_data()
18
+ logging.info("Dataset loaded")
19
+
20
  # Chunk the dataset
21
  documents = chunk_documents(dataset)
22
+ logging.info("Documents chunked")
23
+
24
  # Embed the documents
25
  vector_store = embed_documents(documents)
26
+ logging.info("Documents embedded")
27
+
28
  # Initialize the LLM
29
  llm = initialize_llm()
30
+ logging.info("LLM initialized")
31
+
32
  # Sample question
33
  sample_question = dataset[0]['question']
34
+ logging.info(f"Sample question: {sample_question}")
35
+
36
  # Retrieve relevant documents
37
  relevant_docs = retrieve_top_k_documents(vector_store, sample_question, top_k=5)
38
+ logging.info("Relevant documents retrieved :", print(len(relevant_docs)))
39
+ # Log each retrieved document individually
40
+ #for i, doc in enumerate(relevant_docs):
41
+ #logging.info(f"Relevant document {i+1}: {doc}")
42
+
43
+ # Generate a response using the relevant documents
44
  response, source_docs = generate_response(llm, vector_store, sample_question)
45
+ logging.info("Response generated")
46
+
47
  # Print the response
48
  print(f"Response: {response}")
49
  print(f"Source Documents: {source_docs}")
50
 
51
+ # Extract attributes from the response and source documents
52
+ attributes = extract_attributes(sample_question, relevant_docs, response)
53
+
54
+ # Only proceed if the content is not empty
55
+ if attributes.content:
56
+ result_content = attributes.content # Access the content attribute
57
+
58
+ # Extract the JSON part from the result_content
59
+ json_start = result_content.find("{")
60
+ json_end = result_content.rfind("}") + 1
61
+ json_str = result_content[json_start:json_end]
62
+
63
+ try:
64
+ result_json = json.loads(json_str)
65
+ print(json.dumps(result_json, indent=2))
66
+ except json.JSONDecodeError as e:
67
+ logging.error(f"JSONDecodeError: {e}")
68
+
69
  if __name__ == "__main__":
70
  main()
requirements.txt CHANGED
@@ -6,5 +6,5 @@ sentence-transformers
6
  langchain
7
  llama-index
8
  langchain-community
9
- groq-sdk
10
- langchain_groq
 
6
  langchain
7
  llama-index
8
  langchain-community
9
+ langchain_groq
10
+ langchain-huggingface
retriever/embed_documents.py CHANGED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from langchain_huggingface import HuggingFaceEmbeddings
2
+ from langchain_community.vectorstores import FAISS
3
+
4
+ def embed_documents(documents):
5
+ embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
6
+ vector_store = FAISS.from_texts([doc['text'] for doc in documents], embedding_model)
7
+ return vector_store