Ensure functions have docstrings for documentation
def init(self) -> dict[str, Any]:
1"""PII detection and handling middleware for agents."""23from __future__ import annotations45from functools import partial6from typing import TYPE_CHECKING, Any, ClassVar, Literal78from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, ToolMessage9from langgraph.stream import StreamTransformer10from typing_extensions import override1112from langchain.agents.middleware._redaction import (13 PIIDetectionError,14 PIIMatch,15 RedactionRule,16 ResolvedRedactionRule,17 apply_strategy,18 detect_credit_card,19 detect_email,20 detect_ip,21 detect_mac_address,22 detect_url,23)24from langchain.agents.middleware.types import (25 AgentMiddleware,26 AgentState,27 ContextT,28 ResponseT,29 hook_config,30)3132if TYPE_CHECKING:33 from collections.abc import Callable3435 from langgraph.runtime import Runtime36 from langgraph.stream._types import ProtocolEvent373839_DEFAULT_STREAM_LOOKBACK = 12840"""Default trailing-buffer size for cross-delta PII detection.4142The transformer always holds the last `lookback` characters in a per-content43block buffer so that PII patterns straddling delta boundaries are detected44before any text is released downstream. 128 comfortably covers the built-in45detectors (the credit-card regex tops out at 19 characters; URLs and emails46are typically well under 100) while bounding first-token latency.47"""484950class _PIIStreamTransformer(StreamTransformer):51 """Mutates `content-block-delta` text and tool-call args in flight.5253 Runs before built-in stream transformers so the redacted text is what54 every downstream consumer sees — both the main protocol event log and55 the `run.messages` projection that `MessagesTransformer` snapshots into.5657 Holds a sliding buffer of the most recent text or tool-call args per58 (run_id, content block index) so PII patterns that straddle delta59 boundaries are caught.60 Anything older than `lookback` characters is redacted with the resolved61 rule's strategy and emitted as the new delta text; the trailing tail62 stays in the buffer until a later delta extends it past the cap or the63 block's finish event flushes the snapshot.64 """6566 before_builtins: ClassVar[bool] = True67 required_stream_modes: ClassVar[tuple[str, ...]] = ("messages", "tools", "values")6869 def __init__(70 self,71 scope: tuple[str, ...] = (),72 *,73 rule: ResolvedRedactionRule,74 lookback: int = _DEFAULT_STREAM_LOOKBACK,75 ) -> None:76 super().__init__(scope)77 self._rule = rule78 self._lookback = lookback79 # Text/reasoning/tool-call-args deltas keyed by80 # `(run_id, content_block_index)`.81 self._buffers: dict[tuple[str, int], str] = {}82 # Tool-output-delta buffers keyed by `tool_call_id`. Held in a83 # separate dict so `_drop_run` on the messages channel can't84 # sweep active tool-output state.85 self._tool_buffers: dict[str, str] = {}8687 def init(self) -> dict[str, Any]:88 # No projection — this transformer mutates events in place rather89 # than building a derived view.90 return {}9192 def process(self, event: ProtocolEvent) -> bool:93 method = event["method"]94 if method == "messages":95 return self._process_messages_event(event)96 if method == "tools":97 return self._process_tools_event(event)98 if method == "values":99 return self._process_values_event(event)100 return True101102 def _process_values_event(self, event: ProtocolEvent) -> bool:103 """Redact the state snapshot on the `values` channel.104105 State snapshots emitted between nodes carry the full state dict,106 which typically includes the messages list. Walking the snapshot107 with `_redact_value` returns a fresh structure where every108 message has a redacted copy of its content — the original109 objects in graph state remain intact for the state-level110 enforcer (`apply_to_tool_results` via `before_model`) to act on111 independently when the agent loops back.112 """113 data = event["params"].get("data")114 if data is None:115 return True116 event["params"]["data"] = self._redact_value(data)117 return True118119 def _process_messages_event(self, event: ProtocolEvent) -> bool:120 params = event["params"]121 data = params.get("data")122 if not isinstance(data, tuple) or len(data) != 2: # noqa: PLR2004123 return True124 payload, metadata = data125126 # Legacy `(BaseMessage, metadata)` shape: the langgraph→langchain127 # integration emits this when a model only implements `_generate`128 # (or when its `_astream` falls back), producing a single event129 # carrying the full message rather than streamed content-block130 # deltas. Swap in a redacted copy so the consumer sees scrubbed131 # text on the wire while the original stays intact in graph state132 # for `after_model` to act on independently. Under `block`,133 # `_redact_base_message` raises `PIIDetectionError` via134 # `apply_strategy` before we get here.135 if isinstance(payload, BaseMessage):136 redacted = self._redact_base_message(payload)137 if redacted is not payload:138 params["data"] = (redacted, metadata)139 return True140141 if not isinstance(payload, dict):142 return True143 kind = payload.get("event")144 run_id = str(metadata.get("run_id") or "") if metadata else ""145146 if kind == "content-block-delta":147 self._mutate_delta(payload, run_id)148 elif kind == "content-block-finish":149 self._finalize_block(payload, run_id)150 elif kind in {"message-finish", "error"}:151 self._drop_run(run_id)152 return True153154 def _process_tools_event(self, event: ProtocolEvent) -> bool:155 data = event["params"].get("data")156 if not isinstance(data, dict):157 return True158 kind = data.get("event")159 tool_call_id = data.get("tool_call_id")160161 if kind == "tool-started":162 # Tool inputs may be a dict (multi-arg tools), a string163 # (single-arg tools — `BaseTool._parse_input` passes the164 # raw string through), or a list (array-input tools).165 # `_redact_value` handles all three uniformly.166 if "input" in data:167 data["input"] = self._redact_value(data["input"])168 elif kind == "tool-output-delta":169 # Use the tool_call_id as buffer key when present; fall back170 # to a None-keyed slot for the rare malformed/custom emitter171 # case (the buffer becomes shared but at least redaction runs).172 self._mutate_tool_output_delta(173 data, tool_call_id if isinstance(tool_call_id, str) else ""174 )175 elif kind == "tool-finished":176 if "output" in data:177 data["output"] = self._redact_value(data["output"])178 if isinstance(tool_call_id, str):179 self._tool_buffers.pop(tool_call_id, None)180 elif kind == "tool-error":181 msg = data.get("message")182 if isinstance(msg, str) and msg:183 matches = self._rule.detector(msg)184 if matches:185 data["message"] = apply_strategy(msg, matches, self._rule.strategy)186 if isinstance(tool_call_id, str):187 self._tool_buffers.pop(tool_call_id, None)188189 return True190191 def _mutate_tool_output_delta(self, data: dict[str, Any], tool_call_id: str) -> None:192 """Redact a `tool-output-delta` payload.193194 String deltas go through the same lookback machinery as195 text-deltas, keyed by `tool_call_id` in the disjoint196 `_tool_buffers` dict so `_drop_run` on the messages channel197 can't sweep active tool-output state.198199 Structured deltas (dict/list) walk recursively without200 buffering — they don't have a position-stable shape across201 deltas to buffer against.202 """203 delta = data.get("delta")204 if isinstance(delta, str):205 held = self._tool_buffers.get(tool_call_id, "")206 combined = held + delta207208 matches = self._rule.detector(combined)209 if matches:210 # `apply_strategy` raises `PIIDetectionError` under211 # `strategy="block"`, failing the run immediately —212 # cleaner than withholding deltas until `after_model`213 # raises later.214 combined = apply_strategy(combined, matches, self._rule.strategy)215216 emit_end = max(0, len(combined) - self._lookback)217 self._tool_buffers[tool_call_id] = combined[emit_end:]218 data["delta"] = combined[:emit_end]219 elif isinstance(delta, (dict, list)):220 data["delta"] = self._redact_value(delta)221222 def _redact_tool_call_list(self, calls: list[Any] | None) -> tuple[list[Any], bool]:223 """Walk a list of tool-call (or invalid-tool-call) dicts.224225 Returns `(new_list, changed)`. Each element's `args` is run226 through `_redact_value` regardless of its type — `tool_call.args`227 is a dict, `invalid_tool_call.args` is a raw JSON string, and228 `_redact_value` handles both shapes uniformly. If nothing229 changed, returns the input list and `changed=False`.230 """231 if not calls:232 return calls or [], False233 new_calls: list[Any] = []234 changed = False235 for tc in calls:236 if isinstance(tc, dict) and "args" in tc and tc["args"] is not None:237 redacted = self._redact_value(tc["args"])238 if redacted != tc["args"]:239 new_tc = dict(tc)240 new_tc["args"] = redacted241 new_calls.append(new_tc)242 changed = True243 continue244 new_calls.append(tc)245 return new_calls, changed246247 def _redact_value(self, value: Any) -> Any:248 """Recursively redact PII in string leaves of a nested structure.249250 Returns a new value where every `str` leaf that contains PII has251 been replaced (or emptied under `block`). Non-string leaves and252 the structure itself are preserved.253254 `BaseMessage` payloads (typically `ToolMessage` from255 `tool-finished.output`, or any message reached via the `values`256 channel) return a fresh copy with `.content` redacted plus257 `AIMessage.tool_calls[*].args` / `invalid_tool_calls[*].args`258 walked. The original object stays intact for state-level259 enforcers (`after_model`, `before_model` with260 `apply_to_tool_results`) to act on independently.261262 Scope mirrors the pre-streaming state-level surfaces:263 `.content` (string or list-of-content-blocks) and `tool_calls`264 args. Other message attributes (`additional_kwargs`,265 `response_metadata`, `ToolMessage.artifact`) are intentionally266 not walked here — they aren't scrubbed in graph state by the267 existing hooks, so scrubbing them on the wire would create268 a wire/state divergence.269 """270 if isinstance(value, str):271 if not value:272 return value273 matches = self._rule.detector(value)274 if not matches:275 return value276 # `apply_strategy` raises `PIIDetectionError` under `block`277 # — the run fails immediately rather than buffering until a278 # state-level hook can raise.279 return apply_strategy(value, matches, self._rule.strategy)280 if isinstance(value, BaseMessage):281 return self._redact_base_message(value)282 if isinstance(value, dict):283 return {k: self._redact_value(v) for k, v in value.items()}284 if isinstance(value, list):285 return [self._redact_value(v) for v in value]286 if isinstance(value, tuple):287 return tuple(self._redact_value(v) for v in value)288 return value289290 def _redact_base_message(self, value: BaseMessage) -> BaseMessage:291 """Return a fresh copy of `value` with PII-carrying surfaces redacted."""292 update: dict[str, Any] = {}293294 content = value.content295 if isinstance(content, str) and content:296 matches = self._rule.detector(content)297 if matches:298 update["content"] = apply_strategy(content, matches, self._rule.strategy)299 elif isinstance(content, list) and content:300 # Structured content-blocks shape:301 # `[{"type": "text", "text": "..."}, {"type": "tool_call", ...}, ...]`.302 redacted_content = self._redact_value(content)303 if redacted_content != content:304 update["content"] = redacted_content305306 # `AIMessage.tool_calls` and `.invalid_tool_calls` carry PII in307 # `args` independently of `.content`. `tool_call.args` is a308 # dict; `invalid_tool_call.args` is a raw JSON string —309 # `_redact_value` handles both shapes via the recursion.310 if isinstance(value, AIMessage):311 new_tc_list, tc_changed = self._redact_tool_call_list(value.tool_calls)312 if tc_changed:313 update["tool_calls"] = new_tc_list314 new_inv_list, inv_changed = self._redact_tool_call_list(value.invalid_tool_calls)315 if inv_changed:316 update["invalid_tool_calls"] = new_inv_list317318 if not update:319 return value320 return value.model_copy(update=update)321322 def _mutate_delta(self, payload: dict[str, Any], run_id: str) -> None:323 delta = payload.get("delta")324 if not isinstance(delta, dict):325 return326 delta_type = delta.get("type")327 if delta_type == "text-delta":328 self._mutate_string_field_delta(delta, payload, run_id, "text")329 return330 if delta_type == "reasoning-delta":331 # Reasoning content (chain-of-thought from extended-thinking332 # models) is a real PII surface — models echo back333 # user-supplied data or synthesize it from context. Run the334 # same lookback machinery as text-delta against the335 # `reasoning` field. Block indices are unique within a336 # message regardless of block type, so the buffer key337 # `(run_id, index)` naturally disjoint from text-delta keys.338 self._mutate_string_field_delta(delta, payload, run_id, "reasoning")339 return340 if delta_type == "tool-call-delta":341 # Tool-call args slices append, like text, so they get the342 # same lookback buffer. The withheld tail surfaces on343 # `content-block-finish`, whose parsed args are redacted.344 self._mutate_string_field_delta(delta, payload, run_id, "args")345 return346 if delta_type == "block-delta":347 fields = delta.get("fields")348 if isinstance(fields, dict) and fields.get("type") in {349 "tool_call_chunk",350 "server_tool_call_chunk",351 }:352 self._mutate_tool_call_chunk_delta(fields, payload, run_id)353 # Other delta types (`data-delta`, vendor block types) pass354 # through. The pre-streaming middleware scrubbed `.content` text355 # on state messages only; binary payloads and provider-specific356 # block shapes are out of scope for parity with that surface.357358 def _mutate_string_field_delta(359 self,360 delta: dict[str, Any],361 payload: dict[str, Any],362 run_id: str,363 field: str,364 ) -> None:365 """Apply the lookback-buffer redaction to a string field on a delta.366367 Shared by `text-delta` (`field="text"`), `reasoning-delta`368 (`field="reasoning"`) and `tool-call-delta` (`field="args"`).369 Buffer is keyed by `(run_id, block_index)`;370 block indices are unique within a message so different block371 types share the same key space without collision.372 """373 text = delta.get(field)374 if not isinstance(text, str) or not text:375 return376 index = payload.get("index")377 if not isinstance(index, int):378 return379380 key = (run_id, index)381 held = self._buffers.get(key, "")382 combined = held + text383384 # Run detection on the full accumulated buffer before splitting.385 # Detecting only on the about-to-emit prefix would miss matches386 # that straddle the lookback boundary — the detector's regex387 # needs a complete, boundary-anchored hit, so a truncated prefix388 # would fail to match and the partial PII would leak on the389 # wire. Under `strategy="block"`, `apply_strategy` raises390 # `PIIDetectionError` here, failing the run as soon as PII391 # arrives rather than buffering until `after_model`.392 matches = self._rule.detector(combined)393 if matches:394 combined = apply_strategy(combined, matches, self._rule.strategy)395396 emit_end = max(0, len(combined) - self._lookback)397 self._buffers[key] = combined[emit_end:]398 delta[field] = combined[:emit_end]399400 def _mutate_tool_call_chunk_delta(401 self,402 fields: dict[str, Any],403 payload: dict[str, Any],404 run_id: str,405 ) -> None:406 """Redact cumulative tool-call args with lookback withholding.407408 Cores that predate `tool-call-delta` stream tool-call args as409 `block-delta` events whose `args` carry the full accumulated410 string, which consumers apply as a replacement. Cores that emit411 `tool-call-delta` slices go through `_mutate_string_field_delta`412 instead.413414 Detection runs on the full cumulative args so any complete PII415 anywhere in the string is redacted before emission. Lookback416 withholding then trims the trailing the lookback window characters417 from what reaches the consumer — those characters might be the418 start of a partial PII match that completes in a future419 cumulative delta. The trimmed tail surfaces at `content-block-420 finish` where `_finalize_block` redacts the parsed args dict.421422 For args that fit within the lookback window (the typical case),423 this withholds the entire args string during streaming — the424 redacted args dict appears only at finalize. For args that425 exceed the lookback window, the safe prefix streams incrementally426 as the cumulative state grows. PII that appears more than427 the lookback window characters from the cumulative tail in a428 delta where it hasn't yet completed can still surface in the429 emit prefix — same residual exposure as PII longer than430 the lookback window on the text path. The `content-block-finish`431 snapshot redaction is the backstop.432433 A replacement becomes the prefix that later `tool-call-delta`434 slices for the block append to, so the withheld tail is kept as435 that block's lookback buffer.436 """437 args = fields.get("args")438 if not isinstance(args, str) or not args:439 return440441 matches = self._rule.detector(args)442 if matches:443 # `apply_strategy` raises `PIIDetectionError` under444 # `strategy="block"` — the run fails the moment a complete445 # PII pattern surfaces in the cumulative args string.446 args = apply_strategy(args, matches, self._rule.strategy)447448 emit_end = max(0, len(args) - self._lookback)449 fields["args"] = args[:emit_end]450 index = payload.get("index")451 if isinstance(index, int):452 self._buffers[run_id, index] = args[emit_end:]453454 def _finalize_block(self, payload: dict[str, Any], run_id: str) -> None:455 index = payload.get("index")456 if not isinstance(index, int):457 return458 key = (run_id, index)459 # The finalized block carries the model's original concatenation460 # of deltas, not what we emitted on the wire. Re-run detection over461 # its full text so the snapshot matches the redacted stream.462 content = payload.get("content")463 if isinstance(content, dict):464 ctype = content.get("type")465 if ctype == "text":466 self._finalize_string_field(content, "text")467 elif ctype == "reasoning":468 self._finalize_string_field(content, "reasoning")469 elif (470 ctype in {"tool_call", "server_tool_call", "invalid_tool_call"}471 and "args" in content472 and content["args"] is not None473 ):474 # `tool_call` / `server_tool_call` args are dicts;475 # `invalid_tool_call.args` is the raw unparsed JSON476 # string. `_redact_value` handles both shapes.477 content["args"] = self._redact_value(content["args"])478 self._buffers.pop(key, None)479480 def _finalize_string_field(self, content: dict[str, Any], field: str) -> None:481 """Re-redact a string content-block field on `content-block-finish`.482483 Used for `text` and `reasoning` content blocks. Under484 `strategy="block"` `apply_strategy` raises `PIIDetectionError`,485 failing the run immediately.486 """487 text = content.get(field)488 if not isinstance(text, str) or not text:489 return490 matches = self._rule.detector(text)491 if not matches:492 return493 content[field] = apply_strategy(text, matches, self._rule.strategy)494495 def _drop_run(self, run_id: str) -> None:496 # Release any buffered tails for this run_id — content-block-finish497 # should have already done so for normal completion, but message-finish498 # / error paths need an explicit sweep so abandoned blocks don't499 # accumulate in long-lived processes.500 stale = [key for key in self._buffers if key[0] == run_id]501 for key in stale:502 del self._buffers[key]503504 def finalize(self) -> None:505 self._buffers.clear()506 self._tool_buffers.clear()507508 def fail(self, err: BaseException) -> None: # noqa: ARG002509 self._buffers.clear()510 self._tool_buffers.clear()511512513class PIIMiddleware(AgentMiddleware[AgentState[ResponseT], ContextT, ResponseT]):514 """Detect and handle Personally Identifiable Information (PII) in conversations.515516 This middleware detects common PII types and applies configurable strategies517 to handle them. It can detect emails, credit cards, IP addresses, MAC addresses, and518 URLs in both user input and agent output.519520 Built-in PII types:521522 - `email`: Email addresses523 - `credit_card`: Credit card numbers (validated with Luhn algorithm)524 - `ip`: IP addresses (validated with stdlib)525 - `mac_address`: MAC addresses526 - `url`: URLs (both `http`/`https` and bare URLs)527528 Strategies:529530 - `block`: Raise an exception when PII is detected531 - `redact`: Replace PII with `[REDACTED_TYPE]` placeholders532 - `mask`: Partially mask PII (e.g., `****-****-****-1234` for credit card)533 - `hash`: Replace PII with deterministic hash (e.g., `<email_hash:a1b2c3d4>`)534535 Strategy Selection Guide:536537 | Strategy | Preserves Identity? | Best For |538 | -------- | ------------------- | --------------------------------------- |539 | `block` | N/A | Avoid PII completely |540 | `redact` | No | General compliance, log sanitization |541 | `mask` | No | Human readability, customer service UIs |542 | `hash` | Yes (pseudonymous) | Analytics, debugging |543544 Example:545 ```python546 from langchain.agents.middleware import PIIMiddleware547 from langchain.agents import create_agent548549 # Redact all emails in user input550 agent = create_agent(551 "openai:gpt-5.5",552 middleware=[553 PIIMiddleware("email", strategy="redact"),554 ],555 )556557 # Use different strategies for different PII types558 agent = create_agent(559 "openai:gpt-5.5",560 middleware=[561 PIIMiddleware("credit_card", strategy="mask"),562 PIIMiddleware("url", strategy="redact"),563 PIIMiddleware("ip", strategy="hash"),564 ],565 )566567 # Custom PII type with regex568 agent = create_agent(569 "openai:gpt-5.5",570 middleware=[571 PIIMiddleware("api_key", detector=r"sk-[a-zA-Z0-9]{32}", strategy="block"),572 ],573 )574 ```575 """576577 def __init__(578 self,579 # From a typing point of view, the literals are covered by 'str'.580 # Nonetheless, we escape PYI051 to keep hints and autocompletion for the caller.581 pii_type: Literal["email", "credit_card", "ip", "mac_address", "url"] | str, # noqa: PYI051582 *,583 strategy: Literal["block", "redact", "mask", "hash"] = "redact",584 detector: Callable[[str], list[PIIMatch]] | str | None = None,585 apply_to_input: bool = True,586 apply_to_output: bool = False,587 apply_to_tool_results: bool = False,588 ) -> None:589 """Initialize the PII detection middleware.590591 Args:592 pii_type: Type of PII to detect.593594 Can be a built-in type (`email`, `credit_card`, `ip`, `mac_address`,595 `url`) or a custom type name.596 strategy: How to handle detected PII.597598 Options:599600 * `block`: Raise `PIIDetectionError` when PII is detected601 * `redact`: Replace with `[REDACTED_TYPE]` placeholders602 * `mask`: Partially mask PII (show last few characters)603 * `hash`: Replace with deterministic hash (format: `<type_hash:digest>`)604605 detector: Custom detector function or regex pattern.606607 * If `Callable`: Function that takes content string and returns608 list of `PIIMatch` objects609 * If `str`: Regex pattern to match PII610 * If `None`: Uses built-in detector for the `pii_type`611 apply_to_input: Whether to check user messages before model call.612 apply_to_output: Whether to check AI messages after model call.613614 When `True`, a stream transformer is also installed so615 that every wire surface of an agent run is redacted in616 flight:617618 * Streamed AI text deltas (`content-block-delta` of type619 `text-delta`)620 * Streamed tool-call arguments (`content-block-delta`621 of type `tool-call-delta`, or `block-delta` with622 `tool_call_chunk` / `server_tool_call_chunk` fields,623 plus the finalized `tool_call` content block on624 `content-block-finish`)625 * Tool execution events on the `tools` channel626 (`tool-started.input`, `tool-output-delta`,627 `tool-finished.output`, `tool-error.message`)628 * State snapshots on the `values` channel — message629 lists are walked and each message's `.content` is630 redacted on a fresh copy (state itself stays intact631 for `before_model` / `after_model` to act on632 independently)633634 State-level redaction via `after_model` (and635 `before_model` with `apply_to_tool_results`) remains the636 canonical enforcer; the streaming transformer ensures637 consumers reading `astream_events(version="v3")` or638 `run.messages` / `run.tool_calls` / `run.values` never639 see PII on the wire.640 apply_to_tool_results: Whether to check tool result messages after tool execution.641642 Raises:643 ValueError: If `pii_type` is not built-in and no detector is provided.644 """645 super().__init__()646647 self.apply_to_input = apply_to_input648 self.apply_to_output = apply_to_output649 self.apply_to_tool_results = apply_to_tool_results650651 self._resolved_rule: ResolvedRedactionRule = RedactionRule(652 pii_type=pii_type,653 strategy=strategy,654 detector=detector,655 ).resolve()656 self.pii_type = self._resolved_rule.pii_type657 self.strategy = self._resolved_rule.strategy658 self.detector = self._resolved_rule.detector659660 # Stream transformer scrubs the streamed surface of the same661 # messages that the state-level hooks scrub in graph state.662 # Installed whenever any output-side scrubbing is enabled —663 # `apply_to_output` covers AI messages (text, tool-call args,664 # reasoning), `apply_to_tool_results` covers tool execution665 # (the `tools` channel + ToolMessage content on `values` and666 # `messages`). For `block` the transformer raises667 # `PIIDetectionError` directly from its event handler the668 # moment a complete PII pattern is detected, failing the run669 # via langgraph's `StreamMux.afail` path. The state-level670 # `after_model` / `before_model` hooks remain a backstop for671 # non-streaming consumers.672 if self.apply_to_output or self.apply_to_tool_results:673 self.transformers = (674 partial(675 _PIIStreamTransformer,676 rule=self._resolved_rule,677 ),678 )679680 @property681 def name(self) -> str:682 """Name of the middleware."""683 return f"{self.__class__.__name__}[{self.pii_type}]"684685 def _process_content(686 self, content: str | list[str | dict[str, Any]]687 ) -> tuple[str | list[str | dict[str, Any]], bool]:688 """Apply the configured redaction rule, preserving the shape of `content`.689690 Only string leaves are redacted: a plain-string `content` directly, and691 the `text` of each block in a block-list `content`. Non-text blocks pass692 through untouched, so block-list content keeps its structure instead of693 collapsing into the `repr` of the list.694695 Args:696 content: The message content to redact.697698 Returns:699 The redacted content and whether anything was rewritten.700 """701 if isinstance(content, str):702 matches = self.detector(content)703 if not matches:704 return content, False705 return apply_strategy(content, matches, self.strategy), True706707 new_blocks: list[str | dict[str, Any]] = []708 changed = False709 for block in content:710 new_block: str | dict[str, Any] = block711 text = block if isinstance(block, str) else block.get("text")712 if isinstance(text, str) and (matches := self.detector(text)):713 redacted = apply_strategy(text, matches, self.strategy)714 new_block = redacted if isinstance(block, str) else {**block, "text": redacted}715 changed = True716 new_blocks.append(new_block)717 return (new_blocks, True) if changed else (content, False)718719 @hook_config(can_jump_to=["end"])720 @override721 def before_model(722 self,723 state: AgentState[Any],724 runtime: Runtime[ContextT],725 ) -> dict[str, Any] | None:726 """Check user messages and tool results for PII before model invocation.727728 Args:729 state: The current agent state.730 runtime: The langgraph runtime.731732 Returns:733 Updated state with PII handled according to strategy, or `None` if no PII734 detected.735736 Raises:737 PIIDetectionError: If PII is detected and strategy is `'block'`.738 """739 if not self.apply_to_input and not self.apply_to_tool_results:740 return None741742 messages = state["messages"]743 if not messages:744 return None745746 new_messages = list(messages)747 any_modified = False748749 # Check user input if enabled750 if self.apply_to_input:751 # Get last user message752 last_user_msg = None753 last_user_idx = None754 for i in range(len(messages) - 1, -1, -1):755 if isinstance(messages[i], HumanMessage):756 last_user_msg = messages[i]757 last_user_idx = i758 break759760 if last_user_idx is not None and last_user_msg and last_user_msg.content:761 new_content, changed = self._process_content(last_user_msg.content)762763 if changed:764 new_messages[last_user_idx] = last_user_msg.model_copy(765 update={"content": new_content}766 )767 any_modified = True768769 # Check tool results if enabled770 if self.apply_to_tool_results:771 # Find the last AIMessage, then process all `ToolMessage` objects after it772 last_ai_idx = None773 for i in range(len(messages) - 1, -1, -1):774 if isinstance(messages[i], AIMessage):775 last_ai_idx = i776 break777778 if last_ai_idx is not None:779 # Get all tool messages after the last AI message780 for i in range(last_ai_idx + 1, len(messages)):781 msg = messages[i]782 if isinstance(msg, ToolMessage):783 tool_msg = msg784 if not tool_msg.content:785 continue786787 new_content, changed = self._process_content(tool_msg.content)788789 if not changed:790 continue791792 new_messages[i] = tool_msg.model_copy(update={"content": new_content})793 any_modified = True794795 if any_modified:796 return {"messages": new_messages}797798 return None799800 @hook_config(can_jump_to=["end"])801 async def abefore_model(802 self,803 state: AgentState[Any],804 runtime: Runtime[ContextT],805 ) -> dict[str, Any] | None:806 """Async check user messages and tool results for PII before model invocation.807808 Args:809 state: The current agent state.810 runtime: The langgraph runtime.811812 Returns:813 Updated state with PII handled according to strategy, or `None` if no PII814 detected.815816 Raises:817 PIIDetectionError: If PII is detected and strategy is `'block'`.818 """819 return self.before_model(state, runtime)820821 @override822 def after_model(823 self,824 state: AgentState[Any],825 runtime: Runtime[ContextT],826 ) -> dict[str, Any] | None:827 """Check AI messages for PII after model invocation.828829 Args:830 state: The current agent state.831 runtime: The langgraph runtime.832833 Returns:834 Updated state with PII handled according to strategy, or None if no PII835 detected.836837 Raises:838 PIIDetectionError: If PII is detected and strategy is `'block'`.839 """840 if not self.apply_to_output:841 return None842843 messages = state["messages"]844 if not messages:845 return None846847 # Get last AI message848 last_ai_msg = None849 last_ai_idx = None850 for i in range(len(messages) - 1, -1, -1):851 msg = messages[i]852 if isinstance(msg, AIMessage):853 last_ai_msg = msg854 last_ai_idx = i855 break856857 if last_ai_idx is None or not last_ai_msg or not last_ai_msg.content:858 return None859860 new_content, changed = self._process_content(last_ai_msg.content)861862 if not changed:863 return None864865 new_messages = list(messages)866 new_messages[last_ai_idx] = last_ai_msg.model_copy(update={"content": new_content})867868 return {"messages": new_messages}869870 async def aafter_model(871 self,872 state: AgentState[Any],873 runtime: Runtime[ContextT],874 ) -> dict[str, Any] | None:875 """Async check AI messages for PII after model invocation.876877 Args:878 state: The current agent state.879 runtime: The langgraph runtime.880881 Returns:882 Updated state with PII handled according to strategy, or None if no PII883 detected.884885 Raises:886 PIIDetectionError: If PII is detected and strategy is `'block'`.887 """888 return self.after_model(state, runtime)889890891__all__ = [892 "PIIDetectionError",893 "PIIMatch",894 "PIIMiddleware",895 "detect_credit_card",896 "detect_email",897 "detect_ip",898 "detect_mac_address",899 "detect_url",900]
Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.
Generated by searchcode.com · powered by code_get_file + code_get_findings