Spaces:
Sleeping
Sleeping
Upload 3 files
Browse files- config.py +23 -0
- knowledge_engine.py +184 -0
- lisa_hr_agent.py +120 -0
config.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
|
| 3 |
+
class Config:
|
| 4 |
+
"""Configuration class for all system settings"""
|
| 5 |
+
# File paths
|
| 6 |
+
KNOWLEDGE_DIR = Path("knowledge_base") # Directory for all knowledge files
|
| 7 |
+
VECTOR_STORE_PATH = Path("vector_store") # Directory for FAISS index
|
| 8 |
+
BM25_STORE_PATH = Path("vector_store/bm25.pkl") # Serialized BM25 retriever
|
| 9 |
+
|
| 10 |
+
# Text processing
|
| 11 |
+
CHUNK_SIZE = 1000 # Optimal for balance between context and retrieval
|
| 12 |
+
CHUNK_OVERLAP = 200
|
| 13 |
+
MAX_CONTEXT_CHUNKS = 5 # Number of chunks to retrieve
|
| 14 |
+
|
| 15 |
+
# Performance
|
| 16 |
+
CACHE_EXPIRY_HOURS = 24
|
| 17 |
+
RELEVANCE_THRESHOLD = 0.72 # Strict similarity threshold
|
| 18 |
+
|
| 19 |
+
@classmethod
|
| 20 |
+
def setup_dirs(cls):
|
| 21 |
+
"""Ensure required directories exist"""
|
| 22 |
+
cls.KNOWLEDGE_DIR.mkdir(exist_ok=True)
|
| 23 |
+
cls.VECTOR_STORE_PATH.mkdir(exist_ok=True)
|
knowledge_engine.py
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ict, Any
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 6 |
+
|
| 7 |
+
from config import Config
|
| 8 |
+
|
| 9 |
+
# Core ML/AI libraries
|
| 10 |
+
from langchain_community.document_loaders import TextLoader, DirectoryLoader
|
| 11 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 12 |
+
from langchain_community.vectorstores import FAISS
|
| 13 |
+
from langchain_community.embeddings import OllamaEmbeddings
|
| 14 |
+
from langchain.chains import RetrievalQA
|
| 15 |
+
from langchain.prompts import PromptTemplate
|
| 16 |
+
from langchain_community.llms import Ollama
|
| 17 |
+
from langchain.retrievers import BM25Retriever
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class KnowledgeManager:
|
| 21 |
+
"""Main knowledge management class handling document processing and Q&A with CoT & MoE routing"""
|
| 22 |
+
|
| 23 |
+
def __init__(self):
|
| 24 |
+
Config.setup_dirs()
|
| 25 |
+
self.embeddings = OllamaEmbeddings(model="mxbai-embed-large")
|
| 26 |
+
self.vector_db, self.bm25_retriever = self._init_retrievers()
|
| 27 |
+
self.qa_chain = self._create_moe_qa_chain()
|
| 28 |
+
|
| 29 |
+
def _init_retrievers(self):
|
| 30 |
+
faiss_index_path = Config.VECTOR_STORE_PATH / "index.faiss"
|
| 31 |
+
faiss_pkl_path = Config.VECTOR_STORE_PATH / "index.pkl"
|
| 32 |
+
|
| 33 |
+
if faiss_index_path.exists() and faiss_pkl_path.exists():
|
| 34 |
+
try:
|
| 35 |
+
vector_db = FAISS.load_local(
|
| 36 |
+
str(Config.VECTOR_STORE_PATH),
|
| 37 |
+
self.embeddings,
|
| 38 |
+
allow_dangerous_deserialization=True
|
| 39 |
+
)
|
| 40 |
+
if Config.BM25_STORE_PATH.exists():
|
| 41 |
+
with open(Config.BM25_STORE_PATH, "rb") as f:
|
| 42 |
+
bm25_retriever = pickle.load(f)
|
| 43 |
+
return vector_db, bm25_retriever
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"[!] Error loading existing vector store: {e}. Rebuilding...")
|
| 46 |
+
|
| 47 |
+
return self._build_retrievers_from_documents()
|
| 48 |
+
|
| 49 |
+
def _build_retrievers_from_documents(self):
|
| 50 |
+
if not any(Config.KNOWLEDGE_DIR.glob("**/*.txt")):
|
| 51 |
+
print("[i] No knowledge files found. Creating default base...")
|
| 52 |
+
self._create_default_knowledge()
|
| 53 |
+
|
| 54 |
+
loader = DirectoryLoader(
|
| 55 |
+
str(Config.KNOWLEDGE_DIR),
|
| 56 |
+
glob="**/*.txt",
|
| 57 |
+
loader_cls=TextLoader,
|
| 58 |
+
loader_kwargs={'encoding': 'utf-8'}
|
| 59 |
+
)
|
| 60 |
+
docs = loader.load()
|
| 61 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 62 |
+
chunk_size=Config.CHUNK_SIZE,
|
| 63 |
+
chunk_overlap=Config.CHUNK_OVERLAP,
|
| 64 |
+
separators=["\n\n", "\n", ". ", "! ", "? ", "; ", " ", ""]
|
| 65 |
+
)
|
| 66 |
+
chunks = splitter.split_documents(docs)
|
| 67 |
+
|
| 68 |
+
vector_db = FAISS.from_documents(chunks, self.embeddings)
|
| 69 |
+
vector_db.save_local(str(Config.VECTOR_STORE_PATH))
|
| 70 |
+
|
| 71 |
+
bm25_retriever = BM25Retriever.from_documents(chunks)
|
| 72 |
+
bm25_retriever.k = Config.MAX_CONTEXT_CHUNKS
|
| 73 |
+
|
| 74 |
+
with open(Config.BM25_STORE_PATH, "wb") as f:
|
| 75 |
+
pickle.dump(bm25_retriever, f)
|
| 76 |
+
|
| 77 |
+
return vector_db, bm25_retriever
|
| 78 |
+
|
| 79 |
+
def _create_default_knowledge(self):
|
| 80 |
+
default_text = """Sirraya xBrain - Advanced AI Platform\n\nCreated by Amir Hameed.\n\nFeatures:\n- Hybrid Retrieval (Vector + BM25)\n- LISA Assistant\n- FAISS, Ollama, BM25 Integration"""
|
| 81 |
+
with open(Config.KNOWLEDGE_DIR / "sirraya_xbrain.txt", "w", encoding="utf-8") as f:
|
| 82 |
+
f.write(default_text)
|
| 83 |
+
|
| 84 |
+
def _parallel_retrieve(self, question: str):
|
| 85 |
+
"""Parallel retrieval execution: simulates Mixture of Experts routing"""
|
| 86 |
+
|
| 87 |
+
def retrieve_with_bm25():
|
| 88 |
+
return self.bm25_retriever.get_relevant_documents(question)
|
| 89 |
+
|
| 90 |
+
def retrieve_with_vector():
|
| 91 |
+
# Lowered threshold to 0.3 for better doc retrieval (adjust as needed)
|
| 92 |
+
retriever = self.vector_db.as_retriever(
|
| 93 |
+
search_type="similarity_score_threshold",
|
| 94 |
+
search_kwargs={"k": Config.MAX_CONTEXT_CHUNKS, "score_threshold": 0.83}
|
| 95 |
+
)
|
| 96 |
+
return retriever.get_relevant_documents(question)
|
| 97 |
+
|
| 98 |
+
with ThreadPoolExecutor(max_workers=2) as executor:
|
| 99 |
+
bm25_future = executor.submit(retrieve_with_bm25)
|
| 100 |
+
vector_future = executor.submit(retrieve_with_vector)
|
| 101 |
+
bm25_results = bm25_future.result()
|
| 102 |
+
vector_results = vector_future.result()
|
| 103 |
+
|
| 104 |
+
# Combine results; duplicates are possible, consider deduplication if needed
|
| 105 |
+
return vector_results + bm25_results
|
| 106 |
+
|
| 107 |
+
def _create_moe_qa_chain(self):
|
| 108 |
+
if not self.vector_db or not self.bm25_retriever:
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
prompt_template = """You are LISA, an AI assistant for Sirraya xBrain. Answer using the context below:
|
| 112 |
+
|
| 113 |
+
Context:
|
| 114 |
+
{context}
|
| 115 |
+
|
| 116 |
+
Question: {question}
|
| 117 |
+
|
| 118 |
+
Instructions:
|
| 119 |
+
- Use only the context.
|
| 120 |
+
- Be accurate and helpful.
|
| 121 |
+
- If unsure, say: "I don’t have that information in my knowledge base."
|
| 122 |
+
|
| 123 |
+
Answer:"""
|
| 124 |
+
|
| 125 |
+
return RetrievalQA.from_chain_type(
|
| 126 |
+
llm=Ollama(model="phi", temperature=0.1),
|
| 127 |
+
chain_type="stuff",
|
| 128 |
+
retriever=self.vector_db.as_retriever(search_kwargs={"k": 1}), # Dummy retriever to satisfy LangChain
|
| 129 |
+
chain_type_kwargs={
|
| 130 |
+
"prompt": PromptTemplate(
|
| 131 |
+
template=prompt_template,
|
| 132 |
+
input_variables=["context", "question"]
|
| 133 |
+
)
|
| 134 |
+
},
|
| 135 |
+
return_source_documents=True
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
def query(self, question: str) -> Dict[str, Any]:
|
| 139 |
+
"""Query system using CoT + MoE logic"""
|
| 140 |
+
if not self.qa_chain:
|
| 141 |
+
return {
|
| 142 |
+
"answer": "Knowledge system not initialized. Please reload.",
|
| 143 |
+
"processing_time": 0,
|
| 144 |
+
"source_chunks": []
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
try:
|
| 148 |
+
start_time = datetime.now()
|
| 149 |
+
docs = self._parallel_retrieve(question)
|
| 150 |
+
|
| 151 |
+
# If no docs found, fallback to retriever without threshold for testing
|
| 152 |
+
if not docs:
|
| 153 |
+
retriever = self.vector_db.as_retriever(search_kwargs={"k": Config.MAX_CONTEXT_CHUNKS})
|
| 154 |
+
docs = retriever.get_relevant_documents(question)
|
| 155 |
+
|
| 156 |
+
# Use invoke() for chains with multiple outputs
|
| 157 |
+
result = self.qa_chain.invoke({"input_documents": docs, "query": question})
|
| 158 |
+
|
| 159 |
+
processing_time = (datetime.now() - start_time).total_seconds() * 1000
|
| 160 |
+
|
| 161 |
+
return {
|
| 162 |
+
"answer": result.get("result", ""),
|
| 163 |
+
"processing_time": processing_time,
|
| 164 |
+
"source_chunks": result.get("source_documents", [])
|
| 165 |
+
}
|
| 166 |
+
except Exception as e:
|
| 167 |
+
print(f"[!] Query error: {e}")
|
| 168 |
+
return {
|
| 169 |
+
"answer": f"Error: {e}",
|
| 170 |
+
"processing_time": 0,
|
| 171 |
+
"source_chunks": []
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
def get_knowledge_files_count(self) -> int:
|
| 175 |
+
return len(list(Config.KNOWLEDGE_DIR.glob("**/*.txt"))) if Config.KNOWLEDGE_DIR.exists() else 0
|
| 176 |
+
|
| 177 |
+
def save_uploaded_file(self, uploaded_file, filename: str) -> bool:
|
| 178 |
+
try:
|
| 179 |
+
with open(Config.KNOWLEDGE_DIR / filename, "wb") as f:
|
| 180 |
+
f.write(uploaded_file.getbuffer())
|
| 181 |
+
return True
|
| 182 |
+
except Exception as e:
|
| 183 |
+
print(f"[!] File save error: {e}")
|
| 184 |
+
return False
|
lisa_hr_agent.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# lisa_hr_agent.py
|
| 2 |
+
|
| 3 |
+
from langchain_community.llms import Ollama
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from reportlab.lib.pagesizes import A4
|
| 6 |
+
from reportlab.pdfgen import canvas
|
| 7 |
+
from reportlab.lib.units import inch
|
| 8 |
+
import textwrap
|
| 9 |
+
|
| 10 |
+
class LISAHRAgent:
|
| 11 |
+
def __init__(self):
|
| 12 |
+
self.memory = {}
|
| 13 |
+
self.questions = [
|
| 14 |
+
("name", "What is the full name of the selected candidate?"),
|
| 15 |
+
("job_title", "What is the job title offered?"),
|
| 16 |
+
("salary", "What is the monthly salary offered (in Rs.)?"),
|
| 17 |
+
("joining_date", "What is the joining date? (e.g., 5 June 2025)"),
|
| 18 |
+
("probation_period", "What is the probation period? (e.g., 3 months)?"),
|
| 19 |
+
("location", "What is the job location?")
|
| 20 |
+
]
|
| 21 |
+
self.index = 0
|
| 22 |
+
|
| 23 |
+
def ask_next(self):
|
| 24 |
+
if self.index < len(self.questions):
|
| 25 |
+
return self.questions[self.index][1]
|
| 26 |
+
return None
|
| 27 |
+
|
| 28 |
+
def receive_answer(self, answer):
|
| 29 |
+
key = self.questions[self.index][0]
|
| 30 |
+
self.memory[key] = answer
|
| 31 |
+
self.index += 1
|
| 32 |
+
|
| 33 |
+
def is_complete(self):
|
| 34 |
+
return self.index >= len(self.questions)
|
| 35 |
+
|
| 36 |
+
def get_inputs(self):
|
| 37 |
+
return {
|
| 38 |
+
**self.memory,
|
| 39 |
+
"today": datetime.today().strftime("%d %B %Y")
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
def generate_letter_with_llm(data: dict) -> str:
|
| 43 |
+
llm = Ollama(model="phi") # You can change model if you like
|
| 44 |
+
|
| 45 |
+
prompt = f"""
|
| 46 |
+
You are a professional HR assistant. Write a detailed and formal appointment letter for a selected candidate with the following information:
|
| 47 |
+
|
| 48 |
+
Candidate Name: {data['name']}
|
| 49 |
+
Job Title: {data['job_title']}
|
| 50 |
+
Monthly Salary: Rs. {data['salary']}
|
| 51 |
+
Joining Date: {data['joining_date']}
|
| 52 |
+
Probation Period: {data['probation_period']}
|
| 53 |
+
Location: {data['location']}
|
| 54 |
+
Date of Letter: {data['today']}
|
| 55 |
+
Company Name: Amsaa
|
| 56 |
+
Founder: Amir Hameed
|
| 57 |
+
|
| 58 |
+
Instructions:
|
| 59 |
+
- This is an appointment letter, the candidate has already been selected.
|
| 60 |
+
- Include a letterhead title at the top: "Amsaa – Appointment Letter"
|
| 61 |
+
- Start with date, recipient name, and subject ("Appointment for the position of [Job Title]")
|
| 62 |
+
- Include details like reporting authority, job location, salary in Rs., joining date, probation period.
|
| 63 |
+
- Maintain a professional and polite tone throughout.
|
| 64 |
+
- Add a paragraph welcoming the candidate and emphasizing the company’s vision and values.
|
| 65 |
+
- Conclude with "Sincerely, Amir Hameed, Founder & CEO, Amsaa"
|
| 66 |
+
- Format should be clean and easy to read.
|
| 67 |
+
"""
|
| 68 |
+
response = llm.invoke(prompt)
|
| 69 |
+
return response.strip()
|
| 70 |
+
|
| 71 |
+
def save_letter_as_pdf(content: str, filename="appointment_letter.pdf"):
|
| 72 |
+
c = canvas.Canvas(filename, pagesize=A4)
|
| 73 |
+
width, height = A4
|
| 74 |
+
margin = 50
|
| 75 |
+
y_position = height - margin
|
| 76 |
+
|
| 77 |
+
# Header
|
| 78 |
+
c.setFont("Helvetica-Bold", 16)
|
| 79 |
+
c.drawString(margin, y_position, "Amsaa – Appointment Letter")
|
| 80 |
+
y_position -= 30
|
| 81 |
+
|
| 82 |
+
c.setFont("Helvetica", 12)
|
| 83 |
+
# Wrap and draw each line
|
| 84 |
+
for line in content.split('\n'):
|
| 85 |
+
if not line.strip():
|
| 86 |
+
y_position -= 12
|
| 87 |
+
continue
|
| 88 |
+
wrapped_lines = textwrap.wrap(line, width=95)
|
| 89 |
+
for wrap_line in wrapped_lines:
|
| 90 |
+
c.drawString(margin, y_position, wrap_line)
|
| 91 |
+
y_position -= 14
|
| 92 |
+
if y_position < 50: # Add new page if needed
|
| 93 |
+
c.showPage()
|
| 94 |
+
y_position = height - margin
|
| 95 |
+
c.setFont("Helvetica", 12)
|
| 96 |
+
|
| 97 |
+
c.save()
|
| 98 |
+
print(f"\n[✓] Appointment letter saved as: {filename}")
|
| 99 |
+
|
| 100 |
+
def main():
|
| 101 |
+
agent = LISAHRAgent()
|
| 102 |
+
|
| 103 |
+
print("\n👩💼 Welcome to LISA HR — AI HR Assistant (Powered by LLM)\n")
|
| 104 |
+
|
| 105 |
+
while not agent.is_complete():
|
| 106 |
+
question = agent.ask_next()
|
| 107 |
+
answer = input(f"{question} ")
|
| 108 |
+
agent.receive_answer(answer)
|
| 109 |
+
|
| 110 |
+
print("\n🧠 Generating Appointment Letter with LLM...\n")
|
| 111 |
+
collected_data = agent.get_inputs()
|
| 112 |
+
letter = generate_letter_with_llm(collected_data)
|
| 113 |
+
|
| 114 |
+
save_letter_as_pdf(letter)
|
| 115 |
+
|
| 116 |
+
print("\n📄 Preview:\n")
|
| 117 |
+
print(letter)
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
main()
|