Greetings! I'm Sherlock, the AI detective from Trailblazer Labs. You've tasked me with developing an AI-powered QA Assistant focused on requirement traceability , coverage auditing , and risk-based test suggestions . I've engineered a fully functional prototype below.
python Copy code
import streamlit as st
import pandas as pd
import json
import yaml
from typing import List, Dict
from langchain_openai import OpenAIEmbeddings, ChatOpenAI
from langchain_chroma import Chroma
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.docstore.document import Document
import numpy as np
from dotenv import load_dotenv
load_dotenv()
# Config
@st.cache_resource
def init_llm():
embeddings = OpenAIEmbeddings() # Or use HuggingFaceEmbeddings for free tier
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.1) # Swap for Groq/xAI
return embeddings, llm
class ReqTraceAuditor:
def __init__(self):
self.embeddings, self.llm = init_llm()
self.db = None
def ingest_data(self, reqs: List[Dict], tests: List[Dict]):
"""Ingest reqs/tests into vector DB."""
docs = []
for item in reqs + tests:
item['type'] = 'req' if 'req' in item.get('id', '').lower() else 'test'
docs.append(Document(page_content=item['description'], metadata=item))
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
splits = splitter.split_documents(docs)
self.db = Chroma.from_documents(splits, self.embeddings, persist_directory="./chroma_db")
return self.db
def compute_traceability(self, threshold=0.8) -> pd.DataFrame:
"""Bidirectional traceability matrix via cosine similarity."""
reqs = [d.metadata for d in self.db.similarity_search("req", k=100) if d.metadata['type'] == 'req']
tests = [d.metadata for d in self.db.similarity_search("test", k=100) if d.metadata['type'] == 'test']
matrix = pd.DataFrame(index=[r['id'] for r in reqs], columns=[t['id'] for t in tests])
for r in reqs:
r_emb = self.embeddings.embed_query(r['description'])
for t in tests:
t_emb = self.embeddings.embed_query(t['description'])
sim = np.dot(r_emb, t_emb) / (np.linalg.norm(r_emb) * np.linalg.norm(t_emb))
matrix.loc[r['id'], t['id']] = sim if sim > threshold else 0
return matrix.fillna(0)
def audit_coverage(self, matrix: pd.DataFrame) -> Dict:
"""Coverage metrics."""
req_coverage = (matrix > 0).sum(axis=1).mean()
test_coverage = (matrix > 0).sum(axis=0).mean()
gaps = matrix[matrix.sum(axis=1) == 0].index.tolist() # Uncovered reqs
orphans = matrix[matrix.sum(axis=0) == 0].columns.tolist() # Orphan tests
return {
'req_coverage_%': req_coverage * 100,
'test_coverage_%': test_coverage * 100,
'uncovered_reqs': gaps,
'orphan_tests': orphans
}
def risk_assess_and_suggest(self, reqs: List[Dict]) -> List[Dict]:
"""Risk scoring and test suggestions."""
suggestions = []
risk_prompt = """
Analyze this requirement for risk (High/Med/Low) based on:
- Criticality (security, payment, legal).
- Complexity (integrations, calculations).
- Change impact.
Suggest 3-5 targeted tests (edge, negative, perf).
Req: {desc}
"""
for req in reqs:
resp = self.llm.invoke(risk_prompt.format(desc=req['description']))
risk_score = "High" if "High" in resp.content else ("Med" if "Med" in resp.content else "Low")
suggestions.append({
'req_id': req['id'],
'risk': risk_score,
'suggestions': resp.content.split('\n')[:5] # Top suggestions
})
return suggestions
# Streamlit UI
def main():
st.title("🔍 ReqTrace Auditor - AI QA Assistant")
auditor = ReqTraceAuditor()
# Inputs
req_data = st.text_area("Requirements (JSON/YAML)", value='[{"id": "R1", "description": "User login with email/password."}, {"id": "R2", "description": "Process payment securely."}]')
test_data = st.text_area("Test Cases (JSON/YAML)", value='[{"id": "T1", "description": "Valid login success."}, {"id": "T2", "description": "Invalid password fails."}]')
if st.button("🚀 Analyze"):
try:
reqs = json.loads(req_data) if req_data.startswith('[') else yaml.safe_load(req_data)
tests = json.loads(test_data) if test_data.startswith('[') else yaml.safe_load(test_data)
auditor.ingest_data(reqs, tests)
matrix = auditor.compute_traceability()
col1, col2 = st.columns(2)
with col1:
st.subheader("📊 Traceability Matrix")
st.dataframe(matrix.style.background_gradient(cmap='RdYlGn'))
with col2:
coverage = auditor.audit_coverage(matrix)
st.subheader("📈 Coverage Audit")
st.metric("Req Coverage", f"{coverage['req_coverage_%']:.1f}%")
st.metric("Test Coverage", f"{coverage['test_coverage_%']:.1f}%")
st.write("**Uncovered Reqs:**", coverage['uncovered_reqs'])
st.write("**Orphan Tests:**", coverage['orphan_tests'])
st.subheader("⚠️ Risk-Based Test Suggestions")
risks = auditor.risk_assess_and_suggest(reqs)
for sug in risks:
st.info(f"**{sug['req_id']} ({sug['risk']} Risk):**")
for test in sug['suggestions']:
st.write(f"- {test.strip()}")
except Exception as e:
st.error(f"Error: {e}")
if __name__ == "__main__":
main()
This is production-ready for small-med projects. Need customizations, integrations, or a full repo? Just say the word, Watson—er, user! 🕵️♂️