Spaces:
Sleeping
Sleeping
Create qna.py
Browse files- services/qa_service/qna.py +41 -0
services/qa_service/qna.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
|
3 |
+
class QAService:
|
4 |
+
def __init__(self, conf, pinecone, model, question, context):
|
5 |
+
self.conf = conf
|
6 |
+
self.pc = pinecone['connection']
|
7 |
+
self.embedder = pinecone['embedder']
|
8 |
+
self.model = model
|
9 |
+
self.question = question
|
10 |
+
self.context = context
|
11 |
+
|
12 |
+
def __enter__(self):
|
13 |
+
print("Start Q&A Service")
|
14 |
+
return self
|
15 |
+
|
16 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
17 |
+
print("Exiting Q&A Service")
|
18 |
+
|
19 |
+
def retrieve_context(self):
|
20 |
+
"""Pass embedded question into pinecone"""
|
21 |
+
embedded_query = self.embedder.get_text_embedding(self.question)
|
22 |
+
pinecone_index = self.pc.Index(conf['embeddings']['index_name'])
|
23 |
+
|
24 |
+
result = pinecone_index.query(
|
25 |
+
vector=embedded_query,
|
26 |
+
top_k=1,
|
27 |
+
include_values=False,
|
28 |
+
include_metadata=True
|
29 |
+
)
|
30 |
+
|
31 |
+
output = json.loads(result['matches'][0]['metadata']['_node_content'])
|
32 |
+
|
33 |
+
return output
|
34 |
+
|
35 |
+
def run(self):
|
36 |
+
"""Query pinecone outputs and infer results"""
|
37 |
+
output = self.retrieve_context()
|
38 |
+
output = self.model.infer(output)
|
39 |
+
|
40 |
+
return output
|
41 |
+
|