Repository navigation
Expand file tree
/
Copy pathrag.py
More file actions
83 lines (61 loc) · 1.97 KB
/
Copy pathrag.py
File metadata and controls
83 lines (61 loc) · 1.97 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from langchain_groq import ChatGroq
from langchain_core.prompts import ChatPromptTemplate
from dotenv import load_dotenv
def create_context(results):
return '\n\n'.join(f"Page: {x.metadata['page']}\n{x.page_content}" for x in results)
def rewrite_query(query, chat_history):
history = '\n\n'.join(f'User: {message['question']}\nAI: {message['answer']}' for message in chat_history)
rewrite_prompt = ChatPromptTemplate.from_template(
"""
Given the conversation history and the user's latest question,
rewrite the latest question into a standalone question that can
be understood without the conversation history.
If the latest question is already standalone, return it unchanged.
Do not answer the question.
Conversation history:
{history}
Latest question:
{question}
Standalone question:
"""
)
prompt = rewrite_prompt.invoke({
'history' : history,
'question' : query
})
response = llm.invoke(prompt)
return response.content
prompt = ChatPromptTemplate.from_template(
"""
Use only the information provided in the retrieved passages.
Answer the question clearly and concisely.
If the passages do not contain enough information to answer the
question, say that the answer cannot be determined from the
provided passages.
Retrieved passages:
{context}
Question:
{question}
"""
)
load_dotenv()
llm = ChatGroq(
model = 'openai/gpt-oss-120b'
)
def answer_rag(vector_base, query, chat_history):
retriever = vector_base.as_retriever(
search_type = 'mmr',
search_kwargs = {
'k' : 5 ,
'fetch_k' : 20
}
)
rewritten_query = rewrite_query(query, chat_history)
results = retriever.invoke(rewritten_query)
context = create_context(results)
message = prompt.invoke({
'context' : context,
'question' : rewritten_query
})
response = llm.invoke(message)
return response.content, results