| 1 | from openai import OpenAI |
| 2 | from src.utils import get_completion |
| 3 | import qdrant_client |
| 4 | import re |
| 5 | |
| 6 | # # # Initialize connections |
| 7 | client = OpenAI() |
| 8 | qdrant = qdrant_client.QdrantClient(host='localhost')#, prefer_grpc=True) |
| 9 | |
| 10 | # # Set embedding model |
| 11 | # # TODO: Add this to global config |
| 12 | EMBEDDING_MODEL = 'text-embedding-3-large' |
| 13 | |
| 14 | # # # Set qdrant collection |
| 15 | collection_name = 'help_center' |
| 16 | |
| 17 | # # # Query function for qdrant |
| 18 | def query_qdrant(query, collection_name, vector_name='article', top_k=5): |
| 19 | # Creates embedding vector from user query |
| 20 | embedded_query = client.embeddings.create( |
| 21 | input=query, |
| 22 | model=EMBEDDING_MODEL, |
| 23 | ).data[0].embedding |
| 24 | |
| 25 | query_results = qdrant.search( |
| 26 | collection_name=collection_name, |
| 27 | query_vector=( |
| 28 | vector_name, embedded_query |
| 29 | ), |
| 30 | limit=top_k, |
| 31 | ) |
| 32 | |
| 33 | return query_results |
| 34 | |
| 35 | |
| 36 | def query_docs(query): |
| 37 | print(f'Searching knowledge base with query: {query}') |
| 38 | query_results = query_qdrant(query,collection_name=collection_name) |
| 39 | output = [] |
| 40 | |
| 41 | for i, article in enumerate(query_results): |
| 42 | title = article.payload["title"] |
| 43 | text = article.payload["text"] |
| 44 | url = article.payload["url"] |
| 45 | |
| 46 | output.append((title,text,url)) |
| 47 | |
| 48 | if output: |
| 49 | title, content, _ = output[0] |
| 50 | response = f"Title: {title}\nContent: {content}" |
| 51 | truncated_content = re.sub(r'\s+', ' ', content[:50] + '...' if len(content) > 50 else content) |
| 52 | print('Most relevant article title:', truncated_content) |
| 53 | return {'response': response} |
| 54 | else: |
| 55 | print('no results') |
| 56 | return {'response': 'No results found.'} |