import os
import glob
import shutil
from typing import List, Dict, Any, Optional
import re
import pandas as pd
from langchain_core.documents import Document
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
from langchain_text_splitters import RecursiveCharacterTextSampler, TextSplitter
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import OpenAIEmbeddings # Or use HuggingFaceEmbeddings etc.
from langchain_openai import ChatOpenAI # Or use HuggingFaceHub etc.
from langgraph.graph import StateGraph, END
from langgraph.graph.message import add_message, AnyMessage
# --- Configuration ---
FILES_DIR = "files"
RUBRIC_FILE = "rubric.xlsx"
MAPPING_FILE = "file_requirement_mapping.xlsx"
PERSIST_DIR = "./chroma_db" # Directory to persist the vector store
# Ensure directories exist
os.makedirs(FILES_DIR, exist_ok=True)
os.makedirs(PERSIST_DIR, exist_ok=True)
# --- LLM and Embedding Setup ---
# Use OpenAI models - replace or configure if using different providers
# Ensure OPENAI_API_KEY is set in your environment variables
try:
embeddings_model = OpenAIEmbeddings()
llm = ChatOpenAI(model="gpt-4o", temperature=0.2) # Using GPT-4o for better reasoning
# llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.2) # Alternative
except Exception as e:
print(f"Error initializing LLM/Embeddings: {e}")
print("Please ensure you have set the OPENAI_API_KEY environment variable.")
exit(1)
# --- Document Loading ---
# Map file extensions to LangChain loaders
# Note: 'unstructured' handles many types implicitly. Add explicit loaders if needed.
LOADER_MAP = {
".pdf": "langchain_community.document_loaders.PyPDFLoader",
".docx": "langchain_community.document_loaders.Docx2txtLoader",
".pptx": "langchain_community.document_loaders.UnstructuredPowerPointLoader",
".xlsx": "langchain_community.document_loaders.UnstructuredExcelLoader", # Reads sheets as docs
".md": "langchain_community.document_loaders.UnstructuredMarkdownLoader",
".txt": "langchain_community.document_loaders.TextLoader",
}
def load_unstructured_docs(directory_path: str) -> List[Document]:
"""Loads documents from various file types in a directory."""
all_docs = []
supported_extensions = list(LOADER_MAP.keys())
print(f"Scanning directory: {directory_path}")
for ext in supported_extensions:
# Glob pattern handles different file types
pattern = os.path.join(directory_path, f"**/*{ext}")
files = glob.glob(pattern, recursive=True)
print(f"Found {len(files)} files with extension '{ext}'")
for file_path in files:
try:
# Dynamically import and use the loader based on extension
# Simple approach: use unstructured if available for most types
if ext in [".pdf", ".docx", ".pptx", ".md", ".txt", ".xlsx"]:
# Use Unstructured for broader compatibility
from unstructured.partition.auto import partition
print(f" Partitioning: {os.path.basename(file_path)}...")
elements = partition(filename=file_path)
# Convert elements to LangChain Document format
for element in elements:
metadata = {
"source": file_path,
"page": getattr(element, 'page_number', None), # If available
"category": str(element.category) # e.g., title, narrative, table
}
# Clean up text content
text_content = re.sub(r'\s+', ' ', element.text).strip()
if text_content: # Only add if there's actual text
all_docs.append(Document(page_content=text_content, metadata=metadata))
# Fallback or specific loader if needed (less common with Unstructured)
# elif ext == ".txt":
# from langchain_community.document_loaders import TextLoader
# loader = TextLoader(file_path, encoding='utf-8')
# all_docs.extend(loader.load())
print(f" Successfully loaded {os.path.basename(file_path)}")
except ImportError as imp_err:
print(f" Skipping {os.path.basename(file_path)}: Missing dependency ({imp_err}). Try installing 'unstructured[local-inference]'.")
except Exception as e:
print(f" Error loading {os.path.basename(file_path)}: {e}")
print(f"Total documents loaded: {len(all_docs)}")
# Clean up empty documents potentially created by loaders
all_docs = [doc for doc in all_docs if doc.page_content and doc.page_content.strip()]
print(f"Total non-empty documents after cleanup: {len(all_docs)}")
return all_docs
# --- Document Splitting ---
def split_docs(documents: List[Document], chunk_size: int = 1000, chunk_overlap: int = 100) -> List[Document]:
"""Splits documents into chunks using RecursiveCharacterTextSplitter."""
# Using RecursiveCharacterTextSplitter as a practical approach for semantic chunking.
# More advanced methods exist (e.g., using sentence transformers), but this is a good start.
text_splitter = RecursiveCharacterTextSampler(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
# Add other separators if needed, e.g., ["\n\n", "\n", ". ", " "]
)
print(f"Splitting {len(documents)} documents...")
chunks = text_splitter.split_documents(documents)
print(f"Split into {len(chunks)} chunks.")
return chunks
# --- Vector Store ---
def setup_vectorstore(chunks: List[Document], embeddings: Any, persist_dir: str) -> Chroma:
"""Creates or loads a Chroma vector store."""
print("Setting up vector store...")
# Check if vectorstore already exists and is not empty
if os.path.exists(persist_dir) and len(os.listdir(persist_dir)) > 0:
try:
print(f"Loading existing vector store from {persist_dir}...")
vectorstore = Chroma(persist_directory=persist_dir, embedding_function=embeddings)
# Optional: Check if existing data matches the new chunks (e.g., by count or hash)
# For simplicity, we'll reload/recreate if directory exists.
# To properly update, you'd need to manage existing embeddings.
# Let's recreate for this example to ensure freshness, but add a check
print(f"Existing store loaded. Contains {vectorstore._collection.count()} documents.")
# Simple check: If chunk count differs significantly, consider recreating.
# For this example, we'll proceed assuming we want to potentially add/update.
# A cleaner approach might involve deleting and recreating if files change.
# Let's delete and recreate for simplicity in this example script.
print(f"Clearing existing Chroma DB at {persist_dir} for fresh indexing...")
del vectorstore # Remove the reference
shutil.rmtree(persist_dir)
os.makedirs(persist_dir)
print("Creating new vector store...")
vectorstore = Chroma.from_documents(
documents=chunks,
embedding=embeddings,
persist_directory=persist_dir
)
vectorstore.persist()
print("New vector store created and persisted.")
except Exception as e:
print(f"Error loading or recreating vector store: {e}")
print("Attempting to create a new one...")
# Fallback: Clear and create if loading failed unexpectedly
if os.path.exists(persist_dir):
shutil.rmtree(persist_dir)
os.makedirs(persist_dir)
vectorstore = Chroma.from_documents(
documents=chunks,
embedding=embeddings,
persist_directory=persist_dir
)
vectorstore.persist()
print("New vector store created and persisted after error.")
else:
print("Creating new vector store...")
if os.path.exists(persist_dir): # Clean up if it existed but was empty
shutil.rmtree(persist_dir)
os.makedirs(persist_dir)
vectorstore = Chroma.from_documents(
documents=chunks,
embedding=embeddings,
persist_directory=persist_dir
)
vectorstore.persist()
print("New vector store created and persisted.")
return vectorstore
# --- Excel Data Loading ---
def load_excel_data(file_path: str) -> Dict[str, pd.DataFrame]:
"""Loads data from Excel, handling multiple sheets if necessary."""
print(f"Loading Excel data from: {file_path}")
if not os.path.exists(file_path):
raise FileNotFoundError(f"Excel file not found: {file_path}")
try:
# Try reading with default engine first
excel_data = pd.read_excel(file_path, sheet_name=None) # Reads all sheets into a dict
print(f"Loaded sheets: {list(excel_data.keys())}")
return excel_data
except Exception as e:
print(f"Error loading {file_path}: {e}")
# Consider specific error handling for different Excel read issues if needed
return {}
# --- RAG Chain ---
def create_rag_chain(retriever, llm):
"""Creates the RAG chain."""
template = """
You are an AI assistant specializing in vendor risk assessment.
You need to evaluate a vendor's compliance against specific requirements based on provided documentation.
**Risk Requirement:**
{requirement_description}
**Assessment Criteria:**
{criteria_text}
**Context from Vendor Documents:**
{context}
**Task:**
Based *only* on the provided context, assess the vendor's compliance with the requirement.
Provide your assessment in the following JSON format:
{{
"requirement_id": "{requirement_id}",
"rating": <integer 1-5>,
"rationale": "<string>",
"summary": "<string>",
"issues": "<string, describe specific issues found>",
"recommendations": "<string, suggest improvements>"
}}
* **Rating:** 1 (Poor) to 5 (Excellent). Base the rating strictly on the criteria and context.
* **Rationale:** Explain *why* you gave that rating, referencing specific information from the context.
* **Summary:** Briefly summarize the vendor's performance regarding this requirement.
* **Issues:** Detail any specific gaps, non-compliance, or concerns identified. If none, state "None".
* **Recommendations:** Suggest concrete actions the vendor should take to improve compliance or address identified issues. If none, state "None".
If the context does not provide enough information to make a judgment for a specific criterion, clearly state that in the rationale and provide the best possible rating based on available information, or indicate uncertainty. Do not invent information.
"""
prompt = ChatPromptTemplate.from_template(template)
rag_chain = (
{
"context": retriever,
"requirement_description": RunnablePassthrough.assign(requirement_description=lambda x: x['requirement_description']),
"criteria_text": RunnablePassthrough.assign(criteria_text=lambda x: x['criteria_text']),
"requirement_id": RunnablePassthrough.assign(requirement_id=lambda x: x['requirement_id']),
}
| prompt
| llm
| JsonOutputParser() # Expecting JSON output
)
return rag_chain
def parse_llm_output(output: Dict[str, Any]) -> Dict[str, Any]:
"""Parses and validates the LLM output."""
# Basic validation - add more robust checks as needed
validated_output = {
"requirement_id": output.get("requirement_id"),
"rating": max(1, min(5, int(output.get("rating", 0)))) if output.get("rating") else 1, # Clamp rating 1-5
"rationale": output.get("rationale", "N/A"),
"summary": output.get("summary", "N/A"),
"issues": output.get("issues", "N/A"),
"recommendations": output.get("recommendations", "N/A"),
}
# Ensure text fields are strings
for key in ["rationale", "summary", "issues", "recommendations"]:
if not isinstance(validated_output[key], str):
validated_output[key] = str(validated_output[key])
# Handle cases where LLM might fail to produce valid JSON or required fields
if not validated_output["requirement_id"]:
print("Warning: LLM output missing 'requirement_id'. Attempting fallback.")
# Try to extract from context if possible, otherwise skip or use placeholder
validated_output["requirement_id"] = "UNKNOWN" # Or handle differently
return validated_output
# --- LangGraph State ---
class AssessmentState:
"""State for the assessment graph."""
files_to_process: List[str] = []
loaded_documents: List[Document] = []
chunks: List[Document] = []
vectorstore: Optional[Chroma] = None
rubric_data: Optional[Dict[str, pd.DataFrame]] = None
mapping_data: Optional[Dict[str, pd.DataFrame]] = None
requirements: List[Dict[str, Any]] = [] # List of {'RequirementID': '...', 'Requirement': '...', 'Criteria': '...'}
current_requirement_index: int = 0
all_assessments: Dict[str, Dict[str, Any]] = {}
current_assessment_result: Optional[Dict[str, Any]] = None
# For message-based graph (optional, can use direct state passing)
# messages: List[AnyMessage] = []
# --- LangGraph Nodes ---
def node_load_files(state: AssessmentState) -> AssessmentState:
"""Scans the files directory and loads documents."""
print("\n--- Node: Loading Files ---")
state['files_to_process'] = glob.glob(os.path.join(FILES_DIR, "*.*"))
if not state['files_to_process']:
print(f"No files found in '{FILES_DIR}'.")
# Optionally raise an error or handle gracefully
return state
state['loaded_documents'] = load_unstructured_docs(FILES_DIR)
return state
def node_split_documents(state: AssessmentState) -> AssessmentState:
"""Splits the loaded documents into chunks."""
print("\n--- Node: Splitting Documents ---")
if not state['loaded_documents']:
print("No documents loaded, skipping splitting.")
return state
state['chunks'] = split_docs(state['loaded_documents'])
return state
def node_create_vectorstore(state: AssessmentState) -> AssessmentState:
"""Creates or loads the Chroma vector store."""
print("\n--- Node: Creating Vector Store ---")
if not state['chunks']:
print("No document chunks available, cannot create vector store.")
# Handle this case: maybe raise an error or return without vectorstore
state['vectorstore'] = None # Explicitly set to None
return state
state['vectorstore'] = setup_vectorstore(state['chunks'], embeddings_model, PERSIST_DIR)
return state
def node_load_rubric_and_mapping(state: AssessmentState) -> AssessmentState:
"""Loads rubric and file mapping data from Excel files."""
print("\n--- Node: Loading Rubric and Mapping ---")
try:
state['rubric_data'] = load_excel_data(RUBRIC_FILE)
state['mapping_data'] = load_excel_data(MAPPING_FILE)
if not state['rubric_data'] or not state['mapping_data']:
print("Error: Failed to load one or both Excel files.")
# Decide how to proceed: stop, or continue without data
return state # Stop processing if essential data is missing
# Process rubric data into a more usable format
rubric_df = state['rubric_data'].get('Sheet1', state['rubric_data'].get('rubric', None)) # Adjust sheet name if needed
if rubric_df is None:
raise ValueError("Could not find 'Sheet1' or 'rubric' sheet in rubric file.")
# Process mapping data
mapping_df = state['mapping_data'].get('Sheet1', state['mapping_data'].get('file_mapping', None)) # Adjust sheet name
if mapping_df is None:
raise ValueError("Could not find 'Sheet1' or 'file_mapping' sheet in mapping file.")
# Standardize column names (assuming common names)
rubric_df.columns = [col.strip() for col in rubric_df.columns]
mapping_df.columns = [col.strip() for col in mapping_df.columns]
# Validate required columns exist
if 'RequirementID' not in rubric_df.columns or 'Requirement' not in rubric_df.columns:
raise ValueError("Rubric file missing 'RequirementID' or 'Requirement' columns.")
if 'RequirementID' not in mapping_df.columns or 'FileName' not in mapping_df.columns:
raise ValueError("Mapping file missing 'RequirementID' or 'FileName' columns.")
# Create mapping dict: RequirementID -> List of FileNames
file_map_dict = {}
for _, row in mapping_df.iterrows():
req_id = row['RequirementID']
file_name = row['FileName']
if req_id not in file_map_dict:
file_map_dict[req_id] = []
file_map_dict[req_id].append(file_name)
# Build the list of requirements to process
requirements_list = []
for _, row in rubric_df.iterrows():
req_id = row['RequirementID']
# Combine criteria into a single string
criteria_parts = []
for i in range(1, 6):
col_name = f'Criteria{i}'
if col_name in row and pd.notna(row[col_name]):
criteria_parts.append(f" - Criterion {i}: {row[col_name]}")
criteria_text = "\n".join(criteria_parts)
if not criteria_text:
print(f"Warning: No criteria found for RequirementID '{req_id}'.")
criteria_text = "No specific criteria provided."
requirements_list.append({
"RequirementID": str(req_id), # Ensure string
"Requirement": row['Requirement'],
"Criteria": criteria_text,
"MappedFiles": file_map_dict.get(str(req_id), []) # Get files for this req
})
state['requirements'] = requirements_list
print(f"Loaded {len(state['requirements'])} requirements.")
except FileNotFoundError as e:
print(f"Error: {e}")
state['rubric_data'] = None
state['mapping_data'] = None
state['requirements'] = []
except ValueError as e:
print(f"Error processing Excel data: {e}")
state['rubric_data'] = None
state['mapping_data'] = None
state['requirements'] = []
except Exception as e:
print(f"An unexpected error occurred loading Excel files: {e}")
state['rubric_data'] = None
state['mapping_data'] = None
state['requirements'] = []
return state
def node_assess_requirement(state: AssessmentState) -> AssessmentState:
"""Assesses a single requirement using RAG."""
print("\n--- Node: Assessing Requirement ---")
if not state['vectorstore'] or not state['requirements']:
print("Skipping assessment: Vector store or requirements data is missing.")
# Move to completion check
state['current_requirement_index'] += 1 # Ensure loop termination
return state
if state['current_requirement_index'] >= len(state['requirements']):
print("All requirements have been processed.")
return state # Should be caught by check_completion, but good practice
# Get data for the current requirement
req_data = state['requirements'][state['current_requirement_index']]
req_id = req_data['RequirementID']
requirement_desc = req_data['Requirement']
criteria_text = req_data['Criteria']
mapped_files = req_data['MappedFiles']
print(f"Assessing Requirement {req_id}: {requirement_desc[:50]}...")
print(f"Mapped files: {mapped_files}")
# --- Retrieval ---
# Create a retriever instance
# We can filter metadata here if needed, but let's rely on the prompt for now
# Filter retriever to only consider documents from mapped files
retriever = state['vectorstore'].as_retriever(
search_kwargs={
"filter": {
"document": {"$in": [os.path.join(FILES_DIR, f) for f in mapped_files]} if mapped_files else {} # Filter by filename if files are mapped
}
}
)
# If no files are mapped, retrieve from the whole collection
# retriever = state['vectorstore'].as_retriever() # Use this if filtering is not desired or files are missing
# Construct the query for the LLM
# Combine requirement and criteria for a focused retrieval query
retrieval_query = f"Information relevant to requirement '{requirement_desc}' with criteria: {criteria_text}. Files: {', '.join(mapped_files) if mapped_files else 'All'}"
# Create the RAG chain specifically for this step
rag_chain = create_rag_chain(retriever, llm)
# --- Generation ---
try:
# Pass all necessary info to the chain
assessment_result = rag_chain.invoke({
"requirement_id": req_id,
"requirement_description": requirement_desc,
"criteria_text": criteria_text,
"retrieval_query": retrieval_query # LLM chain uses this internally via retriever kwargs
})
# Parse and validate the output
parsed_result = parse_llm_output(assessment_result)
parsed_result["requirement_id"] = req_id # Ensure ID is correct
parsed_result["requirement"] = requirement_desc # Add description for context
parsed_result["criteria"] = criteria_text # Add criteria for context
state['current_assessment_result'] = parsed_result
state['all_assessments'][req_id] = parsed_result
print(f"Assessment completed for {req_id}. Rating: {parsed_result['rating']}")
except Exception as e:
print(f"Error during assessment for {req_id}: {e}")
# Store error information or placeholder
state['current_assessment_result'] = {
"requirement_id": req_id,
"requirement": requirement_desc,
"criteria": criteria_text,
"rating": "Error",
"rationale": f"Failed to generate assessment: {str(e)}",
"summary": "Error", "issues": "Error", "recommendations": "Error"
}
state['all_assessments'][req_id] = state['current_assessment_result']
# Move to the next requirement
state['current_requirement_index'] += 1
return state
def node_check_completion(state: AssessmentState) -> str:
"""Checks if all requirements have been processed."""
print("\n--- Node: Checking Completion ---")
if state['current_requirement_index'] >= len(state['requirements']):
print("All requirements processed. Ending.")
return END
else:
print(f"More requirements to process. Current index: {state['current_requirement_index']}")
# Route back to assess the next requirement
return "assess_requirement"
# --- Graph Definition ---
class AssessmentGraph:
def __init__(self):
self.graph = self._build_graph()
def _build_graph(self):
"""Builds the LangGraph state machine."""
# Define the state structure
state_graph = StateGraph(AssessmentState)
# Add nodes
state_graph.add_node("load_files", node_load_files)
state_graph.add_node("split_documents", node_split_documents)
state_graph.add_node("create_vectorstore", node_create_vectorstore)
state_graph.add_node("load_rubric_mapping", node_load_rubric_and_mapping)
state_graph.add_node("assess_requirement", node_assess_requirement)
state_graph.add_node("check_completion", node_check_completion) # Node to decide next step
# Define edges/workflow
state_graph.set_entry_point("load_files")
# Sequence of initial steps
state_graph.add_edge("load_files", "split_documents")
state_graph.add_edge("split_documents", "create_vectorstore")
state_graph.add_edge("create_vectorstore", "load_rubric_mapping")
# Conditional edge from loading to assessment or end
# If rubric/mapping fails, requirements list will be empty, check_completion handles it.
state_graph.add_edge("load_rubric_mapping", "assess_requirement") # Start assessment process
# Loop back for subsequent requirements
# The 'assess_requirement' node increments the index.
# We use 'check_completion' to decide whether to loop or finish.
state_graph.add_conditional_edges(
"assess_requirement", # After assessing one req
node_check_completion, # Function that returns next node name or END
{
"assess_requirement": "assess_requirement", # Loop back if not done
END: END # Go to END if done
}
)
# Add automatic edge if requirements list is empty after loading
# Check completion immediately after loading if no requirements found
# This requires modifying check_completion logic slightly or adding another node
# Let's refine node_check_completion to handle initial empty state
# Let's adjust the flow slightly: load -> split -> vecstore -> load_excel -> check (initial)
# If check passes, go to assess. Then assess loops via check.
# Revised flow:
# load_files -> split_documents -> create_vectorstore -> load_rubric_mapping
# load_rubric_mapping -> check_completion (Initial check)
# check_completion --("assess_requirement")--> assess_requirement
# assess_requirement --(internal logic)--> check_completion
# check_completion --(END)--> END
# Re-linking based on revised flow:
# We need a way to go from load_rubric_mapping to check_completion
# And let check_completion decide if it should go to assess_requirement or END
# Let's refine the conditional logic:
# If requirements exist after loading, transition from load_rubric_mapping to assess_requirement
# If no requirements, transition from load_rubric_mapping directly to END
# Simplified approach: Let assess_requirement handle the index, and check_completion always routes based on index.
# Link load_rubric_mapping to assess_requirement
# state_graph.add_edge("load_rubric_mapping", "assess_requirement") # Already did this
# The graph as defined above should work:
# load -> split -> vecstore -> load_excel
# load_excel -> assess_requirement (starts processing, index 0)
# assess_requirement increments index, then calls check_completion
# check_completion checks index against len(requirements)
# If index < len, it returns "assess_requirement" (loop)
# If index >= len, it returns END
# Ensure the graph is compiled
return state_graph.compile()
def run_agent(self):
"""Runs the assessment agent."""
print("--- Starting Vendor Risk Assessment Agent ---")
# Initialize the state
initial_state = AssessmentState()
# Run the graph
final_state = self.graph.invoke(initial_state)
print("\n--- Agent Execution Finished ---")
# Display results
print("\n--- Final Assessment Summary ---")
if not final_state.get('all_assessments'):
print("No assessments were generated.")
return
# Sort assessments by RequirementID for consistent output
sorted_assessments = sorted(
final_state['all_assessments'].values(),
key=lambda x: x.get('requirement_id', 'ZZZ') # Sort safely
)
for assessment in sorted_assessments:
print("-" * 40)
print(f"Requirement ID: {assessment.get('requirement_id')}")
print(f"Requirement: {assessment.get('requirement', '')[:80]}...") # Truncate long requirements
print(f"Rating: {assessment.get('rating')}")
print(f"Rationale: {assessment.get('rationale', '')}")
print(f"Summary: {assessment.get('summary', '')}")
print(f"Issues: {assessment.get('issues', '')}")
print(f"Recommendations: {assessment.get('recommendations', '')}")
print("-" * 40)
print(f"\nTotal requirements assessed: {len(sorted_assessments)}")
# --- Main Execution ---
if __name__ == "__main__":
# --- Optional: Cleanup Old Data ---
# Uncomment to clear previous runs' data
# print("Cleaning up previous run data...")
# if os.path.exists(PERSIST_DIR):
# shutil.rmtree(PERSIST_DIR)
# print(f"Removed directory: {PERSIST_DIR}")
# # Consider clearing ./files/ if needed, but usually populated manually.
# --- Run the Agent ---
agent = AssessmentGraph()
agent.run_agent()