Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix: substitute Message variables literally to avoid re.error on regex escapes (#17319)

rsnetworkinginc8e6f94bfa6a4
diff --git a/agent/component/message.py b/agent/component/message.py
index dbdd58c1fc..d72a598264 100644
--- a/agent/component/message.py
+++ b/agent/component/message.py
@@ -259,6 +259,18 @@ class Message(ComponentBase):
patt = [r"\{%.*%\}", "{{", "}}"]
return any([re.search(p, content) for p in patt])
+ @staticmethod
+ def _apply_kwargs(content: str, kwargs: dict) -> str:
+ # Substitute the sanitized variable tokens with their concrete values.
+ # Both the token and the value are literals, so use str.replace rather
+ # than re.sub: a value containing regex escape sequences (e.g. a Windows
+ # path like "C:\10" or LaTeX like "\begin") would otherwise be read as a
+ # replacement backreference and raise re.error.
+ for n, v in kwargs.items():
+ if v is not None:
+ content = content.replace(n, str(v))
+ return content
+
@timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 10 * 60)))
def _invoke(self, **kwargs):
if self.check_if_canceled("Message processing"):
@@ -281,9 +293,7 @@ class Message(ComponentBase):
if self.check_if_canceled("Message processing"):
return
- for n, v in kwargs.items():
- if v is not None:
- content = re.sub(n, str(v), content)
+ content = self._apply_kwargs(content, kwargs)
self.set_output("downloads", downloads)
self.set_output("content", content)
diff --git a/test/unit_test/agent/component/test_message_kwargs_substitution.py b/test/unit_test/agent/component/test_message_kwargs_substitution.py
new file mode 100644
index 0000000000..3d10cd1f96
--- /dev/null
+++ b/test/unit_test/agent/component/test_message_kwargs_substitution.py
@@ -0,0 +1,31 @@
+import pytest
+
+from agent.component.message import Message
+
+
+def test_apply_kwargs_substitutes_value_with_regex_escapes():
+ # A value containing backslash-digit sequences (e.g. a Windows path) must be
+ # inserted verbatim, not interpreted as a regex replacement backreference.
+ content = Message._apply_kwargs("path is _v end", {"_v": r"C:\10\report"})
+ assert content == r"path is C:\10\report end"
+
+
+def test_apply_kwargs_handles_token_with_regex_metacharacters():
+ # The sanitized token is matched literally, so metacharacters in it are not
+ # treated as a pattern.
+ content = Message._apply_kwargs("value _a[0] here", {"_a[0]": "x"})
+ assert content == "value x here"
+
+
+def test_apply_kwargs_replaces_all_occurrences():
+ content = Message._apply_kwargs("_a and _a", {"_a": "x"})
+ assert content == "x and x"
+
+
+def test_apply_kwargs_skips_none_values():
+ content = Message._apply_kwargs("_a stays", {"_a": None})
+ assert content == "_a stays"