Use LangGraph and Chromadb to create an AI agent that is optimized to used RAG and answer questions. Ingest files from folder called "files/" and use the appropriate semantic chunking and indexing required. Possible files include .pdf, .docx, .pptx, .xlsx, .md, and .txt. The AI agent will be making risk assessments on third party vendors. For each control risk requirements, the agent will rate between 1-5, give rationale, summary, issues, and recommendations on improvements. These risk requirements is in an excel file called "rubric.xlsx" which contain the requirement and criteria for 1 through 5. There is also a file called "file_requirement_mapping.xlsx" that maps each requirement to files associated to said requirement.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'll create a comprehensive solution using LangGraph and ChromaDB to build a RAG-optimized AI agent for vendor risk assessment. This system will ingest various file types, process them with semantic chunking, and provide detailed risk assessments based on your rubric.
Solution Architecture
python
import os
import pandas as pd
from langchain_community.document_loaders import (
PyPDFLoader, Docx2txtLoader, UnstructuredPowerPointLoader,
UnstructuredExcelLoader, TextLoader, UnstructuredMarkdownLoader
)
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.vectorstores import Chroma
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
from langgraph.graph import END, MessageGraph
from typing import Dict, TypedDict, List
from langchain_core.messages import HumanMessage, AIMessage
from langchain_community.embeddings import HuggingFaceEmbeddings
# Configuration
EMBEDDING_MODEL = "sentence-transformers/all-mpnet-base-v2"
CHROMA_DB_PATH = "chroma_db"
FILES_DIR = "files"
RUBRIC_FILE = "rubric.xlsx"
MAPPING_FILE = "file_requirement_mapping.xlsx"
# Initialize embedding model
embeddings = HuggingFaceEmbeddings(model_name=EMBEDDING_MODEL)
# Document Loader Factory
def get_loader(file_path: str):
ext = os.path.splitext(file_path)[1].lower()
if ext == '.pdf':
return PyPDFLoader(file_path)
elif ext == '.docx':
return Docx2txtLoader(file_path)
elif ext == '.pptx':
return UnstructuredPowerPointLoader(file_path)
elif ext in ('.xlsx', '.xls'):
return UnstructuredExcelLoader(file_path)
elif ext == '.txt':
return TextLoader(file_path)
elif ext == '.md':
return UnstructuredMarkdownLoader(file_path)
else:
raise ValueError(f"Unsupported file type: {ext}")
# Document Processing
def process_documents():
# Load mapping file
mapping_df = pd.read_excel(MAPPING_FILE)
# Initialize text splitter
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200,
length_function=len,
is_separator_regex=False,
)
documents = []
metadatas = []
# Process each file
for file_name in os.listdir(FILES_DIR):
file_path = os.path.join(FILES_DIR, file_name)
if os.path.isfile(file_path):
try:
loader = get_loader(file_path)
docs = loader.load()
# Get requirements associated with this file
file_reqs = mapping_df[mapping_df['file_name'] == file_name]['requirement_id'].tolist()
for doc in docs:
chunks = text_splitter.split_text(doc.page_content)
for chunk in chunks:
documents.append(chunk)
metadatas.append({
"source": file_name,
"requirement_ids": file_reqs
})
except Exception as e:
print(f"Error processing {file_name}: {str(e)}")
# Create vector store
vector_store = Chroma.from_texts(
texts=documents,
embedding=embeddings,
metadatas=metadatas,
persist_directory=CHROMA_DB_PATH
)
vector_store.persist()
return vector_store
# Load or create vector store
if os.path.exists(CHROMA_DB_PATH):
vector_store = Chroma(persist_directory=CHROMA_DB_PATH, embedding_function=embeddings)
else:
vector_store = process_documents()
# Load rubric data
rubric_df = pd.read_excel(RUBRIC_FILE)
rubric_data = {}
for _, row in rubric_df.iterrows():
requirement_id = row['requirement_id']
if requirement_id not in rubric_data:
rubric_data[requirement_id] = {}
rubric_data[requirement_id][row['rating']] = {
'criteria': row['criteria'],
'description': row['description']
}
# Define agent state
class AgentState(TypedDict):
requirement_id: str
vendor_info: str
retrieved_docs: List[str]
assessment: Dict[str, str]
messages: List[dict]
# Define nodes for LangGraph
def retrieve_documents(state: AgentState):
requirement_id = state['requirement_id']
vendor_info = state['vendor_info']
# Retrieve relevant documents for this requirement
docs = vector_store.similarity_search(
query=f"Requirement {requirement_id} for vendor: {vendor_info}",
filter={"requirement_ids": requirement_id},
k=5
)
return {
**state,
"retrieved_docs": [doc.page_content for doc in docs]
}
def assess_requirement(state: AgentState):
requirement_id = state['requirement_id']
retrieved_docs = "\n\n".join(state['retrieved_docs'])
vendor_info = state['vendor_info']
# Get rubric criteria for this requirement
criteria = rubric_data.get(requirement_id, {})
# Create assessment prompt
prompt = ChatPromptTemplate.from_template("""
You are a Third-Party Vendor Risk Assessment Specialist. Your task is to evaluate a vendor against specific control requirements.
Vendor Information:
{vendor_info}
Requirement ID: {requirement_id}
Rubric Criteria:
{criteria}
Relevant Documentation:
{retrieved_docs}
Based on the above information, please provide:
1. A rating between 1-5 (with 5 being the best)
2. A detailed rationale for the rating
3. A summary of findings
4. Any identified issues
5. Recommendations for improvement
Return your assessment in the following format:
Rating: [1-5]
Rationale: [your rationale]
Summary: [summary of findings]
Issues: [list of issues]
Recommendations: [recommendations for improvement]
""")
chain = (
{"criteria": RunnablePassthrough(), **RunnablePassthrough()}
| prompt
| StrOutputParser()
)
assessment_text = chain.invoke({
"requirement_id": requirement_id,
"vendor_info": vendor_info,
"retrieved_docs": retrieved_docs,
"criteria": "\n".join(
f"Rating {rating}: {data['criteria']}\nDescription: {data['description']}"
for rating, data in criteria.items()
)
})
# Parse the assessment
assessment = {}
current_section = None
for line in assessment_text.split('\n'):
if line.startswith('Rating:'):
current_section = 'rating'
assessment['rating'] = line.replace('Rating:', '').strip()
elif line.startswith('Rationale:'):
current_section = 'rationale'
assessment['rationale'] = line.replace('Rationale:', '').strip()
elif line.startswith('Summary:'):
current_section = 'summary'
assessment['summary'] = line.replace('Summary:', '').strip()
elif line.startswith('Issues:'):
current_section = 'issues'
assessment['issues'] = line.replace('Issues:', '').strip()
elif line.startswith('Recommendations:'):
current_section = 'recommendations'
assessment['recommendations'] = line.replace('Recommendations:', '').strip()
elif current_section and line.strip():
assessment[current_section] += "\n" + line.strip()
return {
**state,
"assessment": assessment
}
def generate_response(state: AgentState):
assessment = state['assessment']
response = f"""
**Requirement {state['requirement_id']} Assessment**
**Rating:** {assessment.get('rating', 'N/A')}
**Rationale:**
{assessment.get('rationale', 'Not provided')}
**Summary:**
{assessment.get('summary', 'Not provided')}
**Issues Identified:**
{assessment.get('issues', 'None identified')}
**Recommendations:**
{assessment.get('recommendations', 'No specific recommendations')}
"""
return {
**state,
"messages": state["messages"] + [AIMessage(content=response)]
}
# Build the workflow
workflow = MessageGraph()
workflow.add_node("retrieve", retrieve_documents)
workflow.add_node("assess", assess_requirement)
workflow.add_node("respond", generate_response)
workflow.add_edge("retrieve", "assess")
workflow.add_edge("assess", "respond")
workflow.add_edge("respond", END)
workflow.set_entry_point("retrieve")
agent = workflow.compile()
# Main function to run assessments
def assess_vendor(vendor_info: str, requirement_ids: List[str]):
results = {}
for req_id in requirement_ids:
state = {
"requirement_id