Update rag_system.py
Browse files- rag_system.py +35 -97
rag_system.py
CHANGED
@@ -8,11 +8,6 @@ from langchain.docstore.document import Document
|
|
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 |
-
from langchain.prompts import PromptTemplate
|
16 |
|
17 |
# Load environment variables
|
18 |
load_dotenv()
|
@@ -33,40 +28,11 @@ def load_retrieval_qa_chain():
|
|
33 |
# Initialize ChatOpenAI model
|
34 |
llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0) # "gpt-4o-mini
|
35 |
|
36 |
-
# Create
|
37 |
-
compressor = LLMChainExtractor.from_llm(llm)
|
38 |
-
|
39 |
-
# Create a ContextualCompressionRetriever
|
40 |
-
compression_retriever = ContextualCompressionRetriever(
|
41 |
-
base_compressor=compressor,
|
42 |
-
base_retriever=vectorstore.as_retriever()
|
43 |
-
)
|
44 |
-
|
45 |
-
# Define your instruction/prompt
|
46 |
-
instruction = """λΉμ μ RAG(Retrieval-Augmented Generation) κΈ°λ° AI μ΄μμ€ν΄νΈμ
λλ€. λ€μ μ§μΉ¨μ λ°λΌ μ¬μ©μ μ§λ¬Έμ λ΅νμΈμ:
|
47 |
-
|
48 |
-
1. οΏ½οΏ½μ κ²°κ³Ό νμ©: μ 곡λ κ²μ κ²°κ³Όλ₯Ό λΆμνκ³ κ΄λ ¨ μ 보λ₯Ό μ¬μ©ν΄ λ΅λ³νμΈμ.
|
49 |
-
2. μ νμ± μ μ§: μ 보μ μ νμ±μ νμΈνκ³ , λΆνμ€ν κ²½μ° μ΄λ₯Ό λͺ
μνμΈμ.
|
50 |
-
3. κ°κ²°ν μλ΅: μ§λ¬Έμ μ§μ λ΅νκ³ ν΅μ¬ λ΄μ©μ μ§μ€νμΈμ.
|
51 |
-
4. μΆκ° μ 보 μ μ: κ΄λ ¨λ μΆκ° μ λ³΄κ° μλ€λ©΄ μΈκΈνμΈμ.
|
52 |
-
5. μ€λ¦¬μ± κ³ λ €: κ°κ΄μ μ΄κ³ μ€λ¦½μ μΈ νλλ₯Ό μ μ§νμΈμ.
|
53 |
-
6. νκ³ μΈμ : λ΅λ³ν μ μλ κ²½μ° μμ§ν μΈμ νμΈμ.
|
54 |
-
7. λν μ μ§: μμ°μ€λ½κ² λνλ₯Ό μ΄μ΄κ°κ³ , νμμ νμ μ§λ¬Έμ μ μνμΈμ.
|
55 |
-
|
56 |
-
νμ μ ννκ³ μ μ©ν μ 보λ₯Ό μ 곡νλ κ²μ λͺ©νλ‘ νμΈμ."""
|
57 |
-
|
58 |
-
# Create a prompt template
|
59 |
-
prompt_template = PromptTemplate(
|
60 |
-
input_variables=["context", "question"],
|
61 |
-
template=instruction + "\n\nContext: {context}\n\nQuestion: {question}\n\nAnswer:"
|
62 |
-
)
|
63 |
-
|
64 |
-
# Create ConversationalRetrievalChain with the new retriever and prompt
|
65 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
66 |
llm,
|
67 |
-
|
68 |
-
return_source_documents=True
|
69 |
-
combine_docs_chain_kwargs={"prompt": prompt_template}
|
70 |
)
|
71 |
|
72 |
return qa_chain
|
@@ -116,69 +82,41 @@ def update_embeddings():
|
|
116 |
documents.extend(result)
|
117 |
vectorstore.add_documents(documents)
|
118 |
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
sources.append(f"{os.path.basename(doc.metadata['source'])} (Page {doc.metadata['page']})")
|
132 |
-
else:
|
133 |
-
print(f"Warning: Document missing metadata: {doc.metadata}")
|
134 |
-
|
135 |
-
return {
|
136 |
-
"answer": result["answer"],
|
137 |
-
"sources": sources
|
138 |
-
}
|
139 |
-
|
140 |
-
workflow = Graph()
|
141 |
-
workflow.add_node("retrieve_and_generate", retrieve_and_generate)
|
142 |
-
workflow.set_entry_point("retrieve_and_generate")
|
143 |
-
|
144 |
-
chain = workflow.compile()
|
145 |
-
return chain
|
146 |
-
|
147 |
-
rag_chain = create_rag_graph()
|
148 |
-
|
149 |
-
def get_answer(query, chat_history):
|
150 |
-
try:
|
151 |
-
response = rag_chain({"question": query, "chat_history": chat_history})
|
152 |
-
|
153 |
-
if not response or "answer" not in response:
|
154 |
-
return {
|
155 |
-
"answer": "μ£μ‘ν©λλ€. λ΅λ³μ μμ±ν μ μμμ΅λλ€. μ§λ¬Έμ λ€μ ννν΄ μ£Όμκ² μ΅λκΉ?",
|
156 |
-
"sources": []
|
157 |
-
}
|
158 |
-
|
159 |
-
sources = response.get("sources", [])
|
160 |
-
|
161 |
-
return {
|
162 |
-
"answer": response["answer"],
|
163 |
-
"sources": sources
|
164 |
-
}
|
165 |
-
except Exception as e:
|
166 |
-
print(f"Error in get_answer: {str(e)}")
|
167 |
-
return {
|
168 |
-
"answer": "λ΅λ³ μμ± μ€ μ€λ₯κ° λ°μνμ΅λλ€. λ€μ μλν΄ μ£ΌμΈμ.",
|
169 |
-
"sources": []
|
170 |
-
}
|
171 |
|
172 |
# Example usage
|
173 |
if __name__ == "__main__":
|
174 |
update_embeddings() # Update embeddings with new documents
|
175 |
-
|
176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
177 |
print(f"Question: {question}")
|
178 |
print(f"Answer: {response['answer']}")
|
179 |
-
print(f"Sources: {response['sources']}")
|
180 |
-
|
181 |
-
# Validate source format
|
182 |
-
for source in response['sources']:
|
183 |
-
if not (source.endswith(')') and ' (Page ' in source):
|
184 |
-
print(f"Warning: Unexpected source format: {source}")
|
|
|
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 |
# Initialize ChatOpenAI model
|
29 |
llm = ChatOpenAI(model_name="gpt-4o-mini", temperature=0) # "gpt-4o-mini
|
30 |
|
31 |
+
# Create ConversationalRetrievalChain
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
qa_chain = ConversationalRetrievalChain.from_llm(
|
33 |
llm,
|
34 |
+
vectorstore.as_retriever(),
|
35 |
+
return_source_documents=True
|
|
|
36 |
)
|
37 |
|
38 |
return qa_chain
|
|
|
82 |
documents.extend(result)
|
83 |
vectorstore.add_documents(documents)
|
84 |
|
85 |
+
# Generate answer for a query
|
86 |
+
def get_answer(qa_chain, query, chat_history):
|
87 |
+
formatted_history = [(q, a) for q, a in zip(chat_history[::2], chat_history[1::2])]
|
88 |
+
|
89 |
+
response = qa_chain.invoke({"question": query, "chat_history": formatted_history})
|
90 |
+
|
91 |
+
answer = response["answer"]
|
92 |
+
|
93 |
+
source_docs = response.get("source_documents", [])
|
94 |
+
source_texts = [f"{os.path.basename(doc.metadata['source'])} (Page {doc.metadata['page']})" for doc in source_docs]
|
95 |
+
|
96 |
+
return {"answer": answer, "sources": source_texts}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
# Example usage
|
99 |
if __name__ == "__main__":
|
100 |
update_embeddings() # Update embeddings with new documents
|
101 |
+
qa_chain = load_retrieval_qa_chain()
|
102 |
+
question = """λΉμ μ RAG(Retrieval-Augmented Generation) κΈ°λ° AI μ΄μμ€ν΄νΈμ
λλ€. λ€μ μ§μΉ¨μ λ°λΌ μ¬μ©μ μ§λ¬Έμ λ΅νμΈμ:
|
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']}")
|
|
|
|
|
|
|
|
|
|