Spaces:
Running
Running
Update custom_utils.py
Browse files- custom_utils.py +103 -1
custom_utils.py
CHANGED
|
@@ -263,4 +263,106 @@ def connect_to_database():
|
|
| 263 |
db = mongo_client.get_database(DB_NAME)
|
| 264 |
collection = db.get_collection(COLLECTION_NAME)
|
| 265 |
|
| 266 |
-
return db, collection
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
db = mongo_client.get_database(DB_NAME)
|
| 264 |
collection = db.get_collection(COLLECTION_NAME)
|
| 265 |
|
| 266 |
+
return db, collection
|
| 267 |
+
|
| 268 |
+
def vector_search(user_query, db, collection, additional_stages=[], vector_index="vector_index_text"):
|
| 269 |
+
"""
|
| 270 |
+
Perform a vector search in the MongoDB collection based on the user query.
|
| 271 |
+
|
| 272 |
+
Args:
|
| 273 |
+
user_query (str): The user's query string.
|
| 274 |
+
db (MongoClient.database): The database object.
|
| 275 |
+
collection (MongoCollection): The MongoDB collection to search.
|
| 276 |
+
additional_stages (list): Additional aggregation stages to include in the pipeline.
|
| 277 |
+
|
| 278 |
+
Returns:
|
| 279 |
+
list: A list of matching documents.
|
| 280 |
+
"""
|
| 281 |
+
|
| 282 |
+
# Generate embedding for the user query
|
| 283 |
+
query_embedding = custom_utils.get_embedding(user_query)
|
| 284 |
+
|
| 285 |
+
if query_embedding is None:
|
| 286 |
+
return "Invalid query or embedding generation failed."
|
| 287 |
+
|
| 288 |
+
# Define the vector search stage
|
| 289 |
+
vector_search_stage = {
|
| 290 |
+
"$vectorSearch": {
|
| 291 |
+
"index": vector_index, # specifies the index to use for the search
|
| 292 |
+
"queryVector": query_embedding, # the vector representing the query
|
| 293 |
+
"path": "text_embeddings", # field in the documents containing the vectors to search against
|
| 294 |
+
"numCandidates": 150, # number of candidate matches to consider
|
| 295 |
+
"limit": 20, # return top 20 matches
|
| 296 |
+
}
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
# Define the aggregate pipeline with the vector search stage and additional stages
|
| 300 |
+
pipeline = [vector_search_stage] + additional_stages
|
| 301 |
+
|
| 302 |
+
# Execute the search
|
| 303 |
+
results = collection.aggregate(pipeline)
|
| 304 |
+
|
| 305 |
+
explain_query_execution = db.command( # sends a database command directly to the MongoDB server
|
| 306 |
+
'explain', { # return information about how MongoDB executes a query or command without actually running it
|
| 307 |
+
'aggregate': collection.name, # specifies the name of the collection on which the aggregation is performed
|
| 308 |
+
'pipeline': pipeline, # the aggregation pipeline to analyze
|
| 309 |
+
'cursor': {} # indicates that default cursor behavior should be used
|
| 310 |
+
},
|
| 311 |
+
verbosity='executionStats') # detailed statistics about the execution of each stage of the aggregation pipeline
|
| 312 |
+
|
| 313 |
+
vector_search_explain = explain_query_execution['stages'][0]['$vectorSearch']
|
| 314 |
+
millis_elapsed = vector_search_explain['explain']['collectStats']['millisElapsed']
|
| 315 |
+
|
| 316 |
+
print(f"Total time for the execution to complete on the database server: {millis_elapsed} milliseconds")
|
| 317 |
+
|
| 318 |
+
return list(results)
|
| 319 |
+
|
| 320 |
+
class SearchResultItem(BaseModel):
|
| 321 |
+
name: str
|
| 322 |
+
accommodates: Optional[int] = None
|
| 323 |
+
bedrooms: Optional[int] = None
|
| 324 |
+
address: custom_utils.Address
|
| 325 |
+
space: str = None
|
| 326 |
+
|
| 327 |
+
def handle_user_query(query, db, collection, stages=[], vector_index="vector_index_text"):
|
| 328 |
+
# Assuming vector_search returns a list of dictionaries with keys 'title' and 'plot'
|
| 329 |
+
get_knowledge = vector_search(query, db, collection, stages, vector_index)
|
| 330 |
+
|
| 331 |
+
# Check if there are any results
|
| 332 |
+
if not get_knowledge:
|
| 333 |
+
return "No results found.", "No source information available."
|
| 334 |
+
|
| 335 |
+
# Convert search results into a list of SearchResultItem models
|
| 336 |
+
search_results_models = [
|
| 337 |
+
SearchResultItem(**result)
|
| 338 |
+
for result in get_knowledge
|
| 339 |
+
]
|
| 340 |
+
|
| 341 |
+
# Convert search results into a DataFrame for better rendering in Jupyter
|
| 342 |
+
search_results_df = pd.DataFrame([item.dict() for item in search_results_models])
|
| 343 |
+
|
| 344 |
+
# Generate system response using OpenAI's completion
|
| 345 |
+
completion = custom_utils.openai.chat.completions.create(
|
| 346 |
+
model="gpt-3.5-turbo",
|
| 347 |
+
messages=[
|
| 348 |
+
{
|
| 349 |
+
"role": "system",
|
| 350 |
+
"content": "You are a airbnb listing recommendation system."},
|
| 351 |
+
{
|
| 352 |
+
"role": "user",
|
| 353 |
+
"content": f"Answer this user query: {query} with the following context:\n{search_results_df}"
|
| 354 |
+
}
|
| 355 |
+
]
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
system_response = completion.choices[0].message.content
|
| 359 |
+
|
| 360 |
+
# Print User Question, System Response, and Source Information
|
| 361 |
+
print(f"- User Question:\n{query}\n")
|
| 362 |
+
print(f"- System Response:\n{system_response}\n")
|
| 363 |
+
|
| 364 |
+
# Display the DataFrame as an HTML table
|
| 365 |
+
display(HTML(search_results_df.to_html()))
|
| 366 |
+
|
| 367 |
+
# Return structured response and source info as a string
|
| 368 |
+
return system_response
|