Spaces:
Running
Running
Saiteja Solleti
commited on
Commit
Β·
411adbd
1
Parent(s):
a46269a
calculate scores added
Browse files- app.py +9 -1
- calculatescorehelper.py +146 -0
- finetuneresults.py +1 -1
- generationhelper.py +35 -1
app.py
CHANGED
@@ -7,6 +7,8 @@ from insertmilvushelper import EmbedAllDocumentsAndInsert
|
|
7 |
from sentence_transformers import SentenceTransformer
|
8 |
from searchmilvushelper import SearchTopKDocuments
|
9 |
from finetuneresults import FineTuneAndRerankSearchResults
|
|
|
|
|
10 |
|
11 |
from model import generate_response
|
12 |
from huggingface_hub import login
|
@@ -17,6 +19,8 @@ from huggingface_hub import dataset_info
|
|
17 |
# Load embedding model
|
18 |
QUERY_EMBEDDING_MODEL = SentenceTransformer('all-MiniLM-L6-v2')
|
19 |
RERANKING_MODEL = "cross-encoder/ms-marco-MiniLM-L-6-v2"
|
|
|
|
|
20 |
WINDOW_SIZE = 5
|
21 |
OVERLAP = 2
|
22 |
RETRIVE_TOP_K_SIZE=10
|
@@ -44,7 +48,11 @@ results_for_top10_chunks = SearchTopKDocuments(db_collection, query, QUERY_EMBED
|
|
44 |
|
45 |
reranked_results = FineTuneAndRerankSearchResults(results_for_top10_chunks, rag_extracted_data, query, RERANKING_MODEL)
|
46 |
|
47 |
-
|
|
|
|
|
|
|
|
|
48 |
|
49 |
|
50 |
def chatbot(prompt):
|
|
|
7 |
from sentence_transformers import SentenceTransformer
|
8 |
from searchmilvushelper import SearchTopKDocuments
|
9 |
from finetuneresults import FineTuneAndRerankSearchResults
|
10 |
+
from generationhelper import GenerateAnswer
|
11 |
+
from calculatescorehelper import CalculateScoresBasedOnAnswer
|
12 |
|
13 |
from model import generate_response
|
14 |
from huggingface_hub import login
|
|
|
19 |
# Load embedding model
|
20 |
QUERY_EMBEDDING_MODEL = SentenceTransformer('all-MiniLM-L6-v2')
|
21 |
RERANKING_MODEL = "cross-encoder/ms-marco-MiniLM-L-6-v2"
|
22 |
+
PROMPT_MODEL = "llama-3.3-70b-specdec"
|
23 |
+
EVAL_MODEL = "llama-3.3-70b-specdec"
|
24 |
WINDOW_SIZE = 5
|
25 |
OVERLAP = 2
|
26 |
RETRIVE_TOP_K_SIZE=10
|
|
|
48 |
|
49 |
reranked_results = FineTuneAndRerankSearchResults(results_for_top10_chunks, rag_extracted_data, query, RERANKING_MODEL)
|
50 |
|
51 |
+
answer = GenerateAnswer(query, reranked_results.head(3), PROMPT_MODEL)
|
52 |
+
|
53 |
+
completion_result = CalculateScoresBasedOnAnswer(query, reranked_results.head(1), answer, EVAL_MODEL)
|
54 |
+
|
55 |
+
print(completion_result)
|
56 |
|
57 |
|
58 |
def chatbot(prompt):
|
calculatescorehelper.py
ADDED
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import generationhelper
|
2 |
+
|
3 |
+
def evaluate_response_with_prompt(templete, query, documents, answer, eval_model="llama-3.3-70b-specdec"):
|
4 |
+
|
5 |
+
formatted_documents = ""
|
6 |
+
for doc_idx, doc_text in enumerate(documents["document"]):
|
7 |
+
if isinstance(doc_text, list):
|
8 |
+
doc_text = " ".join(doc_text) # Convert list to a single string
|
9 |
+
sentences = doc_text.split('. ')
|
10 |
+
formatted_documents += "\n".join([f"{doc_idx}{chr(97 + i)}. {sent}" for i, sent in enumerate(sentences)]) + "\n"
|
11 |
+
|
12 |
+
# Format response with unique keys (a, b, c)
|
13 |
+
formatted_answer = "\n".join([f"{chr(97 + i)}. {sent}" for i, sent in enumerate(answer.split('. '))])
|
14 |
+
|
15 |
+
prompt = templete.format(documents=formatted_documents, question=query, answer=formatted_answer)
|
16 |
+
|
17 |
+
# Call the LLM API (Llama 3.3-70B)
|
18 |
+
completion = generationhelper.groq_client.chat.completions.create(
|
19 |
+
model=eval_model,
|
20 |
+
messages=[{"role": "user", "content": prompt}],
|
21 |
+
temperature=0.7,
|
22 |
+
max_tokens=2048,
|
23 |
+
top_p=1
|
24 |
+
)
|
25 |
+
|
26 |
+
print("\nGenerated Response:\n", completion)
|
27 |
+
|
28 |
+
return completion
|
29 |
+
|
30 |
+
def CalculateScoresBasedOnAnswer(query, documents, answer, eval_model):
|
31 |
+
templete= get_templet_to_calculatescores()
|
32 |
+
|
33 |
+
completion_results = evaluate_response_with_prompt(templete, query,documents, answer, eval_model)
|
34 |
+
|
35 |
+
print(completion_results)
|
36 |
+
|
37 |
+
return completion_results
|
38 |
+
|
39 |
+
|
40 |
+
|
41 |
+
def get_templet_to_calculatescores():
|
42 |
+
return """
|
43 |
+
You asked someone to answer a question based on one or more documents.
|
44 |
+
Your task is to review their response and assess whether or not each sentence
|
45 |
+
in that response is supported by text in the documents. And if so, which
|
46 |
+
sentences in the documents provide that support. You will also tell me which
|
47 |
+
of the documents contain useful information for answering the question, and
|
48 |
+
which of the documents the answer was sourced from.
|
49 |
+
Here are the documents, each of which is split into sentences. Alongside each
|
50 |
+
sentence is an associated key, such as '0a.' or '0b.' that you can use to refer
|
51 |
+
to it:
|
52 |
+
βββ
|
53 |
+
{documents}
|
54 |
+
βββ
|
55 |
+
The question was:
|
56 |
+
βββ
|
57 |
+
{question}
|
58 |
+
βββ
|
59 |
+
Here is their response, split into sentences. Alongside each sentence is
|
60 |
+
an associated key, such as 'a.' or 'b.' that you can use to refer to it. Note
|
61 |
+
that these keys are unique to the response, and are not related to the keys
|
62 |
+
in the documents:
|
63 |
+
βββ
|
64 |
+
{answer}
|
65 |
+
βββ
|
66 |
+
You must respond with a JSON object matching this schema:
|
67 |
+
βββ
|
68 |
+
{{
|
69 |
+
"relevance_explanation": string,
|
70 |
+
"all_relevant_sentence_keys": [string],
|
71 |
+
"overall_supported_explanation": string,
|
72 |
+
"overall_supported": boolean,
|
73 |
+
"sentence_support_information": [
|
74 |
+
{{
|
75 |
+
"response_sentence_key": string,
|
76 |
+
"explanation": string,
|
77 |
+
"supporting_sentence_keys": [string],
|
78 |
+
"fully_supported": boolean
|
79 |
+
}},
|
80 |
+
],
|
81 |
+
"all_utilized_sentence_keys": [string]
|
82 |
+
}}
|
83 |
+
βββ
|
84 |
+
The relevance_explanation field is a string explaining which documents
|
85 |
+
contain useful information for answering the question. Provide a step-by-step
|
86 |
+
breakdown of information provided in the documents and how it is useful for
|
87 |
+
answering the question.
|
88 |
+
The all_relevant_sentence_keys field is a list of all document sentences keys
|
89 |
+
(e.g. '0a') that are relevant to the question. Include every sentence that is
|
90 |
+
useful and relevant to the question, even if it was not used in the response,
|
91 |
+
or if only parts of the sentence are useful. Ignore the provided response when
|
92 |
+
making this judgment and base your judgment solely on the provided documents
|
93 |
+
and question. Omit sentences that, if removed from the document, would not
|
94 |
+
impact someone's ability to answer the question.
|
95 |
+
The overall_supported_explanation field is a string explaining why the response
|
96 |
+
*as a whole* is or is not supported by the documents. In this field, provide a
|
97 |
+
step-by-step breakdown of the claims made in the response and the support (or
|
98 |
+
lack thereof) for those claims in the documents. Begin by assessing each claim
|
99 |
+
separately, one by one; don't make any remarks about the response as a whole
|
100 |
+
until you have assessed all the claims in isolation.
|
101 |
+
The overall_supported field is a boolean indicating whether the response as a
|
102 |
+
whole is supported by the documents. This value should reflect the conclusion
|
103 |
+
you drew at the end of your step-by-step breakdown in overall_supported_explanation.
|
104 |
+
In the sentence_support_information field, provide information about the support
|
105 |
+
*for each sentence* in the response.
|
106 |
+
The sentence_support_information field is a list of objects, one for each sentence
|
107 |
+
in the response. Each object MUST have the following fields:
|
108 |
+
- response_sentence_key: a string identifying the sentence in the response.
|
109 |
+
This key is the same as the one used in the response above.
|
110 |
+
- explanation: a string explaining why the sentence is or is not supported by the
|
111 |
+
documents.
|
112 |
+
- supporting_sentence_keys: keys (e.g. '0a') of sentences from the documents that
|
113 |
+
support the response sentence. If the sentence is not supported, this list MUST
|
114 |
+
be empty. If the sentence is supported, this list MUST contain one or more keys.
|
115 |
+
In special cases where the sentence is supported, but not by any specific sentence,
|
116 |
+
you can use the string "supported_without_sentence" to indicate that the sentence
|
117 |
+
is generally supported by the documents. Consider cases where the sentence is
|
118 |
+
expressing inability to answer the question due to lack of relevant information in
|
119 |
+
the provided context as "supported_without_sentence". In cases where the
|
120 |
+
sentence is making a general statement (e.g. outlining the steps to produce an answer, or
|
121 |
+
summarizing previously stated sentences, or a transition sentence), use the
|
122 |
+
string "general". In cases where the sentence is correctly stating a well-known fact,
|
123 |
+
like a mathematical formula, use the string "well_known_fact". In cases where the
|
124 |
+
sentence is performing numerical reasoning (e.g. addition, multiplication), use the
|
125 |
+
string "numerical_reasoning".
|
126 |
+
- fully_supported: a boolean indicating whether the sentence is fully supported by
|
127 |
+
the documents.
|
128 |
+
- This value should reflect the conclusion you drew at the end of your step-by-step
|
129 |
+
breakdown in explanation.
|
130 |
+
- If supporting_sentence_keys is an empty list, then fully_supported must be false.
|
131 |
+
- Otherwise, use fully_supported to clarify whether everything in the response
|
132 |
+
sentence is fully supported by the document text indicated in supporting_sentence_keys
|
133 |
+
(fully_supported = true), or whether the sentence is only partially or incompletely
|
134 |
+
supported by that document text (fully_supported = false).
|
135 |
+
The all_utilized_sentence_keys field is a list of all sentences keys (e.g. '0a') that
|
136 |
+
were used to construct the answer. Include every sentence that either directly supported
|
137 |
+
the answer, or was implicitly used to construct the answer, even if it was not used
|
138 |
+
in its entirety. Omit sentences that were not used and could have been removed from
|
139 |
+
the documents without affecting the answer.
|
140 |
+
You must respond with a valid JSON string. Use escapes for quotes, e.g. '\\\\"', and
|
141 |
+
newlines, e.g. '\\\\n'. Do not write anything before or after the JSON string. Do not
|
142 |
+
wrap the JSON string in backticks like '\\`' or '\\`json.
|
143 |
+
As a reminder: your task is to review the response and assess which documents contain
|
144 |
+
useful information pertaining to the question, and how each sentence in the response
|
145 |
+
is supported by the text in the documents.
|
146 |
+
"""
|
finetuneresults.py
CHANGED
@@ -58,4 +58,4 @@ def rerank_documents(query, retrieved_docs_df, model_name="cross-encoder/ms-marc
|
|
58 |
def FineTuneAndRerankSearchResults(top_10_chunk_results, rag_extarcted_data, question, reranking_model):
|
59 |
unique_docs= retrieve_full_documents(top_10_chunk_results, rag_extarcted_data)
|
60 |
reranked_results = rerank_documents(question, unique_docs, reranking_model)
|
61 |
-
return
|
|
|
58 |
def FineTuneAndRerankSearchResults(top_10_chunk_results, rag_extarcted_data, question, reranking_model):
|
59 |
unique_docs= retrieve_full_documents(top_10_chunk_results, rag_extarcted_data)
|
60 |
reranked_results = rerank_documents(question, unique_docs, reranking_model)
|
61 |
+
return reranked_results
|
generationhelper.py
CHANGED
@@ -5,4 +5,38 @@ groq_token = os.getenv("GROQ_TOKEN")
|
|
5 |
|
6 |
groq_client = Groq(
|
7 |
api_key = groq_token
|
8 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
groq_client = Groq(
|
7 |
api_key = groq_token
|
8 |
+
)
|
9 |
+
|
10 |
+
|
11 |
+
def GenerateAnswer(query, top_documents, prompt_model="llama-3.3-70b-specdec"):
|
12 |
+
"""
|
13 |
+
Generates an answer using an AI model based on the top retrieved documents.
|
14 |
+
"""
|
15 |
+
# Convert each document (if it's a list) into a string before joining
|
16 |
+
documents = "\n\n".join([" ".join(doc) if isinstance(doc, list) else str(doc) for doc in top_documents["document"]])
|
17 |
+
|
18 |
+
# Construct the prompt
|
19 |
+
prompt = f"""
|
20 |
+
You are an AI assistant tasked with answering a question based on the information provided in the given documents. Your response should be accurate, concise, and directly address the question using only the information from the documents. If the documents do not contain sufficient information to answer the question, state that clearly.
|
21 |
+
|
22 |
+
Documents:
|
23 |
+
{documents}
|
24 |
+
|
25 |
+
Question: {query}
|
26 |
+
Answer:
|
27 |
+
"""
|
28 |
+
|
29 |
+
# Call Groq API (Llama 3.3-70B)
|
30 |
+
completion = groq_client.chat.completions.create(
|
31 |
+
model=prompt_model,
|
32 |
+
messages=[{"role": "user", "content": prompt}],
|
33 |
+
temperature=0.7,
|
34 |
+
max_tokens=2048,
|
35 |
+
top_p=1
|
36 |
+
)
|
37 |
+
|
38 |
+
# Extract and print the response
|
39 |
+
response_text = completion.choices[0].message.content
|
40 |
+
print("\nGenerated Response:\n", response_text)
|
41 |
+
|
42 |
+
return response_text
|