Spaces:
Running
Running
Update openai_embedding.py
Browse files- openai_embedding.py +46 -1
openai_embedding.py
CHANGED
@@ -1,5 +1,7 @@
|
|
1 |
import openai
|
2 |
|
|
|
|
|
3 |
openai.api_key = OPENAI_API_KEY
|
4 |
|
5 |
def get_embedding(text):
|
@@ -17,4 +19,47 @@ def get_embedding(text):
|
|
17 |
return embedding
|
18 |
except Exception as e:
|
19 |
print(f"Error in get_embedding: {e}")
|
20 |
-
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import openai
|
2 |
|
3 |
+
from IPython.display import display, HTML
|
4 |
+
|
5 |
openai.api_key = OPENAI_API_KEY
|
6 |
|
7 |
def get_embedding(text):
|
|
|
19 |
return embedding
|
20 |
except Exception as e:
|
21 |
print(f"Error in get_embedding: {e}")
|
22 |
+
return None
|
23 |
+
|
24 |
+
def handle_user_query(query, db, collection):
|
25 |
+
# Assuming vector_search returns a list of dictionaries with keys 'title' and 'plot'
|
26 |
+
get_knowledge = vector_search(query, db, collection)
|
27 |
+
|
28 |
+
# Check if there are any results
|
29 |
+
if not get_knowledge:
|
30 |
+
return "No results found.", "No source information available."
|
31 |
+
|
32 |
+
# Convert search results into a list of SearchResultItem models
|
33 |
+
search_results_models = [
|
34 |
+
SearchResultItem(**result)
|
35 |
+
for result in get_knowledge
|
36 |
+
]
|
37 |
+
|
38 |
+
# Convert search results into a DataFrame for better rendering in Jupyter
|
39 |
+
search_results_df = pd.DataFrame([item.dict() for item in search_results_models])
|
40 |
+
|
41 |
+
# Generate system response using OpenAI's completion
|
42 |
+
completion = openai.chat.completions.create(
|
43 |
+
model="gpt-3.5-turbo",
|
44 |
+
messages=[
|
45 |
+
{
|
46 |
+
"role": "system",
|
47 |
+
"content": "You are a airbnb listing recommendation system."},
|
48 |
+
{
|
49 |
+
"role": "user",
|
50 |
+
"content": f"Answer this user query: {query} with the following context:\n{search_results_df}"
|
51 |
+
}
|
52 |
+
]
|
53 |
+
)
|
54 |
+
|
55 |
+
system_response = completion.choices[0].message.content
|
56 |
+
|
57 |
+
# Print User Question, System Response, and Source Information
|
58 |
+
print(f"- User Question:\n{query}\n")
|
59 |
+
print(f"- System Response:\n{system_response}\n")
|
60 |
+
|
61 |
+
# Display the DataFrame as an HTML table
|
62 |
+
display(HTML(search_results_df.to_html()))
|
63 |
+
|
64 |
+
# Return structured response and source info as a string
|
65 |
+
return system_response
|