Update app.py
Browse files
app.py
CHANGED
|
@@ -1,64 +1,147 @@
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from
|
| 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 |
-
token = message.choices[0].delta.content
|
| 38 |
-
|
| 39 |
-
response += token
|
| 40 |
-
yield response
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
"""
|
| 44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
| 45 |
-
"""
|
| 46 |
-
demo = gr.ChatInterface(
|
| 47 |
-
respond,
|
| 48 |
-
additional_inputs=[
|
| 49 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 50 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 51 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 52 |
-
gr.Slider(
|
| 53 |
-
minimum=0.1,
|
| 54 |
-
maximum=1.0,
|
| 55 |
-
value=0.95,
|
| 56 |
-
step=0.05,
|
| 57 |
-
label="Top-p (nucleus sampling)",
|
| 58 |
-
),
|
| 59 |
-
],
|
| 60 |
)
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
if __name__ == "__main__":
|
| 64 |
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import chromadb
|
| 3 |
import gradio as gr
|
| 4 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, pipeline
|
| 5 |
+
from langchain_chroma import Chroma
|
| 6 |
+
from langchain_huggingface import HuggingFaceEmbeddings, HuggingFacePipeline
|
| 7 |
+
from langchain.document_loaders import PyPDFLoader
|
| 8 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 9 |
+
from langchain.chains import create_retrieval_chain, LLMChain
|
| 10 |
+
from langchain.prompts import PromptTemplate
|
| 11 |
+
from collections import OrderedDict
|
| 12 |
+
|
| 13 |
+
# Load embeddings model
|
| 14 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 15 |
+
|
| 16 |
+
# Load Chroma database (Avoid reprocessing documents)
|
| 17 |
+
CHROMA_PATH = "./chroma_db"
|
| 18 |
+
if not os.path.exists(CHROMA_PATH):
|
| 19 |
+
raise FileNotFoundError("ChromaDB folder not found. Make sure it's uploaded to the repo.")
|
| 20 |
+
|
| 21 |
+
chroma_client = chromadb.PersistentClient(path=CHROMA_PATH)
|
| 22 |
+
db = Chroma(embedding_function=embeddings, client=chroma_client)
|
| 23 |
+
|
| 24 |
+
# Load the model
|
| 25 |
+
model_name = "google/flan-t5-large"
|
| 26 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 27 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
|
| 28 |
+
|
| 29 |
+
# Create pipeline
|
| 30 |
+
qa_pipeline = pipeline(
|
| 31 |
+
"text2text-generation",
|
| 32 |
+
model=model,
|
| 33 |
+
tokenizer=tokenizer,
|
| 34 |
+
device=0,
|
| 35 |
+
max_length=512,
|
| 36 |
+
min_length=50,
|
| 37 |
+
do_sample=False,
|
| 38 |
+
repetition_penalty=1.2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
)
|
| 40 |
|
| 41 |
+
# Wrap pipeline in LangChain
|
| 42 |
+
llm = HuggingFacePipeline(pipeline=qa_pipeline)
|
| 43 |
+
retriever = db.as_retriever(search_kwargs={"k": 3})
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def clean_context(context_list, max_tokens=350, min_length=50):
|
| 47 |
+
"""
|
| 48 |
+
Cleans retrieved document context:
|
| 49 |
+
- Removes duplicates while preserving order
|
| 50 |
+
- Limits total token count
|
| 51 |
+
- Ensures useful, non-repetitive context
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
# Preserve order while removing duplicates
|
| 55 |
+
unique_texts = list(OrderedDict.fromkeys([doc.page_content.strip() for doc in context_list]))
|
| 56 |
+
|
| 57 |
+
# Remove very short texts (e.g., headers)
|
| 58 |
+
filtered_texts = [text for text in unique_texts if len(text.split()) > min_length]
|
| 59 |
+
|
| 60 |
+
# Avoid near-duplicate entries
|
| 61 |
+
deduplicated_texts = []
|
| 62 |
+
seen_texts = set()
|
| 63 |
+
for text in filtered_texts:
|
| 64 |
+
if not any(text in s for s in seen_texts): # Avoid near-duplicates
|
| 65 |
+
deduplicated_texts.append(text)
|
| 66 |
+
seen_texts.add(text)
|
| 67 |
+
|
| 68 |
+
# Limit context based on token count
|
| 69 |
+
trimmed_context = []
|
| 70 |
+
total_tokens = 0
|
| 71 |
+
for text in deduplicated_texts:
|
| 72 |
+
tokenized_text = tokenizer.encode(text, add_special_tokens=False)
|
| 73 |
+
token_count = len(tokenized_text)
|
| 74 |
+
|
| 75 |
+
if total_tokens + token_count > max_tokens:
|
| 76 |
+
remaining_tokens = max_tokens - total_tokens
|
| 77 |
+
if remaining_tokens > 20:
|
| 78 |
+
trimmed_context.append(tokenizer.decode(tokenized_text[:remaining_tokens]))
|
| 79 |
+
break
|
| 80 |
+
|
| 81 |
+
trimmed_context.append(text)
|
| 82 |
+
total_tokens += token_count
|
| 83 |
+
|
| 84 |
+
return "\n\n".join(trimmed_context) if trimmed_context else "No relevant context found."
|
| 85 |
+
|
| 86 |
+
# Define prompt
|
| 87 |
+
prompt_template = PromptTemplate(
|
| 88 |
+
template="""
|
| 89 |
+
You are a Kubernetes instructor. Answer the question based on the provided context.
|
| 90 |
+
If the context does not provide an answer, say "I don't have enough information."
|
| 91 |
+
|
| 92 |
+
Context:
|
| 93 |
+
{context}
|
| 94 |
+
|
| 95 |
+
Question:
|
| 96 |
+
{input}
|
| 97 |
+
|
| 98 |
+
Answer:
|
| 99 |
+
""",
|
| 100 |
+
input_variables=["context", "input"]
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
llm_chain = LLMChain(llm=llm, prompt=prompt_template)
|
| 104 |
+
qa_chain = create_retrieval_chain(retriever, llm_chain)
|
| 105 |
+
|
| 106 |
+
# Query function
|
| 107 |
+
def get_k8s_answer(query):
|
| 108 |
+
retrieved_context = retriever.get_relevant_documents(query)
|
| 109 |
+
cleaned_context = clean_context(retrieved_context, max_tokens=350) # Ensure context size is within limits
|
| 110 |
+
|
| 111 |
+
# Ensure total input tokens < 512 before passing to model
|
| 112 |
+
input_text = f"Context:\n{cleaned_context}\n\nQuestion: {query}\nAnswer:"
|
| 113 |
+
total_tokens = len(tokenizer.encode(input_text, add_special_tokens=True))
|
| 114 |
+
|
| 115 |
+
if total_tokens > 512:
|
| 116 |
+
# Trim context further to fit within the limit
|
| 117 |
+
allowed_tokens = 512 - len(tokenizer.encode(query, add_special_tokens=True)) - 50 # 50 tokens for the model's response
|
| 118 |
+
cleaned_context = clean_context(retrieved_context, max_tokens=allowed_tokens)
|
| 119 |
+
|
| 120 |
+
# Recalculate total tokens
|
| 121 |
+
input_text = f"Context:\n{cleaned_context}\n\nQuestion: {query}\nAnswer:"
|
| 122 |
+
total_tokens = len(tokenizer.encode(input_text, add_special_tokens=True))
|
| 123 |
+
|
| 124 |
+
if total_tokens > 512:
|
| 125 |
+
return "Error: Even after trimming, input is too large."
|
| 126 |
+
|
| 127 |
+
response = qa_chain.invoke({"input": query, "context": cleaned_context})
|
| 128 |
+
return response
|
| 129 |
+
|
| 130 |
+
def get_k8s_answer_text(query):
|
| 131 |
+
model_full_answer = get_k8s_answer(query)
|
| 132 |
+
if 'answer' in model_full_answer.keys():
|
| 133 |
+
if 'text' in model_full_answer['answer'].keys():
|
| 134 |
+
return model_full_answer['answer']['text']
|
| 135 |
+
return "Error"
|
| 136 |
+
|
| 137 |
+
# Gradio Interface
|
| 138 |
+
demo = gr.Interface(
|
| 139 |
+
fn=get_k8s_answer_text,
|
| 140 |
+
inputs=gr.Textbox(label="Ask a Kubernetes Question"),
|
| 141 |
+
outputs=gr.Textbox(label="Answer"),
|
| 142 |
+
title="Kubernetes RAG Assistant",
|
| 143 |
+
description="Ask any Kubernetes-related question and get a step-by-step answer based on documentation."
|
| 144 |
+
)
|
| 145 |
|
| 146 |
if __name__ == "__main__":
|
| 147 |
demo.launch()
|