schennu commited on
Commit
209bfa3
·
verified ·
1 Parent(s): b20414e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -4
app.py CHANGED
@@ -6,6 +6,7 @@ import os
6
  import time
7
  import tempfile
8
  import pandas as pd
 
9
 
10
 
11
  from langchain_community.document_loaders import TextLoader
@@ -32,8 +33,15 @@ if 'knowledge_base' not in st.session_state:
32
  if 'knowledge_files' not in st.session_state:
33
  st.session_state.knowledge_files = []
34
 
 
 
 
 
 
 
 
35
  def create_rag_knowledge_base(documents):
36
- """Create a RAG knowledge base using LangChain."""
37
  # Initialize a list to store LangChain documents
38
  langchain_docs = []
39
 
@@ -42,10 +50,21 @@ def create_rag_knowledge_base(documents):
42
  try:
43
  # Create LangChain Document from the uploaded file content
44
  content = doc.getvalue().decode('utf-8')
 
 
 
 
 
 
 
 
 
 
 
45
  langchain_docs.append(
46
  LangchainDocument(
47
  page_content=content,
48
- metadata={"source": doc.name}
49
  )
50
  )
51
  except Exception as e:
@@ -58,6 +77,15 @@ def create_rag_knowledge_base(documents):
58
  )
59
  all_splits = text_splitter.split_documents(langchain_docs)
60
 
 
 
 
 
 
 
 
 
 
61
  # Create embeddings and vector store
62
  embeddings = OpenAIEmbeddings()
63
 
@@ -86,7 +114,7 @@ def query_knowledge_base(vectorstore, query, openai_api_key):
86
  llm=llm,
87
  chain_type="stuff",
88
  retriever=retriever,
89
- return_source_documents=False
90
  )
91
 
92
  # Build the prompt
@@ -94,6 +122,7 @@ def query_knowledge_base(vectorstore, query, openai_api_key):
94
  Based on the following information about senior activities and resources,
95
  please provide relevant suggestions for a senior interested in: {query}
96
  Focus on specific activities, locations, or resources mentioned in the context.
 
97
  """
98
 
99
  # Generate response
@@ -103,7 +132,22 @@ def query_knowledge_base(vectorstore, query, openai_api_key):
103
  if not result or not result.get("result"):
104
  return "No relevant information found in the knowledge base. Proceeding with general search."
105
 
106
- return result["result"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  def get_result(user_prompt, age_group, zip_code, mobility, serper_api_key, openai_api_key, collection=None):
109
  # Double-check that API keys are set
@@ -429,6 +473,7 @@ with tab2:
429
  - **Provide location-specific recommendations** based on your community resources
430
  - **Offer more accurate accessibility information** tailored to your mobility needs
431
  - **Learn over time** as more community resources are added to our knowledge base
 
432
 
433
  Upload local senior activity guides, community center calendars, or neighborhood resources to enhance your recommendations!
434
  """)
 
6
  import time
7
  import tempfile
8
  import pandas as pd
9
+ import re
10
 
11
 
12
  from langchain_community.document_loaders import TextLoader
 
33
  if 'knowledge_files' not in st.session_state:
34
  st.session_state.knowledge_files = []
35
 
36
+ def extract_urls(text):
37
+ """Extract URLs from text content."""
38
+ # Regular expression pattern to match URLs
39
+ url_pattern = r'https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+'
40
+ urls = re.findall(url_pattern, text)
41
+ return urls
42
+
43
  def create_rag_knowledge_base(documents):
44
+ """Create a RAG knowledge base using LangChain with URL extraction."""
45
  # Initialize a list to store LangChain documents
46
  langchain_docs = []
47
 
 
50
  try:
51
  # Create LangChain Document from the uploaded file content
52
  content = doc.getvalue().decode('utf-8')
53
+
54
+ # Extract URLs from the content
55
+ urls = extract_urls(content)
56
+ url_string = "\n".join(urls) if urls else ""
57
+
58
+ # Add extracted URLs to metadata
59
+ metadata = {
60
+ "source": doc.name,
61
+ "urls": url_string
62
+ }
63
+
64
  langchain_docs.append(
65
  LangchainDocument(
66
  page_content=content,
67
+ metadata=metadata
68
  )
69
  )
70
  except Exception as e:
 
77
  )
78
  all_splits = text_splitter.split_documents(langchain_docs)
79
 
80
+ # Preserve URLs in metadata when splitting
81
+ for split_doc in all_splits:
82
+ if "urls" not in split_doc.metadata and "source" in split_doc.metadata:
83
+ # Find the original document to get URLs
84
+ for doc in langchain_docs:
85
+ if doc.metadata["source"] == split_doc.metadata["source"]:
86
+ split_doc.metadata["urls"] = doc.metadata.get("urls", "")
87
+ break
88
+
89
  # Create embeddings and vector store
90
  embeddings = OpenAIEmbeddings()
91
 
 
114
  llm=llm,
115
  chain_type="stuff",
116
  retriever=retriever,
117
+ return_source_documents=True # Changed to True to get source docs with URLs
118
  )
119
 
120
  # Build the prompt
 
122
  Based on the following information about senior activities and resources,
123
  please provide relevant suggestions for a senior interested in: {query}
124
  Focus on specific activities, locations, or resources mentioned in the context.
125
+ If available, include direct URLs to resources.
126
  """
127
 
128
  # Generate response
 
132
  if not result or not result.get("result"):
133
  return "No relevant information found in the knowledge base. Proceeding with general search."
134
 
135
+ # Extract URLs from source documents
136
+ source_urls = []
137
+ if "source_documents" in result:
138
+ for doc in result["source_documents"]:
139
+ if "urls" in doc.metadata and doc.metadata["urls"]:
140
+ urls = doc.metadata["urls"].split("\n")
141
+ source_urls.extend(urls)
142
+
143
+ # Add URLs to the result if available
144
+ final_result = result["result"]
145
+ if source_urls:
146
+ final_result += "\n\nRelevant Resources:\n"
147
+ for i, url in enumerate(set(source_urls), 1): # Using set to remove duplicates
148
+ final_result += f"{i}. {url}\n"
149
+
150
+ return final_result
151
 
152
  def get_result(user_prompt, age_group, zip_code, mobility, serper_api_key, openai_api_key, collection=None):
153
  # Double-check that API keys are set
 
473
  - **Provide location-specific recommendations** based on your community resources
474
  - **Offer more accurate accessibility information** tailored to your mobility needs
475
  - **Learn over time** as more community resources are added to our knowledge base
476
+ - **Direct links to resources** extracted from uploaded documents
477
 
478
  Upload local senior activity guides, community center calendars, or neighborhood resources to enhance your recommendations!
479
  """)