File size: 4,235 Bytes
00af526
dddfd41
 
 
 
 
00af526
11a1fa9
 
 
00af526
 
dddfd41
00af526
 
 
 
 
 
 
 
 
dddfd41
 
 
 
 
4e5ac28
b7fe168
 
4e5ac28
b7fe168
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dddfd41
 
4e5ac28
dddfd41
 
 
 
b7fe168
 
a616932
dddfd41
 
 
 
 
 
 
 
 
 
 
 
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import os
from langchain_community.vectorstores import Qdrant
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain.prompts import PromptTemplate
from utils import setup_openai_embeddings,setup_qdrant_client,openai_llm,format_document_metadata
from dotenv import load_dotenv
from langchain.retrievers.contextual_compression import ContextualCompressionRetriever
from langchain_cohere import CohereRerank
from langchain_community.llms import Cohere
from langfuse.callback import CallbackHandler
load_dotenv()

os.environ["LANGFUSE_PUBLIC_KEY"] = os.getenv("LANGFUSE_PUBLIC_KEY")
os.environ["LANGFUSE_SECRET_KEY"] = os.getenv("LANGFUSE_SECRET_KEY")
os.environ["LANGFUSE_HOST"] = os.getenv("LANGFUSE_HOST") 


 
langfuse_handler = CallbackHandler()

 
def retrieve_documents_from_collection(query, api_key, qdrant_url, qdrant_api_key, collection_name):
    """Retrieve documents based on the specified query from a specific collection."""
    embeddings_model = setup_openai_embeddings(api_key)
    qdrant_client = setup_qdrant_client(qdrant_url, qdrant_api_key)
    qdrant = Qdrant(client=qdrant_client, collection_name=collection_name, embeddings=embeddings_model)
    retriever = qdrant.as_retriever(search_kwargs={"k": 20})
    llm = Cohere(temperature=0,cohere_api_key=os.getenv('COHERE_AI_KEY'))
    compressor = CohereRerank(cohere_api_key=os.getenv('COHERE_AI_KEY'),top_n=5)
    compression_retriever = ContextualCompressionRetriever(
    base_compressor=compressor, base_retriever=retriever
        )
    prompt=PromptTemplate(

    template="""
    # Your role
    You are a brilliant expert at understanding the intent of the questioner and the crux of the question, and providing the most optimal answer  from the docs to the questioner's needs from the documents you are given.


    # Instruction
    Your task is to answer the question  using the following pieces of retrieved context delimited by XML tags.

    <retrieved context>
    Retrieved Context:
    {context}
    </retrieved context>


    # Constraint
    1. Think deeply and multiple times about the user's question\nUser's question:\n{question}\nYou must understand the intent of their question and provide the most appropriate answer.
    - Ask yourself why to understand the context of the question and why the questioner asked it, reflect on it, and provide an appropriate response based on what you understand.
    2. Choose the most relevant content(the key content that directly relates to the question) from the retrieved context and use it to generate an answer.
    3. Generate a concise, logical answer. When generating the answer, Do Not just list your selections, But rearrange them in context so that they become paragraphs with a natural flow.
    4. When you don't have retrieved context for the question or If you have a retrieved documents, but their content is irrelevant to the question, you should answer 'I can't find the answer to that question in the material I have'.
    5. If required break the answer into proper paragraphs.
    6. Mention Name of all the documents and page number you used in generating the response from the context provided . e.g 1. Doc name : RSCA/etienne.pdf, Page number: 1 /n 2. Doc name : RSCA/rubric.pdf, Page number: 10. Remeber to include all of the Document names and pages. Dont missout


    # Question:
    {question}""",
    input_variables=["context","question"]
        )
    llm = openai_llm(api_key=api_key)
    rag_chain = (
        {"context": compression_retriever | format_document_metadata, "question": RunnablePassthrough()}
        | prompt
        | llm
        | StrOutputParser()
    )
    return rag_chain.invoke(query,{"callbacks":[langfuse_handler]})



def delete_collection(collection_name, qdrant_url, qdrant_api_key):
    """Delete a Qdrant collection."""
    client = setup_qdrant_client(qdrant_url, qdrant_api_key)
    try:
        client.delete_collection(collection_name=collection_name)
    except Exception as e:
        print("Failed to delete collection:", e)

def is_document_embedded(filename):
    """Check if a document is already embedded. Actual implementation needed."""
    return False