alekzan commited on
Commit
cab10e5
·
1 Parent(s): 747fbb7

Upload chatbot app

Browse files
.gitignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore the virtual environment
2
+ venv_goldmine/
3
+
4
+ # Ignore environment variables
5
+ .env
6
+
7
+ # Ignore unnecessary files
8
+ *.pyc
9
+ __pycache__/
10
+ *.log
11
+ .DS_Store
12
+
13
+ # Ignore Jupyter Notebook checkpoints
14
+ .ipynb_checkpoints/
app.py CHANGED
@@ -1,12 +1,9 @@
1
- # app.py
2
-
3
  import os
4
  from dotenv import load_dotenv
5
  from langchain_groq import ChatGroq
6
-
7
  from typing import Optional
8
-
9
- from langchain_chroma import Chroma
10
  from langchain_openai import OpenAIEmbeddings, ChatOpenAI
11
  from langchain_text_splitters import RecursiveCharacterTextSplitter
12
  from langgraph.graph import StateGraph
@@ -22,41 +19,37 @@ from langgraph.graph import MessagesState
22
  import gradio as gr
23
  import uuid
24
 
25
- import os.path
26
 
27
- os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY") # Hugging Face Secrets
 
28
  os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY")
29
  os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGCHAIN_API_KEY")
 
30
  os.environ["LANGCHAIN_TRACING_V2"] = "true"
31
  os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
32
  os.environ["LANGCHAIN_PROJECT"] = "Demo Upwork"
 
 
 
 
 
33
 
34
- # Initialize embeddings (using the OpenAI API key)
 
 
35
  embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
36
 
 
37
  gpt = "gpt-4o-mini"
38
  llm = ChatOpenAI(model=gpt, temperature=0.2)
39
- llama_3_2 = "llama-3.2-90b-vision-preview"
40
- # llm = ChatGroq(model=llama_3_2, temperature=0.2)
41
 
42
 
43
  def process_docs_and_get_retriever(
44
- doc_path: str,
45
- persist_directory="./data/chroma_langchain_db",
46
- collection_name: str = "user_data",
47
- k: int = 4,
48
  ):
49
  """
50
- Load a document (PDF or DOCX), split its content, add it to a Chroma vector store, and return a retriever.
51
-
52
- Args:
53
- doc_path: Path to the document file (PDF or DOCX).
54
- persist_directory: Directory where the Chroma vector store will be persisted.
55
- collection_name: Name of the collection in the vector store.
56
- k: Number of documents to retrieve in similarity searches.
57
-
58
- Returns:
59
- A retriever object for querying the vector store.
60
  """
61
  # Step 1: Determine document type and load it
62
  if doc_path.endswith(".pdf"):
@@ -85,49 +78,22 @@ def process_docs_and_get_retriever(
85
  )
86
  splits = text_splitter.split_documents(docs)
87
 
88
- # Step 3: Initialize or load Chroma vector store
89
- embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
90
- if os.path.exists(persist_directory):
91
- # Load existing vector store
92
- vector_store = Chroma(
93
- persist_directory=persist_directory,
94
- embedding_function=embeddings,
95
- collection_name=collection_name,
96
- )
97
- # Add new documents to the existing vector store
98
- vector_store.add_documents(splits)
99
- else:
100
- # Create a new vector store and add documents
101
- vector_store = Chroma.from_documents(
102
- documents=splits,
103
- embedding=embeddings,
104
- persist_directory=persist_directory,
105
- collection_name=collection_name,
106
- )
107
 
108
  return "All Data added"
109
 
110
 
111
  def process_text_as_retriever(text: str):
112
  """
113
- Process plain text, split it into chunks, add it to a Chroma vector store, and return a retriever.
114
-
115
- Args:
116
- text: Plain text to be added to the vector store.
117
-
118
- Returns:
119
- A retriever object for querying the vector store.
120
  """
121
- # Hard-coded parameters
122
- persist_directory = "./data/chroma_langchain_db"
123
- collection_name = "user_data"
124
- k = 4
125
-
126
- # Step 1: Convert text into a Document object
127
-
128
  docs = [Document(page_content=text)]
129
 
130
- # Step 2: Split the text into manageable chunks
131
  text_splitter = RecursiveCharacterTextSplitter(
132
  chunk_size=500,
133
  chunk_overlap=50,
@@ -135,61 +101,30 @@ def process_text_as_retriever(text: str):
135
  )
136
  splits = text_splitter.split_documents(docs)
137
 
138
- # Step 3: Initialize or load Chroma vector store
139
- embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
140
- if os.path.exists(persist_directory):
141
- # Load existing vector store
142
- vector_store = Chroma(
143
- persist_directory=persist_directory,
144
- embedding_function=embeddings,
145
- collection_name=collection_name,
146
- )
147
- # Add new documents to the existing vector store
148
- vector_store.add_documents(splits)
149
- else:
150
- # Create a new vector store and add documents
151
- vector_store = Chroma.from_documents(
152
- documents=splits,
153
- embedding=embeddings,
154
- persist_directory=persist_directory,
155
- collection_name=collection_name,
156
- )
157
 
158
- # Step 4: Create and return the retriever
159
- retriever = vector_store.as_retriever(search_kwargs={"k": k})
160
- return retriever
161
 
162
 
163
- def recreate_retriever(
164
- persist_directory: str = "./data/chroma_langchain_db",
165
- collection_name: str = "user_data",
166
- ):
167
  """
168
- Recreate the retriever dynamically using the metadata in the state.
169
  """
170
-
171
- embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
172
- vector_store = Chroma(
173
- persist_directory=persist_directory,
174
- embedding_function=embeddings,
175
- collection_name=collection_name,
176
- )
177
  return vector_store.as_retriever(search_kwargs={"k": 4})
178
 
179
 
180
- # Check if the path exists
181
- chroma_db_path = "./data/chroma_langchain_db"
182
-
183
- if not os.path.exists(chroma_db_path):
184
- doc_path = "./data/docs/goldmine.docx"
185
- retriever_doc = process_docs_and_get_retriever(doc_path)
186
- print("Retriever is ready:", retriever_doc)
187
- else:
188
- print(f"Path already exists: {chroma_db_path}")
189
-
190
 
 
191
  tools = []
192
-
193
  retriever = recreate_retriever()
194
  retriever_tool = create_retriever_tool(
195
  retriever,
@@ -199,16 +134,16 @@ retriever_tool = create_retriever_tool(
199
  tools.append(retriever_tool)
200
 
201
 
 
202
  class State(MessagesState):
203
  query: str
204
- doc_path: Optional[str] # Path of the document being processed
205
 
206
 
207
  def vector_data(state: State):
208
  if "doc_path" in state and state["doc_path"]:
209
  print("\n\n********** ADDING DATA TO VECTOR STORE **********\n\n")
210
  doc_path = state["doc_path"]
211
- # Add documents
212
  process_docs_and_get_retriever(doc_path)
213
  return {
214
  "doc_path": "",
@@ -222,10 +157,9 @@ def vector_data(state: State):
222
 
223
  def call_model(state: State):
224
  messages = state.get("messages", [])
225
- query = state.get("query", "").strip() # Get query safely, default to empty string
226
 
227
  if not query:
228
- # If no query, return a friendly response
229
  return {
230
  "messages": [
231
  AIMessage(
@@ -236,15 +170,13 @@ def call_model(state: State):
236
 
237
  sys_msg = SystemMessage(
238
  content="""You are a helpful assistant.
239
-
240
- Your main task is to assist the user by providing accurate information using the retriever_tool. Always answer based only on the information retrieved with the retriever_tool.
241
-
242
  If you do not find the information needed to answer the user's question, clearly state:
243
  'I do not have the information you are looking for. If you just added new information, you might try asking your question again.'
244
  Then, politely ask the user to update the knowledge base with relevant details.
245
-
246
-
247
- Do not provide answers based on assumptions, external knowledge, or unsupported information. Always rely solely on the retrieved content."""
248
  )
249
 
250
  message = HumanMessage(content=query)
@@ -257,10 +189,11 @@ def call_model(state: State):
257
  return {"messages": response}
258
 
259
 
 
260
  workflow = StateGraph(State)
261
  workflow.add_node("vector_data", vector_data)
262
  workflow.add_node("call_model", call_model)
263
- workflow.add_node("tools", ToolNode(tools)) # for the tools
264
 
265
  workflow.set_entry_point("vector_data")
266
  workflow.add_edge("vector_data", "call_model")
 
 
 
1
  import os
2
  from dotenv import load_dotenv
3
  from langchain_groq import ChatGroq
 
4
  from typing import Optional
5
+ from langchain_pinecone import PineconeVectorStore
6
+ from pinecone import Pinecone
7
  from langchain_openai import OpenAIEmbeddings, ChatOpenAI
8
  from langchain_text_splitters import RecursiveCharacterTextSplitter
9
  from langgraph.graph import StateGraph
 
19
  import gradio as gr
20
  import uuid
21
 
22
+ PINECONE_API_KEY = os.getenv("PINECONE_API_KEY")
23
 
24
+ # Set environment variables
25
+ os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
26
  os.environ["GROQ_API_KEY"] = os.getenv("GROQ_API_KEY")
27
  os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGCHAIN_API_KEY")
28
+ os.environ["PINECONE_API_KEY"] = os.getenv("PINECONE_API_KEY")
29
  os.environ["LANGCHAIN_TRACING_V2"] = "true"
30
  os.environ["LANGCHAIN_ENDPOINT"] = "https://api.smith.langchain.com"
31
  os.environ["LANGCHAIN_PROJECT"] = "Demo Upwork"
32
+ # os.environ["PINECONE_API_KEY"] = PINECONE_API_KEY
33
+
34
+ # Initialize Pinecone client
35
+ pc = Pinecone(api_key=PINECONE_API_KEY)
36
+
37
 
38
+ index_name = "goldmine-amazon"
39
+
40
+ # Initialize embeddings
41
  embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
42
 
43
+ # Initialize LLM
44
  gpt = "gpt-4o-mini"
45
  llm = ChatOpenAI(model=gpt, temperature=0.2)
 
 
46
 
47
 
48
  def process_docs_and_get_retriever(
49
+ doc_path: str, collection_name: str = "user_data", k: int = 4
 
 
 
50
  ):
51
  """
52
+ Load a document (PDF or DOCX), split its content, add it to Pinecone, and return a retriever.
 
 
 
 
 
 
 
 
 
53
  """
54
  # Step 1: Determine document type and load it
55
  if doc_path.endswith(".pdf"):
 
78
  )
79
  splits = text_splitter.split_documents(docs)
80
 
81
+ # Step 3: Initialize Pinecone vector store and add documents
82
+ vector_store = PineconeVectorStore.from_documents(
83
+ documents=splits, embedding=embeddings, index_name=index_name
84
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  return "All Data added"
87
 
88
 
89
  def process_text_as_retriever(text: str):
90
  """
91
+ Process plain text, split it into chunks, add it to Pinecone, and return a retriever.
 
 
 
 
 
 
92
  """
93
+ # Create Document object from text
 
 
 
 
 
 
94
  docs = [Document(page_content=text)]
95
 
96
+ # Split the text into manageable chunks
97
  text_splitter = RecursiveCharacterTextSplitter(
98
  chunk_size=500,
99
  chunk_overlap=50,
 
101
  )
102
  splits = text_splitter.split_documents(docs)
103
 
104
+ # Initialize Pinecone vector store and add documents
105
+ vector_store = PineconeVectorStore.from_documents(
106
+ documents=splits, embedding=embeddings, index_name=index_name
107
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
+ # Create and return the retriever
110
+ return vector_store.as_retriever(search_kwargs={"k": 4})
 
111
 
112
 
113
+ def recreate_retriever():
 
 
 
114
  """
115
+ Recreate the retriever dynamically using Pinecone.
116
  """
117
+ vector_store = PineconeVectorStore(index_name=index_name, embedding=embeddings)
 
 
 
 
 
 
118
  return vector_store.as_retriever(search_kwargs={"k": 4})
119
 
120
 
121
+ # Initialize first document if needed
122
+ doc_path = "./data/docs/goldmine.docx"
123
+ retriever_doc = process_docs_and_get_retriever(doc_path)
124
+ print("Retriever is ready:", retriever_doc)
 
 
 
 
 
 
125
 
126
+ # Create tools
127
  tools = []
 
128
  retriever = recreate_retriever()
129
  retriever_tool = create_retriever_tool(
130
  retriever,
 
134
  tools.append(retriever_tool)
135
 
136
 
137
+ # Rest of the code remains the same...
138
  class State(MessagesState):
139
  query: str
140
+ doc_path: Optional[str]
141
 
142
 
143
  def vector_data(state: State):
144
  if "doc_path" in state and state["doc_path"]:
145
  print("\n\n********** ADDING DATA TO VECTOR STORE **********\n\n")
146
  doc_path = state["doc_path"]
 
147
  process_docs_and_get_retriever(doc_path)
148
  return {
149
  "doc_path": "",
 
157
 
158
  def call_model(state: State):
159
  messages = state.get("messages", [])
160
+ query = state.get("query", "").strip()
161
 
162
  if not query:
 
163
  return {
164
  "messages": [
165
  AIMessage(
 
170
 
171
  sys_msg = SystemMessage(
172
  content="""You are a helpful assistant.
173
+ Your main task is to assist the user by providing accurate information using the retriever_tool.
174
+ Always answer based only on the information retrieved with the retriever_tool.
 
175
  If you do not find the information needed to answer the user's question, clearly state:
176
  'I do not have the information you are looking for. If you just added new information, you might try asking your question again.'
177
  Then, politely ask the user to update the knowledge base with relevant details.
178
+ Do not provide answers based on assumptions, external knowledge, or unsupported information.
179
+ Always rely solely on the retrieved content."""
 
180
  )
181
 
182
  message = HumanMessage(content=query)
 
189
  return {"messages": response}
190
 
191
 
192
+ # Setup workflow
193
  workflow = StateGraph(State)
194
  workflow.add_node("vector_data", vector_data)
195
  workflow.add_node("call_model", call_model)
196
+ workflow.add_node("tools", ToolNode(tools))
197
 
198
  workflow.set_entry_point("vector_data")
199
  workflow.add_edge("vector_data", "call_model")
chat_test_2.ipynb CHANGED
@@ -2,7 +2,7 @@
2
  "cells": [
3
  {
4
  "cell_type": "code",
5
- "execution_count": 1,
6
  "metadata": {},
7
  "outputs": [],
8
  "source": [
@@ -529,6 +529,86 @@
529
  "app.launch()\n"
530
  ]
531
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  {
533
  "cell_type": "code",
534
  "execution_count": null,
 
2
  "cells": [
3
  {
4
  "cell_type": "code",
5
+ "execution_count": 2,
6
  "metadata": {},
7
  "outputs": [],
8
  "source": [
 
529
  "app.launch()\n"
530
  ]
531
  },
532
+ {
533
+ "cell_type": "code",
534
+ "execution_count": 2,
535
+ "metadata": {},
536
+ "outputs": [
537
+ {
538
+ "name": "stderr",
539
+ "output_type": "stream",
540
+ "text": [
541
+ "/Users/alex/Projects/Auto Flujo/Clientes/Upwork/Goldmine/venv_goldmine/lib/python3.10/site-packages/pinecone/data/index.py:1: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
542
+ " from tqdm.autonotebook import tqdm\n"
543
+ ]
544
+ },
545
+ {
546
+ "data": {
547
+ "text/plain": [
548
+ "{'indexes': [{'deletion_protection': 'disabled',\n",
549
+ " 'dimension': 1536,\n",
550
+ " 'host': 'marko-energia-no-borrar-1-julio-5b1tv9c.svc.aped-4627-b74a.pinecone.io',\n",
551
+ " 'metric': 'cosine',\n",
552
+ " 'name': 'marko-energia-no-borrar-1-julio',\n",
553
+ " 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-east-1'}},\n",
554
+ " 'status': {'ready': True, 'state': 'Ready'}},\n",
555
+ " {'deletion_protection': 'disabled',\n",
556
+ " 'dimension': 1536,\n",
557
+ " 'host': 'seller-noborrar-16-julio-5b1tv9c.svc.aped-4627-b74a.pinecone.io',\n",
558
+ " 'metric': 'cosine',\n",
559
+ " 'name': 'seller-noborrar-16-julio',\n",
560
+ " 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-east-1'}},\n",
561
+ " 'status': {'ready': True, 'state': 'Ready'}},\n",
562
+ " {'deletion_protection': 'disabled',\n",
563
+ " 'dimension': 1536,\n",
564
+ " 'host': 'assy-energia-no-borrar-1-julio-5b1tv9c.svc.aped-4627-b74a.pinecone.io',\n",
565
+ " 'metric': 'cosine',\n",
566
+ " 'name': 'assy-energia-no-borrar-1-julio',\n",
567
+ " 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-east-1'}},\n",
568
+ " 'status': {'ready': True, 'state': 'Ready'}},\n",
569
+ " {'deletion_protection': 'disabled',\n",
570
+ " 'dimension': 1536,\n",
571
+ " 'host': 'goldmine-amazon-5b1tv9c.svc.aped-4627-b74a.pinecone.io',\n",
572
+ " 'metric': 'cosine',\n",
573
+ " 'name': 'goldmine-amazon',\n",
574
+ " 'spec': {'serverless': {'cloud': 'aws', 'region': 'us-east-1'}},\n",
575
+ " 'status': {'ready': True, 'state': 'Ready'}}]}"
576
+ ]
577
+ },
578
+ "execution_count": 2,
579
+ "metadata": {},
580
+ "output_type": "execute_result"
581
+ }
582
+ ],
583
+ "source": [
584
+ "from langchain_pinecone import PineconeVectorStore\n",
585
+ "from pinecone import Pinecone\n",
586
+ "\n",
587
+ "pc = Pinecone(api_key=\"ebf55a00-3f20-4f9c-a1c7-f0c349505238\")\n",
588
+ "pc.list_indexes() # Check if your index exists"
589
+ ]
590
+ },
591
+ {
592
+ "cell_type": "code",
593
+ "execution_count": 1,
594
+ "metadata": {},
595
+ "outputs": [
596
+ {
597
+ "ename": "NameError",
598
+ "evalue": "name 'pc' is not defined",
599
+ "output_type": "error",
600
+ "traceback": [
601
+ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
602
+ "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)",
603
+ "Cell \u001b[0;32mIn[1], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[38;5;28mprint\u001b[39m(\u001b[43mpc\u001b[49m\u001b[38;5;241m.\u001b[39mlist_indexes())\n",
604
+ "\u001b[0;31mNameError\u001b[0m: name 'pc' is not defined"
605
+ ]
606
+ }
607
+ ],
608
+ "source": [
609
+ "print(pc.list_indexes())\n"
610
+ ]
611
+ },
612
  {
613
  "cell_type": "code",
614
  "execution_count": null,
data/chroma_langchain_db/80bec7b5-3d15-4e15-9baf-48ca840252be/data_level0.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f18abd8c514282db82706e52b0a33ed659cd534e925a6f149deb7af9ce34bd8e
3
+ size 6284000
data/chroma_langchain_db/80bec7b5-3d15-4e15-9baf-48ca840252be/header.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:effaa959ce2b30070fdafc2fe82096fc46e4ee7561b75920dd3ce43d09679b21
3
+ size 100
data/chroma_langchain_db/80bec7b5-3d15-4e15-9baf-48ca840252be/length.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:84dbd9bd2ecbbe225125c362d33ec96d29a715e00314484357df530c7a661552
3
+ size 4000
data/chroma_langchain_db/80bec7b5-3d15-4e15-9baf-48ca840252be/link_lists.bin ADDED
File without changes
data/chroma_langchain_db/chroma.sqlite3 ADDED
Binary file (205 kB). View file
 
data/rag/chroma_langchain_db/1f95eb67-2fa4-4a26-ab73-741133869231/length.bin CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7d8fdccf440cba2ae45c9bdd94b553de5adfa1afc18e5745d05713679c59e50f
3
  size 4000
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:47a70c7c5c1eea73d6e90676ca49c037142b5ed82389df90e968adf290770aa2
3
  size 4000
data/rag/chroma_langchain_db/chroma.sqlite3 CHANGED
Binary files a/data/rag/chroma_langchain_db/chroma.sqlite3 and b/data/rag/chroma_langchain_db/chroma.sqlite3 differ