forked from juminsuh/Team5_NLP_Upstage
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
297 lines (226 loc) · 7.75 KB
/
Copy pathutils.py
File metadata and controls
297 lines (226 loc) · 7.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
import os
import re
import pandas as pd
from dotenv import load_dotenv
from prompts import *
from langchain_community.vectorstores import FAISS
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.vectorstores import FAISS
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.prompts import PromptTemplate
from langchain_community.retrievers import BM25Retriever
def load_api_key():
load_dotenv('.env', override=True)
UPSTAGE_API_KEY = os.getenv("UPSTAGE_API_KEY")
return UPSTAGE_API_KEY
def format_docs(docs):
return '\n\n'.join(doc.page_content for doc in docs)
def extract_answer(response):
"""
extracts the answer from the response using a regular expression.
expected format: "[ANSWER]: (A) convolutional networks"
if there are any answers formatted like the format, it returns None.
"""
pattern = r"\[ANSWER\]:\s*\((A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|W|Z)\)"
matches = re.findall(pattern, response)
if matches:
return matches[-1] # return last matching
else:
return extract_again(response)
def extract_again(response):
pattern = r"\b[A-J]\b"
matches = re.findall(pattern, response)
if matches:
return matches[-1]
else:
return None
def read_data(data_path):
data = pd.read_csv(data_path)
prompts = data['prompts']
answers = data['answers']
# returns two lists: prompts and answers
return prompts, answers
def read_data_for_final(data_path):
data = pd.read_csv(data_path)
prompts = data['question']
answers = data['your_answer']
# returns two lists: prompts and answers
return prompts, answers
def route(llm, prompt):
prompt_template = PromptTemplate.from_template(DOMAIN_PROMPT)
chain = prompt_template | llm
response = chain.invoke({"question": prompt})
return response.content
def parse_question_and_choices(prompt):
# extract question+options
question_match = re.search(r'QUESTION\d+\)\s*(.*?)(?=\([A-Z]\))', prompt, re.DOTALL)
if not question_match:
raise ValueError("질문을 찾을 수 없습니다.")
question = question_match.group(1).strip()
# extract options
choice_pattern = r'\(([A-Z])\)\s*(.*?)(?=\([A-Z]\)|$)'
choices_matches = re.finditer(choice_pattern, prompt, re.DOTALL)
choices = []
for match in choices_matches:
label = match.group(1)
text = match.group(2).strip()
choices.append({
'label': label,
'text': text
})
return question, choices
def ewha_context(query_embedding, search_type, k, lambda_mult, fetch_k, prompt):
# load db
db = FAISS.load_local("./faiss_vectorstore/ewha",
query_embedding,
allow_dangerous_deserialization=True)
# retriever
retriever = db.as_retriever(search_type=search_type,
search_kwargs={'k': k, 'lambda_mult': lambda_mult, 'fetch_k': fetch_k})
# parse question & choice
q, choice_list = parse_question_and_choices(prompt)
context = ""
# implement rag for each choice
for _, choice in enumerate(choice_list):
qa = f"{q}\n{choice}"
docs = retriever.invoke(qa)
for doc in docs:
if doc.page_content not in context: # prevent duplication
context += f'\n\n{doc.page_content}'
return context
def mmlu_context(routed_result, embedding_model, search_type, k, lambda_mult, fetch_k, prompt):
# ---- Load FAISS DB ----
db = FAISS.load_local(
f"./faiss_vectorstore/{routed_result}",
embedding_model,
allow_dangerous_deserialization=True
)
# ---- Dense Retriever (FAISS) ----
dense_retriever = db.as_retriever(
search_type=search_type,
search_kwargs={'k': k, 'lambda_mult': lambda_mult, 'fetch_k': fetch_k}
)
# ---- BM25 Retriever ----
documents = list(db.docstore._dict.values())
bm25_retriever = BM25Retriever.from_documents(documents)
bm25_retriever.k = k
# ---- Retrieve Relevant Docs ----
dense_docs = dense_retriever.invoke(prompt)
sparse_docs = bm25_retriever.invoke(prompt)
# ---- Merge (Reranking w/ Reciprocal Rank Fusion (RRF)) ----
scores = {}
rrf_constant = 60
for rank, doc in enumerate(dense_docs, start=1):
content = doc.page_content
if content not in scores:
scores[content] = {'doc': doc, 'score': 0}
scores[content]['score'] += 1 / (rrf_constant + rank)
for rank, doc in enumerate(sparse_docs, start=1):
content = doc.page_content
if content not in scores:
scores[content] = {'doc': doc, 'score': 0}
scores[content]['score'] += 1 / (rrf_constant + rank)
# reranking based on scores -> top-k
sorted_docs = sorted(scores.values(), key=lambda x: x['score'], reverse=True)
docs = [item['doc'] for item in sorted_docs[:k]]
context = format_docs(docs=docs)
return context
def ewha_rag(prompt, context, llm):
prompt_template = ChatPromptTemplate.from_messages([
("system",
EWHA_SYSTEM_PROMPT),
("human",
EWHA_HUMAN_PROMPT)
])
# RAG chain
rag_chain = prompt_template | llm
# call RAG chain
response = rag_chain.invoke({"question": prompt, "context": context})
answer = response.content
print(f"💬 answer: {answer}")
return answer
def mmlu_law_rag(prompt, context, llm):
# ---- Prompt Template ----
prompt_template = ChatPromptTemplate.from_messages([
("system",
MMLU_LAW_PROMPT),
("human",
MMLU_HUMAN_PROMPT)
])
rag_chain = prompt_template | llm
# ---- Call RAG chain ----
response = rag_chain.invoke({
"question": prompt,
"context": context
})
answer = response.content
print(f"💬 answer: {answer}")
return answer
def mmlu_psychology_rag(prompt, context, llm):
# ---- Prompt Template ----
prompt_template = ChatPromptTemplate.from_messages([
("system",
MMLU_PSYCHOLOGY_PROMPT),
("human",
MMLU_HUMAN_PROMPT)
])
rag_chain = prompt_template | llm
# ---- Call RAG chain ----
response = rag_chain.invoke({
"question": prompt,
"context": context
})
answer = response.content
print(f"💬 answer: {answer}")
return answer
def mmlu_philosophy_rag(prompt, context, llm):
# ---- Prompt Template ----
prompt_template = ChatPromptTemplate.from_messages([
("system",
MMLU_PHILOSOPHY_PROMPT),
("human",
MMLU_HUMAN_PROMPT)
])
rag_chain = prompt_template | llm
# ---- Call RAG chain ----
response = rag_chain.invoke({
"question": prompt,
"context": context
})
answer = response.content
print(f"💬 answer: {answer}")
return answer
def mmlu_history_rag(prompt, context, llm):
# ---- Prompt Template ----
prompt_template = ChatPromptTemplate.from_messages([
("system",
MMLU_HISTORY_PROMPT),
("human",
MMLU_HUMAN_PROMPT)
])
rag_chain = prompt_template | llm
# ---- Call RAG chain ----
response = rag_chain.invoke({
"question": prompt,
"context": context
})
answer = response.content
print(f"💬 answer: {answer}")
return answer
def mmlu_business_rag(prompt, context, llm):
# ---- Prompt Template ----
prompt_template = ChatPromptTemplate.from_messages([
("system",
MMLU_BUSINESS_PROMPT),
("human",
MMLU_HUMAN_PROMPT)
])
rag_chain = prompt_template | llm
# ---- Call RAG chain ----
response = rag_chain.invoke({
"question": prompt,
"context": context
})
answer = response.content
print(f"💬 answer: {answer}")
return answer