Building an AI for hard conversations: five agents, one safety regex, and a supervisor who graded us blind
Executive Summary
The challenge of engineering an AI system capable of navigating "hard conversations"—defined here as high-stakes, emotionally charged, or ethically ambiguous interactions—requires moving beyond simple prompt engineering into robust multi-agent orchestration. This analysis dissects a specific architectural pattern: a five-agent ensemble supervised by a blind-grading mechanism, constrained by a single, rigorous safety regex. The core thesis is that safety in complex dialogue is not a feature added at the end, but a structural constraint applied at the token generation level. By decoupling the generative agents (who propose responses) from the safety validator (who enforces the regex) and the supervisor (who evaluates semantic alignment without seeing the raw text), we achieve a system that is both compliant and contextually aware. This approach mitigates the risk of jailbreaks and hallucinations by forcing every output through a deterministic filter before human or automated review, ensuring that the "blind" grading process focuses purely on intent and tone rather than specific keyword evasion techniques.
Implementation & Architecture
The system architecture is built on a synchronous pipeline where five distinct agents operate in parallel or sequence, each specializing in a different rhetorical or logical stance. These agents are not independent LLMs running in isolation but are components of a unified orchestration layer. The flow begins with the user input, which is broadcast to all five agents. Each agent generates a candidate response based on its specific persona or logical framework (e.g., Empathetic Listener, Logical Analyst, Ethical Guard, Creative Problem-Solver, and Neutral Mediator).
The critical component is the "Safety Regex" layer. This is not a simple keyword blocklist but a compiled regular expression engine that scans the concatenated or individual outputs of the five agents. The regex is designed to detect patterns of harm, bias, or policy violation that might be subtle enough to bypass standard LLM safety filters. If any agent's output fails the regex check, that specific branch is pruned immediately. The remaining valid outputs are then passed to the Supervisor.
The Supervisor does not see the raw text of the agents' responses during the initial grading phase. Instead, it receives a structured representation of the responses—such as sentiment scores, logical coherence metrics, and safety confidence intervals—generated by lightweight embedding models. This "blind" grading ensures that the Supervisor evaluates the quality and alignment of the responses without being influenced by the specific wording that might have triggered the safety regex. The final output is selected based on the highest score from the blind grading, ensuring that the chosen response is both safe and effective.
import re
import json
from typing import List, Dict, Any
from dataclasses import dataclass
from enum import Enum
# Define the five agent roles
class AgentRole(Enum):
EMPATHETIC = "empathetic_listener"
LOGICAL = "logical_analyst"
ETHICAL = "ethical_guard"
CREATIVE = "creative_problem_solver"
NEUTRAL = "neutral_mediator"
@dataclass
class AgentResponse:
role: AgentRole
text: str
confidence: float
safety_score: float
class SafetyRegexValidator:
def __init__(self, pattern: str):
self.pattern = re.compile(pattern, re.IGNORECASE | re.MULTILINE)
def validate(self, text: str) -> bool:
"""Returns True if the text is safe (no matches found), False otherwise."""
return not bool(self.pattern.search(text))
class BlindSupervisor:
def __init__(self):
# In a real system, this would be a small, fast model or heuristic engine
self.weights = {
"coherence": 0.4,
"tone": 0.3,
"helpfulness": 0.3
}
def grade(self, responses: List[AgentResponse]) -> AgentResponse:
"""
Grades responses based on metadata only, not raw text.
This simulates the 'blind' grading process.
"""
best_response = None
highest_score = -1
for resp in responses:
# Simulate scoring based on metadata
# In production, these scores would come from an embedding model
coherence_score = resp.confidence * 0.8
tone_score = resp.safety_score * 0.9
helpfulness_score = 0.7 # Placeholder for actual helpfulness metric
total_score = (
self.weights["coherence"] * coherence_score +
self.weights["tone"] * tone_score +
self.weights["helpfulness"] * helpfulness_score
)
if total_score > highest_score:
highest_score = total_score
best_response = resp
return best_response
class HardConversationAI:
def __init__(self, safety_pattern: str):
self.validator = SafetyRegexValidator(safety_pattern)
self.supervisor = BlindSupervisor()
self.agents = {role: self._mock_agent_factory(role) for role in AgentRole}
def _mock_agent_factory(self, role: AgentRole):
"""
Mocks the LLM generation for demonstration.
In production, this would call an actual LLM API.
"""
def generate(input_text: str) -> str:
# Simulate different responses based on role
if role == AgentRole.EMPATHETIC:
return f"I understand this is difficult. Let's explore your feelings about '{input_text}'."
elif role == AgentRole.LOGICAL:
return f"Analyzing '{input_text}': The core issue seems to be a conflict in priorities."
elif role == AgentRole.ETHICAL:
return f"Considering the moral implications of '{input_text}', we must ensure fairness."
elif role == AgentRole.CREATIVE:
return f"Here's a unique perspective on '{input_text}': What if we reframed the problem?"
else:
return f"Neutral observation on '{input_text}': Both sides have valid points."
return generate
def process(self, user_input: str) -> Dict[str, Any]:
# Step 1: Generate responses from all five agents
raw_responses = []
for role, agent_fn in self.agents.items():
response_text = agent_fn(user_input)
raw_responses.append(AgentResponse(
role=role,
text=response_text,
confidence=0.9, # Mock confidence
safety_score=0.95 # Mock safety score
))
# Step 2: Apply Safety Regex Filter
safe_responses = []
for resp in raw_responses:
if self.validator.validate(resp.text):
safe_responses.append(resp)
else:
print(f"Agent {resp.role.value} failed safety check.")
if not safe_responses:
return {"error": "No safe responses generated. All agents failed safety regex."}
# Step 3: Blind Grading by Supervisor
best_response = self.supervisor.grade(safe_responses)
return {
"selected_role": best_response.role.value,
"response_text": best_response.text,
"score": best_response.confidence
}
# Example Usage
if __name__ == "__main__":
# A simple safety regex to block harmful keywords
safety_pattern = r"(?i)\b(hate|kill|destroy|abuse)\b"
ai_system = HardConversationAI(safety_pattern)
user_input = "I am feeling very angry and want to destroy my computer."
result = ai_system.process(user_input)
print(json.dumps(result, indent=2))
ShVaSa Intuition & Hardware Sizing
The architectural choice of a five-agent system with a blind supervisor introduces significant computational overhead, but it is justified by the need for robustness in high-stakes environments. The primary bottleneck is not the LLM inference itself, but the parallel processing and the safety validation layer.
Hardware Sizing & Trade-offs:
- VRAM Footprint: Running five agents simultaneously requires substantial VRAM. If each agent is a quantized 7B parameter model (e.g., Llama-3-8B-Instruct-Q4_K_M), the VRAM requirement per agent is approximately 4-5 GB. For five agents, this totals 20-25 GB. A single 24 GB GPU (like an RTX 3090/4090) is insufficient for full parallelism. A multi-GPU setup with at least two 24 GB GPUs or a single 48 GB/80 GB GPU (like an A100 or H100) is recommended. If using a 40 GB GPU (A40), you can run two agents fully and batch the others, but latency will increase.
- Memory Bandwidth Limits: The safety regex validation is CPU-bound but requires low-latency access to the generated text. The memory bandwidth between the GPU and CPU becomes a critical path. If the GPU is generating tokens at 50 tokens/sec, the CPU must process the regex check in under 20ms to avoid stalling the pipeline. A modern CPU with high single-core performance (e.g., AMD Ryzen 9 or Intel Core i9) is essential for the regex engine.
- CPU vs GPU Latency: The blind supervisor, if implemented as a small embedding model (e.g., 100M parameters), can run on the CPU or a small GPU. However, for real-time interaction, it should be on the same GPU as the agents to avoid PCIe transfer latency. If the supervisor is a rule-based heuristic engine, it can run on the CPU with negligible latency.
- Trade-off Analysis: Parallelism vs. Latency: Running five agents in parallel reduces the time to first token (TTFT) for the best response but increases total compute cost. A sequential approach (one agent at a time) would reduce VRAM usage but increase latency by a factor of five. Regex Complexity vs. Accuracy: A more complex regex (e.g., using lookaheads and backreferences) increases CPU load but improves safety. A simple keyword list is faster but less effective. The optimal regex is a balance, typically under 100 characters, ensuring sub-millisecond evaluation.
- Embedded Edge Device Consideration: For deployment on an embedded ARM edge device (e.g., NVIDIA Jetson Orin), the five-agent model is infeasible. Instead, a single distilled model (e.g., 1.5B parameters) with a simplified safety filter is required. The blind supervisor would be replaced by a lightweight heuristic engine. This reduces VRAM to <2 GB but sacrifices the nuance of multi-perspective responses.
Grounding & Source Attribution
This analysis is grounded in the technical editorial curation and ShVaSa intuition on the topic "Building an AI for hard conversations: five agents, one safety regex, and a supervisor who graded us blind." The architectural patterns described, including the multi-agent ensemble and the blind grading mechanism, are derived from the source attribution: Dev.to by Adilet Akmatov. The hardware sizing and trade-off analysis are based on standard industry benchmarks for LLM inference and real-time safety filtering, ensuring that the recommendations are practical for deployment in production environments. The code block provided is a runnable Python implementation that demonstrates the core logic of the safety regex validation and blind supervisor grading, serving as a foundational template for further development.
flowchart TD
subgraph Ingestion["1. Workload Profiling & Input Tensors"]
A["Input Stream: Building an AI for"] --> B["Memory Allocator & Batch Sizer"]
B --> C["Pinned Host Buffers"]
end
subgraph Execution["2. Hardware Execution & Memory Bus"]
C --> D{"Bus Saturation Monitor"}
D -->|Within Bandwidth| E["High-Throughput Kernel Execution"]
D -->|Bus Contention| F["Adaptive Quantization / KV-Eviction"]
end
subgraph Telemetry["3. Verification & Telemetry"]
E & F --> G["Verified Invariant Telemetry"]
end