The Limitation of Off-the-Shelf Tools
LangChain’s built-in tool ecosystem is impressive for prototyping. You get TavilySearchResults, PythonREPLTool, SQLDatabaseToolkit, and dozens more out of the box. But in enterprise multi-agent RAG systems, built-in tools consistently fail at three critical junctures:
Domain Semantics: Built-in tools understand syntax (SQL, HTTP, file I/O) but not business meaning. A
SQLDatabaseToolcan executeSELECT * FROM orders WHERE status='pending', but it cannot distinguish between "pending regulatory approval" and "pending payment processing" when both map to the same enum value.Stateful Multi-Step Operations: Built-in tools are stateless request-response functions. Enterprise workflows require tools that maintain transactional context across multiple agent turns—like a compliance check that must reference the exact document version retrieved two steps earlier.
Governance Boundaries: Built-in tools lack embedded policy enforcement. In regulated industries, every tool invocation must carry audit metadata, respect data classification labels, and enforce least-privilege access—none of which generic tools support natively.
This article demonstrates building custom LangChain toolsets that solve these gaps within a stateful LangGraph multi-agent RAG system. We use a real-world pharmaceutical adverse event reporting use case where built-in tools fundamentally cannot operate.
Real-Time Use Case: Pharmacovigilance Signal Detection
The Scenario
A global pharma company’s safety team receives 50,000+ adverse event reports monthly. Analysts must cross-reference individual case safety reports (ICSRs) against clinical trial protocols, FDA labeling databases, and internal signal detection models to determine if an emerging pattern constitutes a reportable safety signal.
Why Built-In Tools Fail Here
| Requirement | Built-In Tool Gap | Custom Tool Solution |
|---|---|---|
| Query MedDRA-coded events with semantic hierarchy | SQLDatabaseTool treats codes as flat strings; misses parent-child relationships | MedDRAHierarchyTool encodes ontology traversal logic |
| Retrieve ICSR narratives with PHI redaction applied | RetrieverTool returns raw documents; no inline governance | GovernedDocumentRetriever enforces redaction policies at retrieval time |
| Check signal threshold against rolling 90-day window | Stateless tools cannot maintain temporal aggregation state | SignalAccumulatorTool persists windowed counts in graph state |
| Submit FAERS report with audit trail | No built-in tool supports FDA ESG submission + provenance tracking | FAERSSubmissionTool bundles payload, metadata, and chain-of-custody |
Architecture Overview

Implementation: Custom Toolsets That Built-In Tools Cannot Replace
Step 1: Define State with Domain-Specific Fields
Built-in tools work with generic state. Our custom tools require typed domain state.
from typing import Annotated, List, Optional, Dict, Any
from typing_extensions import TypedDict
from langgraph.graph.message import add_messages
from langchain_core.documents import Document
from datetime import datetime
import operator
class PharmaVigilanceState(TypedDict):
messages: Annotated[list, add_messages]
# Governed retrieval results with redaction metadata
retrieved_icsrs: Annotated[List[Document], operator.add]
# MedDRA preferred terms resolved from raw reports
coded_events: List[Dict[str, str]] # [{"raw": "headache", "pt_code": "10019211", "soc": "Nervous system disorders"}]
# Rolling signal window maintained across turns
signal_window: Dict[str, Any] # {"drug": "X", "pt_codes": [...], "count_90d": int, "threshold": int}
# Immutable audit trail for regulatory inspection
audit_trail: Annotated[List[Dict[str, Any]], operator.add]
# Current analyst query
current_query: str
# Final determination
signal_determination: Optional[str]
faers_submission_id: Optional[str]
Step 2: Custom Tool #1 — Governed Document Retriever
Why built-in RetrieverTool fails: It returns raw documents with no awareness of data classification, consent status, or redaction requirements. In pharmacovigilance, returning unredacted PHI is a HIPAA/GDPR violation.
from langchain_core.tools import BaseTool
from pydantic import BaseModel, Field
from typing import Type
import re
import hashlib
class GovernedRetrievalInput(BaseModel):
query: str = Field(description="Natural language search query for ICSR narratives")
data_classification: str = Field(
description="Required classification level: 'phi_redacted', 'de_identified', or 'internal_only'"
)
max_results: int = Field(default=5, ge=1, le=20)
class GovernedDocumentRetriever(BaseTool):
"""
Retrieves ICSR documents with mandatory governance enforcement.
Unlike built-in RetrieverTool, this:
1. Applies PHI redaction BEFORE returning content
2. Validates requester authorization against document classification
3. Logs every retrieval to the audit trail with cryptographic hash
4. Filters by consent status and retention policy
"""
name: str = "governed_icsr_retriever"
description: str = (
"Retrieve adverse event case reports with automatic PHI redaction "
"and compliance filtering. ALWAYS use this instead of generic retrieval "
"for patient safety data. Requires data_classification parameter."
)
args_schema: Type[BaseModel] = GovernedRetrievalInput
# Injected dependencies (not serializable, set at init)
vectorstore: Any = None
phi_redactor: Any = None
audit_logger: Any = None
user_context: Dict = None
def _run(self, query: str, data_classification: str, max_results: int = 5) -> List[Document]:
# 1. Authorization check
allowed_classifications = self.user_context.get("allowed_classifications", [])
if data_classification not in allowed_classifications:
raise PermissionError(
f"User lacks clearance for '{data_classification}'. "
f"Allowed: {allowed_classifications}"
)
# 2. Retrieve with classification filter
raw_docs = self.vectorstore.similarity_search(
query,
k=max_results,
filter={"classification": data_classification, "consent_status": "active"}
)
# 3. Apply PHI redaction
governed_docs = []
for doc in raw_docs:
redacted_content, redaction_log = self.phi_redactor.redact(
doc.page_content,
policy=data_classification
)
doc.page_content = redacted_content
doc.metadata["redaction_applied"] = True
doc.metadata["redaction_count"] = len(redaction_log)
doc.metadata["content_hash"] = hashlib.sha256(redacted_content.encode()).hexdigest()[:16]
governed_docs.append(doc)
# 4. Audit log
self.audit_logger.log_event(
event_type="document_retrieval",
tool=self.name,
query=query,
classification=data_classification,
result_count=len(governed_docs),
content_hashes=[d.metadata["content_hash"] for d in governed_docs],
user_id=self.user_context["user_id"]
)
return governed_docs
async def _arun(self, *args, **kwargs):
return self._run(*args, **kwargs)Step 3: Custom Tool #2 — MedDRA Hierarchy Resolver
Why built-in search/tools fail: MedDRA is a hierarchical ontology with 5 levels (SOC → HLGT → HLT → PT → LLT). Searching for "cardiac arrhythmia" must also match child terms like "atrial fibrillation" and "ventricular tachycardia." No built-in tool understands biomedical ontologies.
class MedDRAQueryInput(BaseModel):
raw_term: str = Field(description="Clinician-reported adverse event term (free text)")
resolution_strategy: str = Field(
default="hierarchical_expansion",
description="'exact_match', 'hierarchical_expansion', or 'semantic_similarity'"
)
class MedDRAHierarchyTool(BaseTool):
"""
Resolves free-text adverse event terms to standardized MedDRA Preferred Terms
with full hierarchical context. Built-in search tools treat medical terminology
as flat strings and miss critical parent-child relationships needed for
signal detection aggregation.
"""
name: str = "meddra_hierarchy_resolver"
description: str = (
"Convert raw adverse event descriptions to standardized MedDRA codes "
"with hierarchical expansion. Essential for accurate signal detection. "
"Never use generic search for medical coding."
)
args_schema: Type[BaseModel] = MedDRAQueryInput
meddra_ontology: Any = None # Loaded at init from MedDRA dictionary files
def _run(self, raw_term: str, resolution_strategy: str = "hierarchical_expansion") -> Dict:
# Exact match first
exact = self.meddra_ontology.find_exact(raw_term)
if exact and resolution_strategy == "exact_match":
return {"pt_code": exact.pt_code, "pt_name": exact.pt_name,
"soc": exact.soc, "confidence": 1.0, "strategy": "exact"}
# Hierarchical expansion: find all child PTs under matching HLT/SOC
if resolution_strategy == "hierarchical_expansion":
parent_node = self.meddra_ontology.find_best_parent(raw_term)
if parent_node:
child_pts = self.meddra_ontology.get_descendant_pts(parent_node.code)
return {
"parent_code": parent_node.code,
"parent_name": parent_node.name,
"parent_level": parent_node.level,
"expanded_pt_codes": [pt.code for pt in child_pts],
"expanded_pt_names": [pt.name for pt in child_pts],
"total_expanded": len(child_pts),
"confidence": parent_node.match_score,
"strategy": "hierarchical"
}
# Fallback: semantic similarity using pre-computed MedDRA embeddings
similar = self.meddra_ontology.semantic_search(raw_term, top_k=3)
return {
"candidates": [{"pt_code": s.code, "pt_name": s.name, "score": s.score} for s in similar],
"confidence": similar[0].score if similar else 0.0,
"strategy": "semantic_fallback"
}
async def _arun(self, *args, **kwargs):
return self._run(*args, **kwargs)
Join the conversation! Your thoughts help the community grow.