File size: 11,010 Bytes
dae5fc7
 
c4136a8
36320a3
 
 
 
 
738445b
 
 
 
 
 
 
cd4a9a3
e9f64ec
3271e72
25f7970
0a57b44
3271e72
ef400ea
 
 
 
 
 
d5c11ea
380302b
bb2e1f2
380302b
9802e03
 
 
 
 
 
380302b
 
d5c11ea
380302b
 
d5c11ea
26e1b1b
d5c11ea
380302b
d5c11ea
 
 
 
 
 
 
 
380302b
 
 
 
bb2e1f2
380302b
bb2e1f2
8acfede
 
 
bb2e1f2
74dae28
380302b
979095d
 
 
 
 
 
 
380302b
 
738445b
380302b
 
738445b
26e1b1b
0a57b44
380302b
738445b
380302b
03156b5
 
 
 
 
 
 
 
380302b
738445b
380302b
03156b5
 
 
 
 
 
 
 
 
380302b
738445b
380302b
d5c11ea
380302b
d5c11ea
bbfd24e
d5c11ea
 
 
 
 
 
 
 
b1b034e
91d69dd
d5c11ea
 
 
380302b
d5c11ea
9802e03
 
 
d5c11ea
 
 
9802e03
d5c11ea
 
 
 
 
 
 
 
 
0290fda
 
d5c11ea
 
 
0290fda
 
 
 
 
d5c11ea
c413f9d
d5c11ea
 
9802e03
d5c11ea
 
 
 
 
 
9802e03
36320a3
 
 
 
bb2e1f2
9edf419
 
 
 
0290fda
 
081537e
 
979095d
 
081537e
 
cf8a3af
 
8509d56
0290fda
 
 
 
cf8a3af
c413f9d
cf8a3af
8acfede
2d172eb
 
 
bb2e1f2
8acfede
bb2e1f2
 
7364d74
 
 
 
bb2e1f2
7364d74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb2e1f2
 
2d172eb
0290fda
c90c1d1
 
0290fda
 
c90c1d1
 
 
8acfede
c90c1d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8acfede
c90c1d1
 
 
 
 
 
 
 
 
 
 
8acfede
c90c1d1
 
 
 
c413f9d
380302b
8509d56
8131a67
8509d56
cf8a3af
 
0958f7d
8509d56
 
 
 
 
 
c413f9d
8509d56
 
51a98c0
528b643
8509d56
aa247a8
738445b
 
1183b4a
 
738445b
 
380302b
738445b
380302b
 
738445b
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import openai, os, time

from datasets import load_dataset
from pymongo.mongo_client import MongoClient

DB_NAME = "airbnb_dataset"
COLLECTION_NAME = "listings_reviews"

def connect_to_database():
    MONGODB_ATLAS_CLUSTER_URI = os.environ["MONGODB_ATLAS_CLUSTER_URI"]
    mongo_client = MongoClient(MONGODB_ATLAS_CLUSTER_URI, appname="advanced-rag")
    db = mongo_client.get_database(DB_NAME)
    collection = db.get_collection(COLLECTION_NAME)
    return db, collection

def rag_ingestion(collection):
    dataset = load_dataset("bstraehle/airbnb-san-francisco-202403-embed", streaming=True, split="train")
    collection.delete_many({})
    collection.insert_many(dataset)
    return "Manually create a vector search index (in free tier, this feature is not available via SDK)"

def rag_retrieval_naive(openai_api_key,
                        prompt,
                        accomodates,
                        bedrooms,
                        db,
                        collection,
                        vector_index="vector_index"):
    # Naive RAG: Semantic search
    
    retrieval_result = vector_search_naive(
        openai_api_key,
        prompt,
        accomodates,
        bedrooms,
        db,
        collection,
        vector_index
    )

    if not retrieval_result:
        return "No results found."

    #print(retrieval_result)
    
    return retrieval_result

def rag_retrieval_advanced(openai_api_key, 
                           prompt, 
                           accomodates, 
                           bedrooms, 
                           db, 
                           collection, 
                           vector_index="vector_index"):
    # Advanced RAG: Semantic search plus...
    
    # 1a) Pre-retrieval processing: index filter (accomodates, bedrooms) plus...
    # 1b) Post-retrieval processing: result filter (accomodates, bedrooms) plus...
    # 2)  Weighted average review, sorted in descending order

    additional_stages = [
        get_stage_average_review_and_review_count(),
        get_stage_weighting(),
        get_stage_sorting()
    ]
    
    retrieval_result = vector_search_advanced(
        openai_api_key, 
        prompt, 
        accomodates, 
        bedrooms, 
        db, 
        collection, 
        additional_stages, 
        vector_index
    )

    if not retrieval_result:
        return "No results found."

    #print(retrieval_result)
    
    return retrieval_result

def inference(openai_api_key, prompt):
    content = (
        "Answer the question.\n"
        "If you don't know the answer, just say that you don't know, don't try to make up an answer.\n"
        "Keep the answer as concise as possible.\n\n"
        f"Question: {prompt}\n"
        "Helpful Answer: "
    )

    return invoke_llm(openai_api_key, content)

def rag_inference(openai_api_key, prompt, retrieval_result):
    content = (
        "Use the following pieces of context to answer the question at the end.\n"
        "If you don't know the answer, just say that you don't know, don't try to make up an answer.\n"
        "Keep the answer as concise as possible.\n\n"
        f"{retrieval_result}\n\n"
        f"Question: {prompt}\n"
        "Helpful Answer: "
    )

    return invoke_llm(openai_api_key, content)

def invoke_llm(openai_api_key, content):
    openai.api_key = openai_api_key

    completion = openai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system", 
                "content": "You are an AirBnB listing recommendation system."},
            {
                "role": "user", 
                "content": content
            }
        ],
        temperature=0.01
    )

    return completion.choices[0].message.content
    
def vector_search_naive(openai_api_key, 
                        prompt,
                        accomodates,
                        bedrooms,
                        db, 
                        collection, 
                        vector_index="vector_index"):
    query_embedding = get_text_embedding(openai_api_key, prompt)

    if query_embedding is None:
        return "Invalid query or embedding generation failed."

    vector_search_stage = {
        "$vectorSearch": {
            "index": vector_index,
            "queryVector": query_embedding,
            "path": "description_embedding",
            "numCandidates": 150,
            "limit": 25,
        }
    }

    pipeline = [
        vector_search_stage, 
        get_stage_include_fields(), 
        get_stage_filter_result(accomodates, bedrooms)
    ]

    return invoke_search(db, collection, pipeline)

def vector_search_advanced(openai_api_key, 
                           prompt, 
                           accommodates, 
                           bedrooms, 
                           db, 
                           collection, 
                           additional_stages=[], 
                           vector_index="vector_index"):
    query_embedding = get_text_embedding(openai_api_key, prompt)

    if query_embedding is None:
        return "Invalid query or embedding generation failed."

    vector_search_and_filter_stage = {
        "$vectorSearch": {
            "index": vector_index,
            "queryVector": query_embedding,
            "path": "description_embedding",
            "numCandidates": 150,
            "limit": 25,
            "filter": {
                "$and": [
                    {"accommodates": {"$eq": accommodates}}, 
                    {"bedrooms": {"$eq": bedrooms}}
                ]
            },
        }
    }
  
    pipeline = [
        vector_search_and_filter_stage, 
        get_stage_include_fields()
    ] + additional_stages

    return invoke_search(db, collection, pipeline)

def get_stage_exclude_fields():
    return {
        "$unset": "description_embedding"
    }
    
def get_stage_include_fields():
    return {
        "$project": {
            "id": 1, 
            "listing_url": 1, 
            "name": 1, 
            "description": 1, 
            "neighborhood_overview": 1, 
            "picture_url": 1, 
            "host_id": 1, 
            "host_url": 1, 
            "host_name": 1, 
            "host_since": 1, 
            "host_location": 1, 
            "host_about": 1, 
            "host_response_time": 1, 
            "host_response_rate": 1, 
            "host_acceptance_rate": 1, 
            "host_is_superhost": 1, 
            "host_thumbnail_url": 1, 
            "host_picture_url": 1, 
            "host_neighbourhood": 1, 
            "host_listings_count": 1, 
            "host_total_listings_count": 1, 
            "host_verifications": 1, 
            "host_has_profile_pic": 1, 
            "host_identity_verified": 1, 
            "neighbourhood": 1, 
            "neighbourhood_cleansed": 1, 
            "neighbourhood_group_cleansed": 1, 
            "latitude": 1, 
            "longitude": 1, 
            "property_type": 1, 
            "room_type": 1, 
            "accommodates": 1, 
            "bathrooms": 1, 
            "bathrooms_text": 1, 
            "bedrooms": 1, 
            "beds": 1, 
            "amenities": 1, 
            "price": 1, 
            "minimum_nights": 1, 
            "maximum_nights": 1, 
            "minimum_minimum_nights": 1, 
            "maximum_minimum_nights": 1, 
            "minimum_maximum_nights": 1, 
            "maximum_maximum_nights": 1, 
            "minimum_nights_avg_ntm": 1, 
            "maximum_nights_avg_ntm": 1, 
            "calendar_updated": 1, 
            "has_availability": 1, 
            "availability_30": 1, 
            "availability_60": 1, 
            "availability_90": 1, 
            "availability_365": 1, 
            "number_of_reviews": 1, 
            "number_of_reviews_ltm": 1, 
            "number_of_reviews_l30d": 1, 
            "first_review": 1, 
            "last_review": 1, 
            "review_scores_rating": 1, 
            "review_scores_accuracy": 1, 
            "review_scores_cleanliness": 1, 
            "review_scores_checkin": 1, 
            "review_scores_communication": 1, 
            "review_scores_location": 1, 
            "review_scores_value": 1, 
            "license": 1, 
            "instant_bookable": 1, 
            "calculated_host_listings_count": 1, 
            "calculated_host_listings_count_entire_homes": 1, 
            "calculated_host_listings_count_private_rooms": 1, 
            "calculated_host_listings_count_shared_rooms": 1, 
            "reviews_per_month": 1,
        }
    }

def get_stage_filter_result(accomodates, bedrooms):
    return {
        "$match": {
            "accommodates": { "$eq": accomodates},
            "bedrooms": { "$eq": bedrooms}
        }
    }

def get_stage_average_review_and_review_count():
    return {
        "$addFields": {
            "averageReview": {
                "$divide": [
                    {
                        "$add": [
                            "$review_scores_rating",
                            "$review_scores_accuracy",
                            "$review_scores_cleanliness",
                            "$review_scores_checkin",
                            "$review_scores_communication",
                            "$review_scores_location",
                            "$review_scores_value",
                        ]
                    },
                    7
                ]
            },
            "reviewCount": "$number_of_reviews"
        }
    }

def get_stage_weighting():
    return {
        "$addFields": {
            "weightedAverageReview": {
                "$add": [
                    {"$multiply": ["$averageReview", 0.9]},
                    {"$multiply": ["$reviewCount", 0.1]},
                ]
            }
        }
    }

def get_stage_sorting():
    return {
        "$sort": {"weightedAverageReview": -1}
    }

def invoke_search(db, collection, pipeline):
    results = collection.aggregate(pipeline)
    
    print(f"Vector search millis elapsed: {get_millis_elapsed(db, collection, pipeline)}")
    
    return list(results)

def get_millis_elapsed(db, collection, pipeline):
    explain_query_execution = db.command(
        "explain", {
            "aggregate": collection.name,
            "pipeline": pipeline,
            "cursor": {}
        }, 
        verbosity="executionStats")

    explain_vector_search = explain_query_execution["stages"][0]["$vectorSearch"]

    return explain_vector_search["explain"]["collectors"]["allCollectorStats"]["millisElapsed"]

def get_text_embedding(openai_api_key, text):
    if not text or not isinstance(text, str):
        return None

    openai.api_key = openai_api_key
        
    try:
        return openai.embeddings.create(
            input=text,
            model="text-embedding-3-small", dimensions=1536
        ).data[0].embedding
    except Exception as e:
        print(f"Error in get_embedding: {e}")
        return None