Spaces:
Build error
Build error
Download lib/graph.py from miniondenis/Doc_eater: direct link, hf CLI and curl.
- Browser
- Download file 9.58 kB
-
https://huggingface.co/spaces/miniondenis/Doc_eater/resolve/main/lib/graph.py
- Command line
-
hf download hf://spaces/miniondenis/Doc_eater/lib/graph.py
-
curl -L -o graph.py https://huggingface.co/spaces/miniondenis/Doc_eater/resolve/main/lib/graph.py
9.58 kB
| 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() | |