-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqa_chain.py
More file actions
60 lines (44 loc) · 1.36 KB
/
Copy pathqa_chain.py
File metadata and controls
60 lines (44 loc) · 1.36 KB
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
import os
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnableMap
from retrieval import retriever
from re_ranker import rerank_documents
from query_expansion import query_expansion_chain
from dotenv import load_dotenv
load_dotenv()
GROQ_API = os.getenv("GROQ_API_KEY")
llm = ChatGroq(
model="openai/gpt-oss-120b",
api_key= GROQ_API
)
prompt = ChatPromptTemplate.from_template(
"""Answer the question based on the following context below.
Context:
{context}
Question:
{question}
Answer:"""
)
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
def get_context(x):
expanded_query = query_expansion_chain.invoke({"query": x["question"]})
retrieved_docs = retriever.invoke(expanded_query)
reranked_docs = rerank_documents(x["question"], retrieved_docs, top_n=3)
return format_docs(reranked_docs)
rag_pipeline = (
RunnableMap({
"context": get_context,
"question": lambda x: x["question"],
})
| prompt
| llm
| StrOutputParser()
)
if __name__=="__main__":
question = "covering index"
answer = rag_pipeline.invoke({"question": question})
print(f"Question: {question}\n")
print(f"Answer: {answer}")