Skip to content

Commit aa19ebd

Browse files
committed
style(core): replace regex with string search
1 parent 3869806 commit aa19ebd

File tree

2 files changed

+11
-9
lines changed

2 files changed

+11
-9
lines changed

libs/core/langchain_core/runnables/graph_mermaid.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
import asyncio
44
import base64
5-
import hashlib
65
import random
76
import re
7+
import string
88
import time
99
from dataclasses import asdict
1010
from pathlib import Path
@@ -194,8 +194,7 @@ def add_subgraph(edges: list[Edge], prefix: str) -> None:
194194
edge_label = " -.-> " if edge.conditional else " --> "
195195

196196
mermaid_graph += (
197-
f"\t{_to_safe_id(source)}{edge_label}"
198-
f"{_to_safe_id(target)};\n"
197+
f"\t{_to_safe_id(source)}{edge_label}{_to_safe_id(target)};\n"
199198
)
200199

201200
# Recursively add nested subgraphs
@@ -240,18 +239,20 @@ def add_subgraph(edges: list[Edge], prefix: str) -> None:
240239

241240

242241
def _to_safe_id(label: str) -> str:
243-
"""
242+
"""Convert a string into a Mermaid-compatible node id.
243+
244244
Keep [a-zA-Z0-9_-] characters unchanged.
245-
Map every other character -> \ + lowercase hex codepoint.
246-
Result is only [a-zA-Z0-9\\_-], which is Mermaid compatible.
245+
Map every other character -> backslash + lowercase hex codepoint.
246+
Result is Mermaid compatible.
247247
"""
248+
allowed = string.ascii_letters + string.digits + "_-"
248249
out = []
249250
for ch in label:
250-
if re.match(r"[a-zA-Z0-9\\_-]", ch):
251+
if ch in allowed:
251252
out.append(ch)
252253
else:
253-
out.append('\\' + format(ord(ch), 'x'))
254-
return ''.join(out)
254+
out.append("\\" + format(ord(ch), "x"))
255+
return "".join(out)
255256

256257

257258
def _generate_mermaid_graph_styles(node_colors: NodeStyles) -> str:

libs/core/tests/unit_tests/runnables/test_graph.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,7 @@ def test_graph_mermaid_to_safe_id() -> None:
523523
assert _to_safe_id("foo_1") == "foo_1"
524524
assert _to_safe_id("#foo*&!") == "\\23foo\\2a\\26\\21"
525525

526+
526527
def test_graph_mermaid_duplicate_nodes(snapshot: SnapshotAssertion) -> None:
527528
fake_llm = FakeListLLM(responses=["foo", "bar"])
528529
sequence: Runnable = (

0 commit comments

Comments
 (0)