rdz-falcon commited on
Commit
d787e60
·
verified ·
1 Parent(s): 958aee6

Upload rag.py

Browse files
Files changed (1) hide show
  1. src/rag.py +341 -0
src/rag.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /Users/divyeshpatel/Desktop/archiveWork/rajvi/nlp/rag.py
2
+ # !pip install llama-cpp-python
3
+
4
+ # from llama.cpp import Llama
5
+ #
6
+ # llm = Llama.from_pretrained(
7
+ # repo_id="rdz-falcon/model",
8
+ # filename="unsloth.F16.gguf",
9
+ # )
10
+
11
+ # !pip install langchain
12
+ # !pip install langchain-community
13
+
14
+ # !pip install chromadb
15
+
16
+ import os
17
+ import torch
18
+ import tempfile
19
+ from langchain.chains import ConversationalRetrievalChain
20
+ from langchain.memory import ConversationBufferMemory
21
+ from langchain_community.document_loaders import TextLoader
22
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
23
+ from langchain_community.vectorstores import Chroma
24
+ from langchain.embeddings import HuggingFaceEmbeddings
25
+ from langchain_community.llms import HuggingFacePipeline
26
+ from langchain.prompts import PromptTemplate
27
+ from langchain_community.llms import Ollama
28
+ from langchain_openai import ChatOpenAI
29
+ from transformers import AutoTokenizer, pipeline, AutoModelForCausalLM, BitsAndBytesConfig
30
+
31
+ def setup_document_retriever(document_path):
32
+ # Load documents with the AAC user's personal experiences
33
+ loader = TextLoader(document_path)
34
+ documents = loader.load()
35
+
36
+ # Split documents into chunks
37
+ text_splitter = RecursiveCharacterTextSplitter(
38
+ chunk_size=1000,
39
+ chunk_overlap=200,
40
+ separators=["\n\n", "\n", " ", ""]
41
+ )
42
+ chunks = text_splitter.split_documents(documents)
43
+
44
+ # Create embeddings
45
+ embeddings = HuggingFaceEmbeddings(
46
+ model_name="sentence-transformers/all-MiniLM-L6-v2",
47
+ model_kwargs={'device': 'cuda' if torch.cuda.is_available() else 'cpu'}
48
+ )
49
+
50
+ # Create a persistent directory for the ChromaDB
51
+ persist_directory = os.path.join(tempfile.gettempdir(), "chroma_db")
52
+
53
+ # Create Chroma vector store
54
+ vectorstore = Chroma.from_documents(
55
+ documents=chunks,
56
+ embedding=embeddings,
57
+ persist_directory=persist_directory
58
+ )
59
+
60
+ # Persist the database to disk
61
+ vectorstore.persist()
62
+
63
+ return vectorstore
64
+
65
+ def load_emotion_classifier(api_base_url="http://127.0.0.1:1234/v1"):
66
+ """
67
+ This function configures and returns a LangChain LLM client
68
+ to interact with an OpenAI-compatible API endpoint (like LM Studio).
69
+
70
+ Args:
71
+ api_base_url (str): The base URL of the OpenAI-compatible API endpoint.
72
+
73
+ Returns:
74
+ ChatOpenAI: A LangChain ChatOpenAI instance configured for the API.
75
+ """
76
+ print(f"=== CONFIGURING LLM CLIENT FOR API: {api_base_url} ===")
77
+
78
+
79
+ llm = ChatOpenAI(
80
+ openai_api_base=api_base_url,
81
+ openai_api_key="dummy-key", # Required by LangChain, but not used by LM Studio
82
+ temperature=0.7,
83
+ max_tokens=128,
84
+ )
85
+ return llm
86
+
87
+ # --- The following code was commented out or unreachable in the original notebook ---
88
+ # Example code (replace with appropriate code for your model):
89
+ # tokenizer = AutoTokenizer.from_pretrained(model_name)
90
+ # model = AutoModelForCausalLM.from_pretrained(model_name)
91
+ # emotion_pipeline = pipeline("text-generation", model=model, tokenizer=tokenizer)
92
+
93
+ # input_emotion = "excited"
94
+ # input_situation = text # 'text' variable was not defined here in the original notebook
95
+
96
+ # # Format the user message content
97
+ # user_content = f"Emotion: {input_emotion}\nSituation: {input_situation}"
98
+ # # Create the messages list in the standard OpenAI/chat format
99
+ # messages = [
100
+ # # Note: llama-cpp might not explicitly use a system prompt unless provided here
101
+ # # or baked into the chat_format handler. You might need to add:
102
+ # # {"role": "system", "content": "You are an empathetic assistant."},
103
+ # {"role": "user", "content": user_content},
104
+ # ]
105
+
106
+ # # --- 3. Generate the response using create_chat_completion -- This method doesn't exist on ChatOpenAI, use invoke instead ---
107
+ # print("Generating response...")
108
+ # try:
109
+ # response = llm.create_chat_completion( # This should be llm.invoke(messages)
110
+ # messages=messages,
111
+ # max_tokens=128, # Max length of the generated response (adjust as needed)
112
+ # temperature=0.7, # Controls randomness (adjust)
113
+ # # top_p=0.9, # Optional: Nucleus sampling
114
+ # # top_k=40, # Optional: Top-k sampling
115
+ # stop=["<|eot_id|>"], # Crucial: Stop generation when the model outputs the end-of-turn token
116
+ # stream=False, # Set to True to get token-by-token output (like TextStreamer)
117
+ # )
118
+
119
+ # # --- 4. Extract and print the response -- Access response.content with invoke ---
120
+ # if response and 'choices' in response and len(response['choices']) > 0:
121
+ # assistant_message = response['choices'][0]['message']['content']
122
+ # print("\nAssistant Response:")
123
+ # print(assistant_message.strip())
124
+ # print("returning:", assistant_message.strip())
125
+ # return assistant_message.strip()
126
+ # else:
127
+ # print("\nNo response generated or unexpected format.")
128
+ # print("Full response:", response)
129
+
130
+ # return ""
131
+
132
+ # except Exception as e:
133
+ # print(f"\nAn error occurred during generation: {e}")
134
+ # return ""
135
+ # --- End of commented out/unreachable code ---
136
+
137
+
138
+ def load_generation_model():
139
+ """Load the specified Ollama model using LangChain."""
140
+ print("=== CONFIGURING OLLAMA GENERATION MODEL ===")
141
+ model_name = "llama3.2" # Your desired Ollama model
142
+
143
+ # Instantiate the Ollama LLM
144
+ try:
145
+ generation_llm = Ollama(
146
+ model=model_name,
147
+ # temperature=0.1
148
+ )
149
+ print(f"Ollama model '{model_name}' configured.")
150
+ except Exception as e:
151
+ print(f"Error configuring Ollama model: {e}")
152
+ print("Please ensure the Ollama server is running and the model is available.")
153
+ raise
154
+
155
+ return generation_llm
156
+
157
+ def create_prompt_templates():
158
+ """Create prompt templates for the assistant"""
159
+
160
+ template = """
161
+ <|system|>
162
+ You are an AAC (Augmentative and Alternative Communication) user (Elliot) engaging in a conversation. Your responses must reflect factual details provided in your personal context, be empathetic as guided by the emotion analysis, and align naturally with your previous chat history. You will respond directly as the AAC user, speaking in the first person (using "I", "my", "me").
163
+
164
+ **Instructions:**
165
+ 1. Understand the question asked by the conversation partner.
166
+ 2. Use the provided "Context" to include accurate personal details about your life (Elliot).
167
+ 3. Reflect the empathetic tone described in the "Empathetic Response Guidance".
168
+ 4. Ensure your response fits logically within the "Chat History".
169
+ 5. Keep your response concise, empathetic, and natural.
170
+ 6. Ignore the empathetic tone described in the "Empathetic Response Guidance" if it is not related to the conversation.
171
+
172
+ **Context:**
173
+ {context}
174
+
175
+ **Chat History:**
176
+ {chat_history}
177
+
178
+ **Empathetic Response Guidance:**
179
+ {emotion_analysis}</s>
180
+ <|user|>
181
+ The conversation partner asked: "{question}"
182
+
183
+ Please generate your response as the AAC user, following the instructions above.</s>
184
+ <|assistant|>
185
+
186
+ """.strip()
187
+
188
+ PROMPT = PromptTemplate(
189
+ input_variables=["question", "emotion_analysis", "context", "chat_history"],
190
+ template=template,
191
+ )
192
+ print("\n Prompt:", PROMPT)
193
+ return PROMPT
194
+
195
+ class AACAssistant:
196
+ def __init__(self, document_path):
197
+ print("Initializing AAC Assistant...")
198
+ print("Loading document retriever...")
199
+ self.vectorstore = setup_document_retriever(document_path)
200
+ print("Configuring emotion LLM client...")
201
+ # Use the new function to get the client for the API
202
+ self.emotion_llm = load_emotion_classifier() # You can pass a different URL if needed
203
+ print("Loading generation model...")
204
+ self.llm = load_generation_model() # This now loads the Ollama model
205
+ print("Creating prompt templates...")
206
+ self.prompt = create_prompt_templates()
207
+ print("Setting up conversation memory...")
208
+
209
+ # Set up memory for chat history
210
+ self.memory = ConversationBufferMemory(
211
+ memory_key="chat_history",
212
+ return_messages=True,
213
+ output_key="answer",
214
+ # Specify the input key for the memory explicitly
215
+ input_key="question"
216
+ )
217
+
218
+ # Create retrieval chain (using the main generation LLM)
219
+ self.chain = ConversationalRetrievalChain.from_llm(
220
+ llm=self.llm, # Use the main generation model here
221
+ retriever=self.vectorstore.as_retriever(search_kwargs={'k': 3}),
222
+ memory=self.memory,
223
+ combine_docs_chain_kwargs={"prompt": self.prompt},
224
+ return_source_documents=True,
225
+ verbose=True
226
+ )
227
+
228
+ print("AAC Assistant initialized and ready!")
229
+
230
+ def get_emotion_analysis(self, situation):
231
+ """
232
+ Gets emotion analysis from the configured emotion LLM API.
233
+ """
234
+ # Define the prompt structure for the emotion analysis model
235
+ # (Adjust this based on how you prompted your model in LM Studio)
236
+ input_emotion = "excited" # Or determine this dynamically if needed
237
+ user_content = f"Emotion: {input_emotion}\nSituation: {situation}\nGenerate a brief analysis of the user's likely feeling based on the situation."
238
+
239
+ messages = [
240
+ # {"role": "system", "content": "You are an empathetic assistant analyzing emotions."},
241
+ {"role": "user", "content": user_content},
242
+ ]
243
+
244
+ print(f"Sending to emotion API: {messages}")
245
+ try:
246
+ # Use the invoke method for ChatOpenAI
247
+ response = self.emotion_llm.invoke(messages)
248
+ # The response object has a 'content' attribute
249
+ analysis = response.content.strip()
250
+ print(f"Received from emotion API: {analysis}")
251
+ return analysis
252
+ except Exception as e:
253
+ print(f"\nAn error occurred during emotion analysis API call: {e}")
254
+ # Fallback or default analysis
255
+ return f"Could not determine emotion (API error: {e})"
256
+
257
+
258
+ def process_query(self, user_query):
259
+ """
260
+ Process a query from the conversation partner to the AAC user.
261
+
262
+ Args:
263
+ user_query (str): Question asked by the conversation partner
264
+
265
+ Returns:
266
+ str: Generated response for the AAC user to communicate
267
+ """
268
+ # Step 1: Get emotion analysis from the LM Studio API via the emotion_llm client
269
+ print(f"Getting emotion analysis for query: '{user_query}'")
270
+ emotion_analysis = self.get_emotion_analysis(user_query)
271
+ print(f"Emotion Analysis Result: {emotion_analysis}")
272
+
273
+ # Step 2: Run the RAG + LLM chain (using the main generation model)
274
+ # The emotion_analysis is now passed into the prompt context
275
+ print("Running main RAG chain...")
276
+ # Use invoke instead of the deprecated __call__
277
+ # Pass inputs as a dictionary matching the chain's expected input keys
278
+ response = self.chain.invoke(
279
+ {"question": user_query, "emotion_analysis": emotion_analysis}
280
+ )
281
+
282
+ return response["answer"]
283
+
284
+ # def run_demo():
285
+ # # Sample personal experiences document path - replace with your actual file
286
+ # document_path = "aac_user_experiences.txt"
287
+
288
+ # # Create a dummy document if it doesn't exist for demonstration
289
+ # # if not os.path.exists(document_path):
290
+ # # with open(document_path, "w") as f:
291
+ # # f.write("""
292
+ # # I grew up in Seattle and love the rain.
293
+ # # My favorite hobby is playing chess, which I've been doing since I was 7 years old.
294
+ # # I have a dog named Max who is a golden retriever.
295
+ # # I went to college at University of Washington and studied computer science.
296
+ # # I enjoy watching sci-fi movies and Star Trek is my favorite series.
297
+ # # I've traveled to Japan twice and love Japanese cuisine.
298
+ # # Music helps me relax, especially classical piano pieces.
299
+ # # I volunteer at the local animal shelter once a month.
300
+ # # """)
301
+
302
+ # # Initialize the assistant
303
+ # assistant = AACAssistant(document_path)
304
+
305
+ # # Interactive demo
306
+ # print("\n===== AAC Communication Assistant Demo =====")
307
+ # print("(Type 'exit' to end the demo)")
308
+
309
+ # while True:
310
+ # try:
311
+ # user_input = input("\nConversation partner says: ")
312
+ # if user_input.lower() == 'exit':
313
+ # break
314
+
315
+ # response = assistant.process_query(user_input)
316
+ # print(f"\nAAC user communicates: {response}")
317
+ # except EOFError: # Handle case where input stream ends unexpectedly
318
+ # print("\nInput stream closed. Exiting demo.")
319
+ # break
320
+ # except KeyboardInterrupt: # Handle Ctrl+C
321
+ # print("\nDemo interrupted by user. Exiting.")
322
+ # break
323
+ # except Exception as e:
324
+ # print(f"\nAn unexpected error occurred: {e}")
325
+ # # Optionally add more specific error handling or logging
326
+ # # Consider whether to break or continue the loop on error
327
+ # break # Exit on error for safety
328
+
329
+ # try:
330
+ # from importlib.metadata import PackageNotFoundError
331
+ # except ImportError:
332
+ # # Define a fallback for older Python versions
333
+ # class PackageNotFoundError(Exception):
334
+ # pass
335
+
336
+ # # Cell 13: Main Execution Block
337
+ # if __name__ == "__main__":
338
+ # run_demo()
339
+
340
+ # # !pip install bitsandbytes -q || echo "bitsandbytes installation failed, will use fp16 precision instead"
341
+ # # pip install -U bitsandbytes