Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(llma): don't parse literal `{...}` in context prompts as placeholders (#60389)

Georgiy Tarasov16a5a9c58d30
diff --git a/ee/hogai/test/test_tool.py b/ee/hogai/test/test_tool.py
index 17a29c9e2f64..7d29aaa2312b 100644
--- a/ee/hogai/test/test_tool.py
+++ b/ee/hogai/test/test_tool.py
@@ -47,6 +47,40 @@ class TestMaxTool(BaseTest):
result = tool.format_context_prompt_injection({})
assert result == "Value: None"
+ def test_format_context_prompt_injection_substitutes_provided_key(self):
+ tool = DummyTool(team=self.team, user=self.user, context_prompt_template="Value: {expected_key}")
+ result = tool.format_context_prompt_injection({"expected_key": "hello"})
+ assert result == "Value: hello"
+
+ def test_format_context_prompt_injection_ignores_literal_braces_in_code(self):
+ # Templates may contain literal `{...}` code snippets (e.g. Hog/JS examples).
+ # These must not be parsed as placeholders.
+ template = (
+ "Inline example: `fun name(args) { ... }` and the block form\n"
+ " fun onEvent(event) {\n"
+ " // ...\n"
+ " return event\n"
+ " }\n"
+ "End."
+ )
+ tool = DummyTool(team=self.team, user=self.user, context_prompt_template=template)
+ result = tool.format_context_prompt_injection({"current_hog_code": "let x := 1"})
+ assert result == template
+
+ def test_format_context_prompt_injection_mixed_placeholders_and_literal_braces(self):
+ template = "Code: { ... }\nKey: {expected_key}"
+ tool = DummyTool(team=self.team, user=self.user, context_prompt_template=template)
+ result = tool.format_context_prompt_injection({"expected_key": "v"})
+ assert result == "Code: { ... }\nKey: v"
+
+ def test_format_context_prompt_injection_supports_brace_escapes(self):
+ # `{{key}}` should render as `{<value>}` to preserve the prior escape behavior
+ # used by some templates (e.g. session-recording filters).
+ template = "filters={{{current_filters}}}"
+ tool = DummyTool(team=self.team, user=self.user, context_prompt_template=template)
+ result = tool.format_context_prompt_injection({"current_filters": "abc"})
+ assert result == "filters={abc}"
+
class TestMaxToolNodePath(BaseTest):
def test_node_path_uses_context_when_not_passed(self):
diff --git a/ee/hogai/tool.py b/ee/hogai/tool.py
index ea3c8fb0cd1d..cb1979205803 100644
--- a/ee/hogai/tool.py
+++ b/ee/hogai/tool.py
@@ -1,9 +1,9 @@
+import re
import json
import uuid
from abc import ABC, abstractmethod
from collections.abc import Sequence
from functools import cached_property
-from string import Formatter
from typing import Any, Literal, Self
import structlog
@@ -29,6 +29,8 @@ from ee.hogai.utils.types.base import AssistantMessageUnion, AssistantState, Nod
logger = structlog.get_logger(__name__)
+_CONTEXT_PLACEHOLDER_RE = re.compile(r"\{\{|\}\}|\{([A-Za-z_][A-Za-z0-9_]*)\}")
+
class ToolMessagesArtifact(BaseModel):
"""Return messages directly. Use with `artifact`."""
@@ -247,22 +249,31 @@ class MaxTool(AssistantContextMixin, AssistantDispatcherMixin, BaseTool):
def format_context_prompt_injection(self, context: dict[str, Any]) -> str | None:
if not self.context_prompt_template:
return None
- # Build initial context
formatted_context = {
key: (json.dumps(value) if isinstance(value, dict | list) else value) for key, value in context.items()
}
- # Extract expected keys from template
- expected_keys = {
- field for _, field, _, _ in Formatter().parse(self.context_prompt_template) if field is not None
- }
- # If they expect key is not present in the context (for example, cached FE) - use None as a default
- for key in expected_keys:
+ # Only substitute `{valid_identifier}` placeholders. Plain `str.format` parses
+ # any `{...}` — including literal code blocks like `fun onEvent(event) { ... }`
+ # in prompt templates — as placeholders, which raises on substitution.
+ # `{{` / `}}` are honored as literal-brace escapes for backwards compatibility.
+ tool_name = self.get_name()
+
+ def _substitute(match: re.Match[str]) -> str:
+ text = match.group(0)
+ if text == "{{":
+ return "{"
+ if text == "}}":
+ return "}"
+ key = match.group(1)
if key not in formatted_context:
- formatted_context[key] = None
logger.warning(
- f"Context prompt template for {self.get_name()} expects key {key} but it is not present in the context"
+ f"Context prompt template for {tool_name} expects key {key} but it is not present in the context"
)
- return self.context_prompt_template.format(**formatted_context)
+ return "None"
+ value = formatted_context[key]
+ return "None" if value is None else str(value)
+
+ return _CONTEXT_PLACEHOLDER_RE.sub(_substitute, self.context_prompt_template)
def set_node_path(self, node_path: tuple[NodePath, ...]):
self._node_path = node_path