Update rag_system.py
Browse files- rag_system.py +60 -30
rag_system.py
CHANGED
|
@@ -8,6 +8,10 @@ from langchain.docstore.document import Document
|
|
| 8 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 9 |
import pdfplumber
|
| 10 |
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# Load environment variables
|
| 13 |
load_dotenv()
|
|
@@ -28,10 +32,19 @@ def load_retrieval_qa_chain():
|
|
| 28 |
# Initialize ChatOpenAI model
|
| 29 |
llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0) # "gpt-4o-mini
|
| 30 |
|
| 31 |
-
# Create
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
| 33 |
llm,
|
| 34 |
-
|
| 35 |
return_source_documents=True
|
| 36 |
)
|
| 37 |
|
|
@@ -82,41 +95,58 @@ def update_embeddings():
|
|
| 82 |
documents.extend(result)
|
| 83 |
vectorstore.add_documents(documents)
|
| 84 |
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
formatted_history = [(q, a) for q, a in zip(chat_history[::2], chat_history[1::2])]
|
| 88 |
|
| 89 |
-
response =
|
| 90 |
-
|
| 91 |
-
answer = response["answer"]
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
return {"answer": answer, "sources":
|
| 97 |
|
| 98 |
# Example usage
|
| 99 |
if __name__ == "__main__":
|
| 100 |
update_embeddings() # Update embeddings with new documents
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
1. κ²μ κ²°κ³Ό νμ©: μ 곡λ κ²μ κ²°κ³Όλ₯Ό λΆμνκ³ κ΄λ ¨ μ 보λ₯Ό μ¬μ©ν΄ λ΅λ³νμΈμ.
|
| 105 |
-
|
| 106 |
-
2. μ νμ± μ μ§: μ 보μ μ νμ±μ νμΈνκ³ , λΆνμ€ν κ²½μ° μ΄λ₯Ό λͺ
μνμΈμ.
|
| 107 |
-
|
| 108 |
-
3. κ°κ²°ν μλ΅: μ§λ¬Έμ μ§μ λ΅νκ³ ν΅μ¬ λ΄μ©μ μ§μ€νμΈμ.
|
| 109 |
-
|
| 110 |
-
4. μΆκ° μ 보 μ μ: κ΄λ ¨λ μΆκ° μ λ³΄κ° μλ€λ©΄ μΈκΈνμΈμ.
|
| 111 |
-
|
| 112 |
-
5. μ€λ¦¬μ± κ³ λ €: κ°κ΄μ μ΄κ³ μ€λ¦½μ μΈ νλλ₯Ό μ μ§νμΈμ.
|
| 113 |
-
|
| 114 |
-
6. νκ³ μΈμ : λ΅λ³ν μ μλ κ²½μ° μμ§ν μΈμ νμΈμ.
|
| 115 |
-
|
| 116 |
-
7. λν μ μ§: μμ°μ€λ½κ² λνλ₯Ό μ΄μ΄κ°κ³ , νμμ νμ μ§λ¬Έμ μ μνμΈμ.
|
| 117 |
-
νμ μ ννκ³ μ μ©ν μ 보λ₯Ό μ 곡νλ κ²μ λͺ©νλ‘ νμΈμ."""
|
| 118 |
-
|
| 119 |
-
response = get_answer(qa_chain, question, [])
|
| 120 |
print(f"Question: {question}")
|
| 121 |
print(f"Answer: {response['answer']}")
|
| 122 |
-
print(f"Sources: {response['sources']}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 9 |
import pdfplumber
|
| 10 |
from concurrent.futures import ThreadPoolExecutor
|
| 11 |
+
from langchain.retrievers import ContextualCompressionRetriever
|
| 12 |
+
from langchain.retrievers.document_compressors import LLMChainExtractor
|
| 13 |
+
from langgraph.graph import Graph
|
| 14 |
+
from langchain_core.runnables import RunnablePassthrough, RunnableLambda
|
| 15 |
|
| 16 |
# Load environment variables
|
| 17 |
load_dotenv()
|
|
|
|
| 32 |
# Initialize ChatOpenAI model
|
| 33 |
llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0) # "gpt-4o-mini
|
| 34 |
|
| 35 |
+
# Create a compressor for re-ranking
|
| 36 |
+
compressor = LLMChainExtractor.from_llm(llm)
|
| 37 |
+
|
| 38 |
+
# Create a ContextualCompressionRetriever
|
| 39 |
+
compression_retriever = ContextualCompressionRetriever(
|
| 40 |
+
base_compressor=compressor,
|
| 41 |
+
base_retriever=vectorstore.as_retriever()
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
# Create ConversationalRetrievalChain with the new retriever
|
| 45 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
| 46 |
llm,
|
| 47 |
+
retriever=compression_retriever,
|
| 48 |
return_source_documents=True
|
| 49 |
)
|
| 50 |
|
|
|
|
| 95 |
documents.extend(result)
|
| 96 |
vectorstore.add_documents(documents)
|
| 97 |
|
| 98 |
+
def create_rag_graph():
|
| 99 |
+
qa_chain = load_retrieval_qa_chain()
|
| 100 |
+
|
| 101 |
+
def retrieve_and_generate(inputs):
|
| 102 |
+
question = inputs["question"]
|
| 103 |
+
chat_history = inputs["chat_history"]
|
| 104 |
+
result = qa_chain({"question": question, "chat_history": chat_history})
|
| 105 |
+
|
| 106 |
+
# Ensure source documents have the correct metadata
|
| 107 |
+
sources = []
|
| 108 |
+
for doc in result.get("source_documents", []):
|
| 109 |
+
if "source" in doc.metadata and "page" in doc.metadata:
|
| 110 |
+
sources.append(f"{os.path.basename(doc.metadata['source'])} (Page {doc.metadata['page']})")
|
| 111 |
+
else:
|
| 112 |
+
print(f"Warning: Document missing metadata: {doc.metadata}")
|
| 113 |
+
|
| 114 |
+
return {
|
| 115 |
+
"answer": result["answer"],
|
| 116 |
+
"sources": sources
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
workflow = Graph()
|
| 120 |
+
workflow.add_node("retrieve_and_generate", retrieve_and_generate)
|
| 121 |
+
workflow.set_entry_point("retrieve_and_generate")
|
| 122 |
+
|
| 123 |
+
chain = workflow.compile()
|
| 124 |
+
return chain
|
| 125 |
+
|
| 126 |
+
rag_chain = create_rag_graph()
|
| 127 |
+
|
| 128 |
+
def get_answer(query, chat_history):
|
| 129 |
formatted_history = [(q, a) for q, a in zip(chat_history[::2], chat_history[1::2])]
|
| 130 |
|
| 131 |
+
response = rag_chain.invoke({"question": query, "chat_history": formatted_history})
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
# Validate response format
|
| 134 |
+
if "answer" not in response or "sources" not in response:
|
| 135 |
+
print("Warning: Unexpected response format")
|
| 136 |
+
return {"answer": "Error in processing", "sources": []}
|
| 137 |
|
| 138 |
+
return {"answer": response["answer"], "sources": response["sources"]}
|
| 139 |
|
| 140 |
# Example usage
|
| 141 |
if __name__ == "__main__":
|
| 142 |
update_embeddings() # Update embeddings with new documents
|
| 143 |
+
question = "RAG μμ€ν
μ λν΄ μ€λͺ
ν΄μ£ΌμΈμ."
|
| 144 |
+
response = get_answer(question, [])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
print(f"Question: {question}")
|
| 146 |
print(f"Answer: {response['answer']}")
|
| 147 |
+
print(f"Sources: {response['sources']}")
|
| 148 |
+
|
| 149 |
+
# Validate source format
|
| 150 |
+
for source in response['sources']:
|
| 151 |
+
if not (source.endswith(')') and ' (Page ' in source):
|
| 152 |
+
print(f"Warning: Unexpected source format: {source}")
|