langchain 1.0.0rc1__py3-none-any.whl → 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,15 +2,22 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- import hashlib
6
- import ipaddress
7
- import re
8
5
  from typing import TYPE_CHECKING, Any, Literal
9
- from urllib.parse import urlparse
10
6
 
11
7
  from langchain_core.messages import AIMessage, AnyMessage, HumanMessage, ToolMessage
12
- from typing_extensions import TypedDict
13
8
 
9
+ from langchain.agents.middleware._redaction import (
10
+ PIIDetectionError,
11
+ PIIMatch,
12
+ RedactionRule,
13
+ ResolvedRedactionRule,
14
+ apply_strategy,
15
+ detect_credit_card,
16
+ detect_email,
17
+ detect_ip,
18
+ detect_mac_address,
19
+ detect_url,
20
+ )
14
21
  from langchain.agents.middleware.types import AgentMiddleware, AgentState, hook_config
15
22
 
16
23
  if TYPE_CHECKING:
@@ -19,396 +26,6 @@ if TYPE_CHECKING:
19
26
  from langgraph.runtime import Runtime
20
27
 
21
28
 
22
- class PIIMatch(TypedDict):
23
- """Represents a detected PII match in text."""
24
-
25
- type: str
26
- """The type of PII detected (e.g., 'email', 'ssn', 'credit_card')."""
27
- value: str
28
- """The actual matched text."""
29
- start: int
30
- """Starting position of the match in the text."""
31
- end: int
32
- """Ending position of the match in the text."""
33
-
34
-
35
- class PIIDetectionError(Exception):
36
- """Exception raised when PII is detected and strategy is 'block'."""
37
-
38
- def __init__(self, pii_type: str, matches: list[PIIMatch]) -> None:
39
- """Initialize the exception with PII detection information.
40
-
41
- Args:
42
- pii_type: The type of PII that was detected.
43
- matches: List of PII matches found.
44
- """
45
- self.pii_type = pii_type
46
- self.matches = matches
47
- count = len(matches)
48
- msg = f"Detected {count} instance(s) of {pii_type} in message content"
49
- super().__init__(msg)
50
-
51
-
52
- # ============================================================================
53
- # PII Detection Functions
54
- # ============================================================================
55
-
56
-
57
- def _luhn_checksum(card_number: str) -> bool:
58
- """Validate credit card number using Luhn algorithm.
59
-
60
- Args:
61
- card_number: Credit card number string (digits only).
62
-
63
- Returns:
64
- True if the number passes Luhn validation, False otherwise.
65
- """
66
- digits = [int(d) for d in card_number if d.isdigit()]
67
-
68
- if len(digits) < 13 or len(digits) > 19:
69
- return False
70
-
71
- checksum = 0
72
- for i, digit in enumerate(reversed(digits)):
73
- d = digit
74
- if i % 2 == 1:
75
- d *= 2
76
- if d > 9:
77
- d -= 9
78
- checksum += d
79
-
80
- return checksum % 10 == 0
81
-
82
-
83
- def detect_email(content: str) -> list[PIIMatch]:
84
- """Detect email addresses in content.
85
-
86
- Args:
87
- content: Text content to scan.
88
-
89
- Returns:
90
- List of detected email matches.
91
- """
92
- pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
93
- return [
94
- PIIMatch(
95
- type="email",
96
- value=match.group(),
97
- start=match.start(),
98
- end=match.end(),
99
- )
100
- for match in re.finditer(pattern, content)
101
- ]
102
-
103
-
104
- def detect_credit_card(content: str) -> list[PIIMatch]:
105
- """Detect credit card numbers in content using Luhn validation.
106
-
107
- Detects cards in formats like:
108
- - 1234567890123456
109
- - 1234 5678 9012 3456
110
- - 1234-5678-9012-3456
111
-
112
- Args:
113
- content: Text content to scan.
114
-
115
- Returns:
116
- List of detected credit card matches.
117
- """
118
- # Match various credit card formats
119
- pattern = r"\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b"
120
- matches = []
121
-
122
- for match in re.finditer(pattern, content):
123
- card_number = match.group()
124
- # Validate with Luhn algorithm
125
- if _luhn_checksum(card_number):
126
- matches.append(
127
- PIIMatch(
128
- type="credit_card",
129
- value=card_number,
130
- start=match.start(),
131
- end=match.end(),
132
- )
133
- )
134
-
135
- return matches
136
-
137
-
138
- def detect_ip(content: str) -> list[PIIMatch]:
139
- """Detect IP addresses in content using stdlib validation.
140
-
141
- Validates both IPv4 and IPv6 addresses.
142
-
143
- Args:
144
- content: Text content to scan.
145
-
146
- Returns:
147
- List of detected IP address matches.
148
- """
149
- matches = []
150
-
151
- # IPv4 pattern
152
- ipv4_pattern = r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b"
153
-
154
- for match in re.finditer(ipv4_pattern, content):
155
- ip_str = match.group()
156
- try:
157
- # Validate with stdlib
158
- ipaddress.ip_address(ip_str)
159
- matches.append(
160
- PIIMatch(
161
- type="ip",
162
- value=ip_str,
163
- start=match.start(),
164
- end=match.end(),
165
- )
166
- )
167
- except ValueError:
168
- # Not a valid IP address
169
- pass
170
-
171
- return matches
172
-
173
-
174
- def detect_mac_address(content: str) -> list[PIIMatch]:
175
- """Detect MAC addresses in content.
176
-
177
- Detects formats like:
178
- - 00:1A:2B:3C:4D:5E
179
- - 00-1A-2B-3C-4D-5E
180
-
181
- Args:
182
- content: Text content to scan.
183
-
184
- Returns:
185
- List of detected MAC address matches.
186
- """
187
- pattern = r"\b([0-9A-Fa-f]{2}[:-]){5}[0-9A-Fa-f]{2}\b"
188
- return [
189
- PIIMatch(
190
- type="mac_address",
191
- value=match.group(),
192
- start=match.start(),
193
- end=match.end(),
194
- )
195
- for match in re.finditer(pattern, content)
196
- ]
197
-
198
-
199
- def detect_url(content: str) -> list[PIIMatch]:
200
- """Detect URLs in content using regex and stdlib validation.
201
-
202
- Detects:
203
- - http://example.com
204
- - https://example.com/path
205
- - www.example.com
206
- - example.com/path
207
-
208
- Args:
209
- content: Text content to scan.
210
-
211
- Returns:
212
- List of detected URL matches.
213
- """
214
- matches = []
215
-
216
- # Pattern 1: URLs with scheme (http:// or https://)
217
- scheme_pattern = r"https?://[^\s<>\"{}|\\^`\[\]]+"
218
-
219
- for match in re.finditer(scheme_pattern, content):
220
- url = match.group()
221
- try:
222
- result = urlparse(url)
223
- if result.scheme in ("http", "https") and result.netloc:
224
- matches.append(
225
- PIIMatch(
226
- type="url",
227
- value=url,
228
- start=match.start(),
229
- end=match.end(),
230
- )
231
- )
232
- except Exception: # noqa: S110, BLE001
233
- # Invalid URL, skip
234
- pass
235
-
236
- # Pattern 2: URLs without scheme (www.example.com or example.com/path)
237
- # More conservative to avoid false positives
238
- bare_pattern = r"\b(?:www\.)?[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?:/[^\s]*)?" # noqa: E501
239
-
240
- for match in re.finditer(bare_pattern, content):
241
- # Skip if already matched with scheme
242
- if any(
243
- m["start"] <= match.start() < m["end"] or m["start"] < match.end() <= m["end"]
244
- for m in matches
245
- ):
246
- continue
247
-
248
- url = match.group()
249
- # Only accept if it has a path or starts with www
250
- # This reduces false positives like "example.com" in prose
251
- if "/" in url or url.startswith("www."):
252
- try:
253
- # Add scheme for validation (required for urlparse to work correctly)
254
- test_url = f"http://{url}"
255
- result = urlparse(test_url)
256
- if result.netloc and "." in result.netloc:
257
- matches.append(
258
- PIIMatch(
259
- type="url",
260
- value=url,
261
- start=match.start(),
262
- end=match.end(),
263
- )
264
- )
265
- except Exception: # noqa: S110, BLE001
266
- # Invalid URL, skip
267
- pass
268
-
269
- return matches
270
-
271
-
272
- # Built-in detector registry
273
- _BUILTIN_DETECTORS: dict[str, Callable[[str], list[PIIMatch]]] = {
274
- "email": detect_email,
275
- "credit_card": detect_credit_card,
276
- "ip": detect_ip,
277
- "mac_address": detect_mac_address,
278
- "url": detect_url,
279
- }
280
-
281
-
282
- # ============================================================================
283
- # Strategy Implementations
284
- # ============================================================================
285
-
286
-
287
- def _apply_redact_strategy(content: str, matches: list[PIIMatch]) -> str:
288
- """Replace PII with [REDACTED_TYPE] placeholders.
289
-
290
- Args:
291
- content: Original content.
292
- matches: List of PII matches to redact.
293
-
294
- Returns:
295
- Content with PII redacted.
296
- """
297
- if not matches:
298
- return content
299
-
300
- # Sort matches by start position in reverse to avoid offset issues
301
- sorted_matches = sorted(matches, key=lambda m: m["start"], reverse=True)
302
-
303
- result = content
304
- for match in sorted_matches:
305
- replacement = f"[REDACTED_{match['type'].upper()}]"
306
- result = result[: match["start"]] + replacement + result[match["end"] :]
307
-
308
- return result
309
-
310
-
311
- def _apply_mask_strategy(content: str, matches: list[PIIMatch]) -> str:
312
- """Partially mask PII, showing only last few characters.
313
-
314
- Args:
315
- content: Original content.
316
- matches: List of PII matches to mask.
317
-
318
- Returns:
319
- Content with PII masked.
320
- """
321
- if not matches:
322
- return content
323
-
324
- # Sort matches by start position in reverse
325
- sorted_matches = sorted(matches, key=lambda m: m["start"], reverse=True)
326
-
327
- result = content
328
- for match in sorted_matches:
329
- value = match["value"]
330
- pii_type = match["type"]
331
-
332
- # Different masking strategies by type
333
- if pii_type == "email":
334
- # Show only domain: user@****.com
335
- parts = value.split("@")
336
- if len(parts) == 2:
337
- domain_parts = parts[1].split(".")
338
- if len(domain_parts) >= 2:
339
- masked = f"{parts[0]}@****.{domain_parts[-1]}"
340
- else:
341
- masked = f"{parts[0]}@****"
342
- else:
343
- masked = "****"
344
-
345
- elif pii_type == "credit_card":
346
- # Show last 4: ****-****-****-1234
347
- digits_only = "".join(c for c in value if c.isdigit())
348
- separator = "-" if "-" in value else " " if " " in value else ""
349
- if separator:
350
- masked = f"****{separator}****{separator}****{separator}{digits_only[-4:]}"
351
- else:
352
- masked = f"************{digits_only[-4:]}"
353
-
354
- elif pii_type == "ip":
355
- # Show last octet: *.*.*. 123
356
- parts = value.split(".")
357
- masked = f"*.*.*.{parts[-1]}" if len(parts) == 4 else "****"
358
-
359
- elif pii_type == "mac_address":
360
- # Show last byte: **:**:**:**:**:5E
361
- separator = ":" if ":" in value else "-"
362
- masked = (
363
- f"**{separator}**{separator}**{separator}**{separator}**{separator}{value[-2:]}"
364
- )
365
-
366
- elif pii_type == "url":
367
- # Mask everything: [MASKED_URL]
368
- masked = "[MASKED_URL]"
369
-
370
- else:
371
- # Default: show last 4 chars
372
- masked = f"****{value[-4:]}" if len(value) > 4 else "****"
373
-
374
- result = result[: match["start"]] + masked + result[match["end"] :]
375
-
376
- return result
377
-
378
-
379
- def _apply_hash_strategy(content: str, matches: list[PIIMatch]) -> str:
380
- """Replace PII with deterministic hash including type information.
381
-
382
- Args:
383
- content: Original content.
384
- matches: List of PII matches to hash.
385
-
386
- Returns:
387
- Content with PII replaced by hashes in format <type_hash:digest>.
388
- """
389
- if not matches:
390
- return content
391
-
392
- # Sort matches by start position in reverse
393
- sorted_matches = sorted(matches, key=lambda m: m["start"], reverse=True)
394
-
395
- result = content
396
- for match in sorted_matches:
397
- value = match["value"]
398
- pii_type = match["type"]
399
- # Create deterministic hash
400
- hash_digest = hashlib.sha256(value.encode()).hexdigest()[:8]
401
- replacement = f"<{pii_type}_hash:{hash_digest}>"
402
- result = result[: match["start"]] + replacement + result[match["end"] :]
403
-
404
- return result
405
-
406
-
407
- # ============================================================================
408
- # PIIMiddleware
409
- # ============================================================================
410
-
411
-
412
29
  class PIIMiddleware(AgentMiddleware):
413
30
  """Detect and handle Personally Identifiable Information (PII) in agent conversations.
414
31
 
@@ -510,50 +127,34 @@ class PIIMiddleware(AgentMiddleware):
510
127
  """
511
128
  super().__init__()
512
129
 
513
- self.pii_type = pii_type
514
- self.strategy = strategy
515
130
  self.apply_to_input = apply_to_input
516
131
  self.apply_to_output = apply_to_output
517
132
  self.apply_to_tool_results = apply_to_tool_results
518
133
 
519
- # Resolve detector
520
- if detector is None:
521
- # Use built-in detector
522
- if pii_type not in _BUILTIN_DETECTORS:
523
- msg = (
524
- f"Unknown PII type: {pii_type}. "
525
- f"Must be one of {list(_BUILTIN_DETECTORS.keys())} "
526
- "or provide a custom detector."
527
- )
528
- raise ValueError(msg)
529
- self.detector = _BUILTIN_DETECTORS[pii_type]
530
- elif isinstance(detector, str):
531
- # Custom regex pattern
532
- pattern = detector
533
-
534
- def regex_detector(content: str) -> list[PIIMatch]:
535
- return [
536
- PIIMatch(
537
- type=pii_type,
538
- value=match.group(),
539
- start=match.start(),
540
- end=match.end(),
541
- )
542
- for match in re.finditer(pattern, content)
543
- ]
544
-
545
- self.detector = regex_detector
546
- else:
547
- # Custom callable detector
548
- self.detector = detector
134
+ self._resolved_rule: ResolvedRedactionRule = RedactionRule(
135
+ pii_type=pii_type,
136
+ strategy=strategy,
137
+ detector=detector,
138
+ ).resolve()
139
+ self.pii_type = self._resolved_rule.pii_type
140
+ self.strategy = self._resolved_rule.strategy
141
+ self.detector = self._resolved_rule.detector
549
142
 
550
143
  @property
551
144
  def name(self) -> str:
552
145
  """Name of the middleware."""
553
146
  return f"{self.__class__.__name__}[{self.pii_type}]"
554
147
 
148
+ def _process_content(self, content: str) -> tuple[str, list[PIIMatch]]:
149
+ """Apply the configured redaction rule to the provided content."""
150
+ matches = self.detector(content)
151
+ if not matches:
152
+ return content, []
153
+ sanitized = apply_strategy(content, matches, self.strategy)
154
+ return sanitized, matches
155
+
555
156
  @hook_config(can_jump_to=["end"])
556
- def before_model( # noqa: PLR0915
157
+ def before_model(
557
158
  self,
558
159
  state: AgentState,
559
160
  runtime: Runtime, # noqa: ARG002
@@ -594,25 +195,9 @@ class PIIMiddleware(AgentMiddleware):
594
195
  if last_user_idx is not None and last_user_msg and last_user_msg.content:
595
196
  # Detect PII in message content
596
197
  content = str(last_user_msg.content)
597
- matches = self.detector(content)
198
+ new_content, matches = self._process_content(content)
598
199
 
599
200
  if matches:
600
- # Apply strategy
601
- if self.strategy == "block":
602
- raise PIIDetectionError(self.pii_type, matches)
603
-
604
- if self.strategy == "redact":
605
- new_content = _apply_redact_strategy(content, matches)
606
- elif self.strategy == "mask":
607
- new_content = _apply_mask_strategy(content, matches)
608
- elif self.strategy == "hash":
609
- new_content = _apply_hash_strategy(content, matches)
610
- else:
611
- # Should not reach here due to type hints
612
- msg = f"Unknown strategy: {self.strategy}"
613
- raise ValueError(msg)
614
-
615
- # Create updated message
616
201
  updated_message: AnyMessage = HumanMessage(
617
202
  content=new_content,
618
203
  id=last_user_msg.id,
@@ -641,26 +226,11 @@ class PIIMiddleware(AgentMiddleware):
641
226
  continue
642
227
 
643
228
  content = str(tool_msg.content)
644
- matches = self.detector(content)
229
+ new_content, matches = self._process_content(content)
645
230
 
646
231
  if not matches:
647
232
  continue
648
233
 
649
- # Apply strategy
650
- if self.strategy == "block":
651
- raise PIIDetectionError(self.pii_type, matches)
652
-
653
- if self.strategy == "redact":
654
- new_content = _apply_redact_strategy(content, matches)
655
- elif self.strategy == "mask":
656
- new_content = _apply_mask_strategy(content, matches)
657
- elif self.strategy == "hash":
658
- new_content = _apply_hash_strategy(content, matches)
659
- else:
660
- # Should not reach here due to type hints
661
- msg = f"Unknown strategy: {self.strategy}"
662
- raise ValueError(msg)
663
-
664
234
  # Create updated tool message
665
235
  updated_message = ToolMessage(
666
236
  content=new_content,
@@ -716,26 +286,11 @@ class PIIMiddleware(AgentMiddleware):
716
286
 
717
287
  # Detect PII in message content
718
288
  content = str(last_ai_msg.content)
719
- matches = self.detector(content)
289
+ new_content, matches = self._process_content(content)
720
290
 
721
291
  if not matches:
722
292
  return None
723
293
 
724
- # Apply strategy
725
- if self.strategy == "block":
726
- raise PIIDetectionError(self.pii_type, matches)
727
-
728
- if self.strategy == "redact":
729
- new_content = _apply_redact_strategy(content, matches)
730
- elif self.strategy == "mask":
731
- new_content = _apply_mask_strategy(content, matches)
732
- elif self.strategy == "hash":
733
- new_content = _apply_hash_strategy(content, matches)
734
- else:
735
- # Should not reach here due to type hints
736
- msg = f"Unknown strategy: {self.strategy}"
737
- raise ValueError(msg)
738
-
739
294
  # Create updated message
740
295
  updated_message = AIMessage(
741
296
  content=new_content,
@@ -749,3 +304,14 @@ class PIIMiddleware(AgentMiddleware):
749
304
  new_messages[last_ai_idx] = updated_message
750
305
 
751
306
  return {"messages": new_messages}
307
+
308
+
309
+ __all__ = [
310
+ "PIIDetectionError",
311
+ "PIIMiddleware",
312
+ "detect_credit_card",
313
+ "detect_email",
314
+ "detect_ip",
315
+ "detect_mac_address",
316
+ "detect_url",
317
+ ]