Create retriever.py
Browse files- retriever.py +45 -0
retriever.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Retriever function
|
| 2 |
+
|
| 3 |
+
from pinecone import Pinecone
|
| 4 |
+
from langchain_openai import AzureOpenAIEmbeddings
|
| 5 |
+
import uuid
|
| 6 |
+
import pandas as pd
|
| 7 |
+
|
| 8 |
+
# Initialize Pinecone client
|
| 9 |
+
pc = Pinecone(api_key="567aca04-6fb0-40a0-ba92-a5ed30be190b")
|
| 10 |
+
index = pc.Index("openai-serverless")
|
| 11 |
+
|
| 12 |
+
# Azure OpenAI configuration
|
| 13 |
+
os.environ["AZURE_OPENAI_API_KEY"] =
|
| 14 |
+
os.environ["AZURE_OPENAI_ENDPOINT"] = "https://davidfearn-gpt4.openai.azure.com/"
|
| 15 |
+
os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"] = "text-embedding-ada-002"
|
| 16 |
+
os.environ["AZURE_OPENAI_API_VERSION"] = "2024-08-01-preview"
|
| 17 |
+
|
| 18 |
+
# Model configuration
|
| 19 |
+
embeddings_model = AzureOpenAIEmbeddings(
|
| 20 |
+
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
|
| 21 |
+
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
|
| 22 |
+
openai_api_version=os.environ["AZURE_OPENAI_API_VERSION"],
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
def retriever(query, namespace="gskRegIntel", top_k=3):
|
| 26 |
+
"""
|
| 27 |
+
Embeds a query string and searches the vector database for similar entries.
|
| 28 |
+
|
| 29 |
+
:param query: The string to embed and search for.
|
| 30 |
+
:param namespace: Pinecone namespace to search within.
|
| 31 |
+
:param top_k: Number of top results to retrieve.
|
| 32 |
+
:return: List of search results with metadata and scores.
|
| 33 |
+
"""
|
| 34 |
+
try:
|
| 35 |
+
# Generate embedding for the query
|
| 36 |
+
query_embedding = embeddings_model.embed_query(query)
|
| 37 |
+
|
| 38 |
+
# Perform search in Pinecone
|
| 39 |
+
results = index.query(vector=query_embedding, top_k=top_k, namespace=namespace, include_metadata=True)
|
| 40 |
+
|
| 41 |
+
return results.matches
|
| 42 |
+
|
| 43 |
+
except Exception as e:
|
| 44 |
+
print(f"Error during search: {e}")
|
| 45 |
+
return []
|