-
Notifications
You must be signed in to change notification settings - Fork 578
/
Copy pathfind_relevant_chunks.py
71 lines (58 loc) · 1.83 KB
/
find_relevant_chunks.py
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
import os
from dotenv import load_dotenv
from openai import OpenAI
from pymongo import MongoClient
load_dotenv()
open_ai_key = os.getenv("OPENAI_API_KEY1")
print(f"----OpenAI Key in find chunks is {open_ai_key}")
openai_client = OpenAI(api_key=open_ai_key)
"""
@retry(wait=wait_random_exponential(min=1, max=1), stop=stop_after_attempt(6))
def chat_completion_backoff(**kwargs):
return openai_client.chat.completions.create(**kwargs)
@retry(wait=wait_random_exponential(min=1, max=1), stop=stop_after_attempt(6))
def embedding_create_backoff(**kwargs):
return openai_client.embeddings.create(**kwargs)
"""
def find_chunks(question):
docs = []
min_chunk_size = 500
max_chunk_size = 2000
delimiter = ". "
# openai_client = OpenAI()
k = 3
multiplier = 10
# embeddings = embedding_create_backoff(
# input=question,
# model="text-embedding-ada-002"
# )
embeddings = openai_client.embeddings.create(
input=question, model="text-embedding-ada-002"
)
query_vector = embeddings.data[0].embedding
agg_pipeline = [
{
"$vectorSearch": {
"index": "vector_index",
"path": "embedding",
"queryVector": query_vector,
"limit": k,
"numCandidates": k * multiplier,
},
},
{"$project": {"embedding": 0}},
]
tag_docs = []
try:
uri = os.getenv("ATLAS_CONNECTION_STRING")
client = MongoClient(uri)
database = client["langchain_db"]
collection = database["knowledge_graph"]
cursor = collection.aggregate(agg_pipeline)
for tag in cursor:
tag_docs.append(tag)
except Exception as e:
print(e)
finally:
client.close()
return tag_docs