Repository navigation
Expand file tree
/
Copy pathrag_pipeline.py
More file actions
93 lines (67 loc) · 2.21 KB
/
Copy pathrag_pipeline.py
File metadata and controls
93 lines (67 loc) · 2.21 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
84
85
86
87
88
89
90
91
"""
rag_pipeline.py
This module is responsible for:
1. Retrieving relevant documents from ChromaDB.
2. Creating context from the retrieved documents.
3. Preparing the prompt for the LLM.
4. Sending the prompt to the LLM.
5. Returning the final response.
"""
from langchain_core.prompts import PromptTemplate
from langchain_ollama import ChatOllama
from config import LLM_MODEL
def generate_response(retriever, question):
"""
Generate a response using the RAG pipeline.
Args:
retriever: LangChain retriever object
question (str): User question
Returns:
str: Response generated by the LLM
"""
# Step 1: Retrieve relevant documents from ChromaDB
retrieved_docs = retriever.invoke(question)
print("\n" + "=" * 60)
print(f"Retrieved Documents: {len(retrieved_docs)}")
for i, doc in enumerate(retrieved_docs):
print(f"\nDocument {i+1}")
print("Source:", doc.metadata.get("source", "Unknown"))
print("Preview:")
print(doc.page_content[:300])
print("=" * 60)
# Step 2: Combine all retrieved document text into one context
context = "\n\n".join(
doc.page_content for doc in retrieved_docs
)
# Step 3: Create the Prompt Template
prompt = PromptTemplate(
input_variables=["context", "question"],
template="""
You are an expert DevOps Engineer specializing in AWS, Kubernetes,
Docker, Linux, Terraform, Jenkins, CI/CD and Python.
Use ONLY the information provided in the given context to answer the user's question.
If the answer is not available in the context, reply exactly:
"I don't have enough information in the knowledge base."
Do not make up any information.
Context:
{context}
Question:
{question}
Answer:
"""
)
# Step 4: Replace placeholders with actual values
formatted_prompt = prompt.format(
context=context,
question=question
)
print("\nPrompt Preview")
print("=" * 60)
print(formatted_prompt[:1000])
print("=" * 60)
# Step 5: Initialize the LLM
llm = ChatOllama(model=LLM_MODEL)
# Step 6: Generate the response
response = llm.invoke(formatted_prompt)
# Step 7: Return only the response text
return response.content