Guardrails
Purpose and Scope
Guardrails are validation, filtering, and intervention points that keep an agent from accepting unsafe input, making unsafe tool calls, or returning output that violates product policy. In LangChain documentation, guardrails are described as checks that can run before an agent starts, after it completes, or around model and tool calls. That placement matters because different risks appear at different phases: prompt injection is usually input-adjacent, tool misuse happens during action selection, and quality or compliance failures often appear in final responses.
A useful guardrail design starts by separating deterministic checks from model-based checks. Deterministic guardrails use explicit logic such as regular expressions, keyword lists, schema validation, or allowlists. They are fast, repeatable, and inexpensive, which makes them well suited for PII patterns, blocked domains, or required fields. Model-based guardrails use another model or classifier to evaluate semantic risk. They are slower and more expensive, but they can catch subtle violations that simple string matching misses.
Core Guardrail Patterns
Input guardrails protect the agent before the first model call. They can remove sensitive fields, reject requests that include disallowed instructions, or normalize documents before retrieval. The official guardrails guidance calls out PII leakage, prompt injection, harmful content, business-rule enforcement, and output validation as common use cases. In practice, teams usually combine a cheap first pass with selective model-based review: for example, run deterministic PII detection on every request, then call a classifier only when the request enters a higher-risk workflow.
Tool-call guardrails sit between the model’s proposed action and the external system being called. The frontend tool-calling documentation describes each tool call as containing a tool name, structured arguments, and an identifier linking the call to its result, with results returned as tool messages. That shape creates a natural inspection boundary: before execution, validate the tool name against an allowlist, validate arguments against the tool schema, redact secrets, and require approval for destructive or costly actions. After execution, filter raw tool output before adding it back to the conversation.
Output guardrails run after the model or agent has produced an answer. They can validate structured output, enforce response format, remove leaked data, or route the run into a human review flow. Built-in PII middleware in the official docs supports handling strategies such as redaction, masking, hashing, or blocking, and those same strategies are good mental models for custom output policy. Redaction preserves the workflow while removing sensitive values, masking preserves partial readability, hashing supports deterministic matching, and blocking prevents the response from being delivered at all.
System-to-Code Mapping
The requested repository source path is not itself a guardrail middleware implementation; it is a compatibility module for JavaScript language parsing in langchain_classic. It exposes JavaScriptSegmenter through a deprecated lookup that forwards imports to langchain_community.document_loaders.parsers.language.javascript, using create_importer to centralize deprecation handling and optional import behavior. That kind of parser is relevant to deterministic guardrail pipelines because code-aware segmentation can be used before indexing, retrieval, or policy scanning of JavaScript source documents.
Sources: libs/langchain/langchain_classic/document_loaders/parsers/language/javascript.py
The important implementation detail is the dynamic attribute boundary. The module defines DEPRECATED_LOOKUP, constructs _import_attribute, implements __getattr__, and lists JavaScriptSegmenter in __all__. For guardrail authors, this means legacy import paths can still resolve the segmenter while the actual implementation lives in the community package. A code-ingestion guardrail should therefore treat this module as an import-facing shim, not as the place to customize segmentation or policy logic. Put custom validation in the pipeline that consumes segmented documents, not in this compatibility layer.
Execution Flow
A typical guardrailed agent flow begins with request normalization. First, validate the user input and any uploaded or retrieved documents with deterministic rules. For code-heavy applications, a language segmenter can help split JavaScript into more meaningful units before scanning for risky tokens, secrets, or policy violations. Next, pass only approved context into the agent. During model execution, inspect proposed tool calls by checking the tool name, arguments, caller context, and expected side effects. If a tool touches external systems, require explicit approval or a stricter policy.
After the tool runs, inspect the result before it becomes model-visible context. Raw JSON from APIs, database results, logs, and search snippets can contain secrets or prompt-injection text. The same guardrail strategy should apply to the final response: validate that required structure is present, that sensitive content has not leaked, and that the answer follows product rules. If a check fails, the runtime can block, retry with safer instructions, redact the problematic content, escalate to a human reviewer, or return a policy-specific error message.
Relevant Source Files
libs/langchain/langchain_classic/document_loaders/parsers/language/javascript.py— Defines the compatibility import surface forJavaScriptSegmenter, including deprecated lookup routing throughcreate_importer, dynamic__getattr__, and the public__all__export. This supports code-aware preprocessing scenarios that may feed deterministic guardrail checks over JavaScript documents.
Implementation Guidance
Treat guardrails as part of the agent contract rather than as a single afterthought filter. Document which checks run at each boundary, what data they can see, and what action they take when they fail. Deterministic checks should be explicit and easy to test. Model-based checks should be reserved for semantic review, and their prompts, thresholds, and fallback behavior should be versioned. For tool calls, keep policy close to the tool schema: validate the arguments the model supplied, not only the natural-language request that preceded them.
When using language-specific preprocessing, keep compatibility imports separate from policy implementation. The JavaScript parser module in langchain_classic is an import-routing layer, so application code should depend on it only for access to the segmenter surface. The guardrail itself should live in middleware, chain logic, indexing code, or an agent wrapper where it can observe inputs, tool calls, outputs, and run context. That separation keeps policy changes independent from package migration details and makes it easier to test policy behavior directly.
Testing Signals and Next Steps
Test guardrails with examples that represent both allowed and blocked behavior. Include obvious deterministic cases, such as email addresses or credit-card-like values, and adversarial cases, such as prompt-injection text hidden in retrieved documents or tool outputs. For tool-call policies, test approved, rejected, malformed, and approval-required calls. For output validation, test redaction, masking, hashing, blocking, and retry behavior as separate outcomes. Good guardrail tests should assert the intervention decision as well as the transformed content returned to the agent or user.
Next, connect this page with the middleware and human-in-the-loop documentation. Middleware is the usual place to intercept agent execution around model and tool calls, while approval workflows are the operational pattern for decisions that should not be made automatically. If your application ingests JavaScript or other source code, pair language-aware document segmentation with deterministic secret scanning and prompt-injection checks before retrieved content reaches the model.