Spaces:
Build error

File size: 9,581 Bytes
9c32f1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2753b08
9c32f1b
eb56c9e
 
 
 
2753b08
 
 
 
eb56c9e
 
2753b08
 
eb56c9e
 
 
 
 
 
 
 
 
 
 
9c32f1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb56c9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c32f1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb56c9e
9c32f1b
 
 
 
 
 
 
 
 
 
 
 
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
from typing import Dict, List
from typing_extensions import TypedDict

from langchain_core.documents import Document

from lib.model_builder import ModelBuilderV2
from lib.vectorestores import FAISSBuilder
from lib.model_builder import ModelBuilderV2
from lib.vectorestores import FAISSBuilder
from langchain.retrievers.multi_query import MultiQueryRetriever
from lib.runnables import (
    casual_llm,
    retrieval_grader_3,
    rag_chain,
    message_classificator,
)
from lib.config import Config
from langgraph.graph import END, StateGraph
from transformers import AutoModel, AutoTokenizer
import torch
import torch.nn.functional as F

config = Config("config.yml")
model_name = config.get("embeddings", "intfloat", "model")
device = config.get("embeddings", "intfloat", "device")

tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModel.from_pretrained(model_name)

device = torch.device(device)
model.to(device)
SIMILARITY_TRESHHOLD = 0.8


def get_embeddings(texts):
    inputs = tokenizer(texts, return_tensors="pt", padding=True, truncation=True)
    inputs.to(device)
    with torch.no_grad():
        outputs = model(**inputs)
        embeddings = torch.mean(outputs.last_hidden_state, dim=1)
    return embeddings


class GraphState(TypedDict):
    """
    Represents the state of our graph.

    Attributes:
        question: question
        generation: LLM generation
        web_search: whether to add search
        documents: list of documents
    """

    question: str
    generation: str
    documents: List[Document]
    filtered_documets: List[Document]
    count_regenerations: int


def combine_vectors(vectors):
    result = []
    vec1_count = len(vectors["vector1"])
    # vec2_count = len(vectors["vector2"])
    for i in range(vec1_count):
        if i < vec1_count:
            result.append(vectors["vector1"][i])
        # if i < vec2_count:
        #     result.append(vectors['vector2'][i])
    return result


def retrieve(state):
    """
    Retrieve documents

    Args:
        state (dict): The current graph state

    Returns:
        state (dict): New key added to state, documents, that contains retrieved documents
    """
    print("---RETRIEVE---")
    question = state["question"]

    # Retrieval
    with FAISSBuilder() as faiss_retriever:
        with ModelBuilderV2("openchat/openchat-7b") as mq_llm:
            retriever = MultiQueryRetriever.from_llm(
                retriever=faiss_retriever, llm=mq_llm
            )
            documents = retriever.get_relevant_documents(question)
            return {"documents": documents, "question": question}


def start_point(state):
    """
    Start point, just return state

    Args:
        state (dict): The current graph state

    Returns:
        state (dict): The current graph state
    """
    return state


def casual_chat(state):
    """
    Define type of message

    Args:
        state (dict): The current graph state

    Returns:
        state (dict): New key added to state, generation, that contains message with casual answer
    """
    question = state["question"]
    print("---CASUAL CHAT---")
    generation = casual_llm.invoke(
        {"question": question},
        config={
            "configurable": {
                "conversation_id": "default_session",
                "user_id": "deafault_user",
            }
        },
    )
    state["generation"] = generation

    return state


def define_message_type(state):
    """
    Define type of message

    Args:
        state (dict): The current graph state

    Returns:

    """
    print("---MESSAGE CLASSIFICATION---")
    question = state["question"]
    msg_type_obj = message_classificator.invoke({"question": question})
    print(
        f"---MESSAGE TYPE: {msg_type_obj['message_type']} SYSTEM MESSAGE---\n {msg_type_obj['system_message']}"
    )
    msg_type = msg_type_obj["message_type"]

    if msg_type == "TAX":
        return "retrieve"
    # if msg_type == "":
    return "casual_chat"
    return "__end__"


def generate(state):
    """
    Generate answer

    Args:
        state (dict): The current graph state

    Returns:
        state (dict): New key added to state, generation, that contains LLM generation, based on documents
    """
    print("---GENERATE---")
    question = state["question"]
    documents = state["documents"]

    # RAG generation
    generation = rag_chain.invoke(
        {"context": documents, "question": question},
        config={
            "configurable": {
                "conversation_id": "default_session",
                "user_id": "deafault_user",
            }
        },
    )
    return {"documents": documents, "question": question, "generation": generation}


def grade_documents_by_embed(state):
    """
    Determines whether the retrieved documents are relevant to the question.

    Args:
        state (dict): The current graph state

    Returns:
        state (dict): Updates documents key with only filtered relevant documents
    """
    question = state["question"]
    documents = state["documents"]

    # Score each doc
    filtered_docs = []

    query_embedding = get_embeddings([question])
    document_embeddings = get_embeddings([doc.page_content for doc in documents])

    # Calculate cosine similarity
    similarity_scores = F.cosine_similarity(query_embedding, document_embeddings)
    for doc, score in zip(documents, similarity_scores):
        if score >= SIMILARITY_TRESHHOLD:
            filtered_docs.append(doc)
    sorted_documents = [
        doc[0]
        for doc in sorted(
            zip(documents, similarity_scores), key=lambda x: x[1], reverse=True
        )
    ]
    cut_off_documents = sorted_documents[:5]
    return {"documents": cut_off_documents, "question": question}


def grade_documents(state):
    """
    Determines whether the retrieved documents are relevant to the question.

    Args:
        state (dict): The current graph state

    Returns:
        state (dict): Updates documents key with only filtered relevant documents
    """

    print("---CHECK DOCUMENT RELEVANCE TO QUESTION---")
    question = state["question"]
    documents = state["documents"]

    # Score each doc
    filtered_docs = []
    count_docs = len(documents)
    for ind_d in range(0, count_docs, 3):
        d_1 = documents[ind_d] if ind_d < count_docs else None
        d_2 = documents[ind_d + 1] if ind_d + 1 < count_docs else None
        d_3 = documents[ind_d + 2] if ind_d + 2 < count_docs else None
        scores = retrieval_grader_3.invoke(
            {
                "question": question,
                "document_1": d_1,
                "document_2": d_2,
                "document_3": d_3,
            }
        )
        for j in range(len(scores)):
            grade = scores[j]["score"]
            if grade > 0.7:
                print(f"---GRADE: DOCUMENT RELEVANT--- GRADE: {grade}")
                filtered_docs.append(documents[ind_d + j])
            else:
                print("---GRADE: DOCUMENT NOT RELEVANT---")

    return {"documents": filtered_docs, "question": question}


def make_collapsable_source_message(doc: Dict):
    file_path = doc.metadata.get("file_name", "")
    file_name = file_path.replace(".pdf", "")
    chapter_title = doc.metadata.get("chapter_title", None)
    page_num = doc.metadata.get("first_page_num", None)
    title = f"""
        {file_name}
        {f": {chapter_title} " if chapter_title is not None else ""}
        {f"Стр. {page_num} " if page_num is not None else ""}
    """.replace(
        "\n", " "
    )
    content = doc.page_content.replace("\n\n", "\n")

    if page_num is None:
        message = rf"""
            <details>
            <summary>{title}</summary>
            {str(content)}
            </details>
        """
    else:
        base_url = "http://localhost:5000/sta"
        url = f"{base_url}?file={file_path}&#page={page_num}&zoom=90&toolbar=0"
        message = f"""
            <a class="open_pdf" href='{url}' onclick="return openPdf('{url}')">{title}</a>
        """

    return message


def add_sources(state):
    """
    Determines whether the retrieved documents are relevant to the question.

    Args:
        state (dict): The current graph state

    Returns:
        state (dict): Add collapsable sources
    """
    question = state["question"]
    documents = state["documents"]
    generation = state["generation"]

    sources_message = "<i></i>".join(map(make_collapsable_source_message, documents))
    extended_generation_message = f"{generation} {sources_message}"
    return {
        "documents": documents,
        "question": question,
        "generation": extended_generation_message,
    }


def build_workflow():
    workflow = StateGraph(GraphState)

    # Define the nodes
    workflow.add_node("start_point", start_point)
    workflow.add_node("retrieve", retrieve)  # retrieve
    workflow.add_node("grade_documents", grade_documents_by_embed)  # grade documents
    workflow.add_node("generate", generate)  # generate
    workflow.add_node("casual_chat", casual_chat)  # simple chat
    workflow.add_node("add_sources", add_sources)
    # Build graph
    workflow.set_entry_point("start_point")
    workflow.add_conditional_edges("start_point", define_message_type)
    workflow.add_edge("retrieve", "grade_documents")
    workflow.add_edge("grade_documents", "generate")
    workflow.add_edge("generate", "add_sources")
    workflow.add_edge("add_sources", END)
    workflow.add_edge("casual_chat", END)
    return workflow.compile()