File size: 7,198 Bytes
dae5fc7
16b5324
dae5fc7
c4136a8
16b5324
36320a3
 
 
fe97823
36320a3
 
 
 
738445b
 
 
 
 
 
 
 
cd4a9a3
e9f64ec
3271e72
25f7970
0a57b44
3271e72
979095d
 
 
 
 
 
 
74dae28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
979095d
 
 
 
 
 
 
 
 
738445b
 
 
 
0a57b44
9c1fe60
0a57b44
 
9c1fe60
738445b
979095d
 
 
738445b
74dae28
6931de0
738445b
 
 
 
 
 
 
 
 
 
 
 
 
 
aa247a8
738445b
979095d
 
 
 
 
 
 
 
aa247a8
36320a3
 
 
 
979095d
 
 
 
 
 
 
 
 
9edf419
 
 
 
 
 
 
979095d
081537e
 
979095d
 
081537e
 
cf8a3af
 
5b5b03e
 
 
 
7ad4a46
5b5b03e
cf8a3af
 
 
74dae28
 
 
 
 
 
 
cf8a3af
74dae28
 
 
cf8a3af
 
 
aa247a8
738445b
 
1183b4a
 
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
import openai, os, time
#import pandas as pd

from datasets import load_dataset
#from pydantic import ValidationError
from pymongo.collection import Collection
from pymongo.errors import OperationFailure
from pymongo.mongo_client import MongoClient
from pymongo.operations import SearchIndexModel

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(openai_api_key, 
                  prompt, 
                  accomodates, 
                  bedrooms, 
                  db, 
                  collection, 
                  vector_index="vector_index"):
    ###
    ### Pre-retrieval processing: index filter
    ### Post-retrieval processing: result filter
    #match_stage = {
    #    "$match": {
    #        "accommodates": { "$eq": 2},
    #        "bedrooms": { "$eq": 1}
    #    }
    #}

    #additional_stages = [match_stage]
    ###
    """
    projection_stage = {
        "$project": {
            "_id": 0,  
            "name": 1,
            "accommodates": 1,
            "address.street": 1,
            "address.government_area": 1, 
            "address.market": 1,
            "address.country": 1, 
            "address.country_code": 1, 
            "address.location.type": 1, 
            "address.location.coordinates": 1,  
            "address.location.is_location_exact": 1,
            "summary": 1,
            "space": 1,  
            "neighborhood_overview": 1, 
            "notes": 1, 
            "score": {"$meta": "vectorSearchScore"} 
        }
    }
    
    additional_stages = [projection_stage]
    """
    ###
    #review_average_stage = {
    #    "$addFields": {
    #        "averageReviewScore": {
    #            "$divide": [
    #                {
    #                    "$add": [
    #                        "$review_scores.review_scores_accuracy",
    #                        "$review_scores.review_scores_cleanliness",
    #                        "$review_scores.review_scores_checkin",
    #                        "$review_scores.review_scores_communication",
    #                        "$review_scores.review_scores_location",
    #                        "$review_scores.review_scores_value",
    #                    ]
    #                },
    #                6  # Divide by the number of review score types to get the average
    #            ]
    #        },
    #        # Calculate a score boost factor based on the number of reviews
    #        "reviewCountBoost": "$number_of_reviews"
    #    }
    #}

    #weighting_stage = {
    #    "$addFields": {
    #        "combinedScore": {
    #            # Example formula that combines average review score and review count boost
    #            "$add": [
    #                {"$multiply": ["$averageReviewScore", 0.9]},  # Weighted average review score
    #                {"$multiply": ["$reviewCountBoost", 0.1]}   # Weighted review count boost
    #            ]
    #        }
    #    }
    #}

    # Apply the combinedScore for sorting
    #sorting_stage_sort = {
    #    "$sort": {"combinedScore": -1}  # Descending order to boost higher combined scores
    #}

    #additional_stages = [review_average_stage, weighting_stage, sorting_stage_sort]
    ###
    additional_stages = []
    ###    
    ###
    
    get_knowledge = vector_search(
        openai_api_key, 
        prompt, 
        accomodates, 
        bedrooms, 
        db, 
        collection, 
        additional_stages, 
        vector_index)

    if not get_knowledge:
        return "No results found.", "No source information available."

    print("###")
    print(get_knowledge)
    print("###")
    
    return get_knowledge

def rag_inference(openai_api_key, 
                  prompt, 
                  search_results):
    openai.api_key = openai_api_key
  
    content = f"Answer this user question: {prompt} with the following context:\n{search_results}"
    
    completion = openai.chat.completions.create(
        model="gpt-4o",
        messages=[
            {
                "role": "system", 
                "content": "You are an AirBnB listing recommendation system."},
            {
                "role": "user", 
                "content": content
            }
        ]
    )

    return completion.choices[0].message.content

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

    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": 3,
    #    }
    #}

    vector_search_stage = {
        "$vectorSearch": {
            "index": vector_index,
            "queryVector": query_embedding,
            "path": "description_embedding",
            "numCandidates": 150,
            "limit": 10,
            "filter": {
                "$and": [
                    {"accommodates": {"$eq": accommodates}}, 
                    {"bedrooms": {"$eq": bedrooms}}
                ]
            },
        }
    }

    remove_embedding_stage =     {
        "$unset": "description_embedding"
    }
    
    pipeline = [vector_search_stage, remove_embedding_stage]# + additional_stages

    results = collection.aggregate(pipeline)

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

    #vector_search_explain = explain_query_execution["stages"][0]["$vectorSearch"]
    #millis_elapsed = vector_search_explain["explain"]["collectStats"]["millisElapsed"]
    #print(f"Query execution time: {millis_elapsed} milliseconds")

    return list(results)

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:
        embedding = openai.embeddings.create(
            input=text,
            model="text-embedding-3-small", dimensions=1536).data[0].embedding
        return embedding
    except Exception as e:
        print(f"Error in get_embedding: {e}")
        return None