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(aio): extract judge input text from OTel parts-shaped messages (#76569)

Christiaan Hendriksenc508a2b5d0ae
diff --git a/posthog/temporal/ai_observability/message_utils.py b/posthog/temporal/ai_observability/message_utils.py
index befc5e30d3be..eb2a10d0fe0b 100644
--- a/posthog/temporal/ai_observability/message_utils.py
+++ b/posthog/temporal/ai_observability/message_utils.py
@@ -13,6 +13,9 @@ def extract_text_from_messages(messages: Union[str, list, dict, None]) -> str:
- OpenAI tool calling: assistant messages with `tool_calls` (rendered alongside any content),
paired with `role: "tool"` results that carry a `tool_call_id` for correlation
- Anthropic: [{"role": "user", "content": [{"type": "text", "text": "..."}]}]
+ - OTel GenAI semconv: [{"role": "user", "parts": [{"type": "text", "content": "..."}]}]
+ as ingested verbatim from `gen_ai.input.messages` / `gen_ai.output.messages`
+ by `/i/v0/ai/otel` (e.g. Vercel AI SDK spans)
- Simple strings
Returns formatted string like:
@@ -30,9 +33,10 @@ def extract_text_from_messages(messages: Union[str, list, dict, None]) -> str:
formatted_parts = []
for msg in messages:
if isinstance(msg, dict):
- rendered_msg = _render_message(msg)
- if rendered_msg is not None:
- formatted_parts.append(rendered_msg)
+ for flattened in _flatten_parts_message(msg):
+ rendered_msg = _render_message(flattened)
+ if rendered_msg is not None:
+ formatted_parts.append(rendered_msg)
elif isinstance(msg, str):
formatted_parts.append(msg)
@@ -41,7 +45,79 @@ def extract_text_from_messages(messages: Union[str, list, dict, None]) -> str:
# Handle single dict message — render it the same way as a one-element
# list so that role prefixes and tool_call_id correlation are surfaced
# consistently regardless of the wrapper shape.
- return _render_message(messages) or ""
+ rendered_messages = [_render_message(flattened) for flattened in _flatten_parts_message(messages)]
+ return "\n".join(rendered for rendered in rendered_messages if rendered is not None)
+
+
+def _flatten_parts_message(msg: dict) -> list[dict]:
+ """Convert an OTel GenAI semconv parts-shaped message into flat chat message(s).
+
+ `/i/v0/ai/otel` stores `gen_ai.input.messages` / `gen_ai.output.messages` verbatim,
+ so messages arrive as `{"role": ..., "parts": [...]}` with the text inside typed
+ parts instead of a flat `content` key. `_render_message` only reads `content` and
+ `tool_calls`, which made these messages render as a bare `role:` line and left the
+ LLM judge grading an empty conversation.
+
+ Mirrors the trace UI's `otel.yaml` normalizer recipe so the judge sees the same
+ conversation the trace view renders:
+ - `{"type": "text", "content": ...}` parts join into the message's `content`
+ - `{"type": "tool_call", "id", "name", "arguments"}` parts become `tool_calls`
+ - each `{"type": "tool_call_response", "id", "result"}` part becomes its own
+ follow-up `role: "tool"` message so the existing `tool[<id>]:` correlation applies
+ - `reasoning` and other non-text parts are dropped, matching the trace view
+
+ Like the recipe, this only applies to dicts with a string `role` alongside the
+ `parts` list, so a structured-output payload that happens to have its own `parts`
+ array still reaches the JSON-stringify fallback in `_render_message`.
+
+ Messages that already carry `content` or `tool_calls`, or have no `parts` list,
+ pass through unchanged.
+ """
+ parts = msg.get("parts")
+ if not isinstance(msg.get("role"), str) or not isinstance(parts, list):
+ return [msg]
+ if msg.get("content") or msg.get("tool_calls"):
+ return [msg]
+
+ text_chunks: list[str] = []
+ tool_calls: list[dict] = []
+ tool_results: list[dict] = []
+ for part in parts:
+ if not isinstance(part, dict):
+ continue
+ part_type = part.get("type")
+ if part_type == "text":
+ content = part.get("content")
+ if isinstance(content, str) and content:
+ text_chunks.append(content)
+ elif part_type == "tool_call":
+ tool_calls.append(
+ {
+ "id": part.get("id"),
+ "function": {"name": part.get("name", ""), "arguments": part.get("arguments", "")},
+ }
+ )
+ elif part_type == "tool_call_response":
+ result = part.get("result", "")
+ if not isinstance(result, str):
+ result = json.dumps(result, default=str)
+ tool_results.append({"role": "tool", "content": result, "tool_call_id": part.get("id")})
+
+ primary = {key: value for key, value in msg.items() if key != "parts"}
+ if text_chunks:
+ primary["content"] = " ".join(text_chunks)
+ if tool_calls:
+ primary["tool_calls"] = tool_calls
+
+ # Keep an empty primary only when there are no follow-up tool results, so a
+ # message whose parts produce nothing still holds its `role:` conversation slot
+ # (matching how empty flat messages render) without adding a stray blank line
+ # in front of every tool result.
+ flattened: list[dict] = []
+ if text_chunks or tool_calls or not tool_results:
+ flattened.append(primary)
+ flattened.extend(tool_results)
+ return flattened
def _render_message(msg: dict) -> str | None:
diff --git a/posthog/temporal/ai_observability/test_message_utils.py b/posthog/temporal/ai_observability/test_message_utils.py
index e03c483887df..e942ef4ad7fa 100644
--- a/posthog/temporal/ai_observability/test_message_utils.py
+++ b/posthog/temporal/ai_observability/test_message_utils.py
@@ -327,6 +327,108 @@ class TestExtractTextFromMessages:
assert "user: Extract brands." in result
assert "Google Ads" in result
+ @pytest.mark.parametrize(
+ "message",
+ [
+ pytest.param({"parts": ["wheel", "tire"]}, id="string_parts"),
+ pytest.param({"parts": [{"name": "wheel", "qty": 2}]}, id="dict_parts"),
+ pytest.param({"parts": [{"type": "text", "content": "wheel"}]}, id="otel_shaped_parts"),
+ ],
+ )
+ def test_structured_output_with_parts_key_is_json_stringified(self, message):
+ # A structured-output schema can have its own `parts` array. Parts flattening
+ # is keyed on a string `role` (as the trace UI's otel.yaml recipe is) so these
+ # still reach the JSON-stringify fallback instead of rendering as empty.
+ result = extract_text_from_messages(message)
+ assert result == json.dumps(message, default=str)
+
+ def test_otel_parts_text_message(self):
+ messages = [{"role": "user", "parts": [{"type": "text", "content": "How long is the warranty?"}]}]
+ assert extract_text_from_messages(messages) == "user: How long is the warranty?"
+
+ def test_otel_parts_text_selected_by_type_not_position(self):
+ messages = [
+ {
+ "role": "assistant",
+ "parts": [
+ {"type": "reasoning", "content": "thinking it through"},
+ {"type": "reasoning", "content": "more thinking"},
+ {"type": "text", "content": "The warranty lasts three years."},
+ ],
+ }
+ ]
+ assert extract_text_from_messages(messages) == "assistant: The warranty lasts three years."
+
+ def test_otel_parts_multiple_text_parts_join(self):
+ messages = [
+ {"role": "user", "parts": [{"type": "text", "content": "First."}, {"type": "text", "content": "Second."}]}
+ ]
+ assert extract_text_from_messages(messages) == "user: First. Second."
+
+ def test_otel_parts_agentic_conversation_correlates_calls_and_results(self):
+ messages = [
+ {"role": "user", "parts": [{"type": "text", "content": "Weather in Montreal?"}]},
+ {
+ "role": "assistant",
+ "parts": [
+ {"type": "reasoning", "content": "need the weather tool"},
+ {
+ "type": "tool_call",
+ "id": "call_1",
+ "name": "get_weather",
+ "arguments": '{"location": "Montreal"}',
+ },
+ ],
+ },
+ {"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_1", "result": "-10C"}]},
+ {"role": "assistant", "parts": [{"type": "text", "content": "It is -10C."}]},
+ ]
+ result = extract_text_from_messages(messages)
+ assert "user: Weather in Montreal?" in result
+ assert '[tool_call call_1: get_weather({"location": "Montreal"})]' in result
+ assert "tool[call_1]: -10C" in result
+ assert "assistant: It is -10C." in result
+ assert "need the weather tool" not in result
+
+ def test_otel_parts_dict_tool_call_response_result_is_stringified(self):
+ messages = [
+ {"role": "tool", "parts": [{"type": "tool_call_response", "id": "call_1", "result": {"temperature": 25}}]}
+ ]
+ assert extract_text_from_messages(messages) == 'tool[call_1]: {"temperature": 25}'
+
+ def test_otel_parts_message_with_flat_content_is_untouched(self):
+ messages = [{"role": "user", "content": "flat wins", "parts": [{"type": "text", "content": "ignored"}]}]
+ assert extract_text_from_messages(messages) == "user: flat wins"
+
+ def test_otel_parts_only_reasoning_preserves_role_slot(self):
+ messages = [
+ {"role": "user", "parts": [{"type": "text", "content": "hi"}]},
+ {"role": "assistant", "parts": [{"type": "reasoning", "content": "hmm"}]},
+ ]
+ result = extract_text_from_messages(messages)
+ assert "user: hi" in result
+ assert "assistant:" in result
+ assert "hmm" not in result
+
+ @pytest.mark.parametrize(
+ "parts",
+ [
+ pytest.param(["not-a-dict"], id="non_dict_part"),
+ pytest.param([{"type": "text"}], id="text_part_without_content"),
+ pytest.param([{"type": "tool_call"}], id="tool_call_without_name"),
+ pytest.param([{"no_type": True}], id="part_without_type"),
+ pytest.param([{"type": "file", "data": "aGVsbG8="}], id="unknown_part_type"),
+ ],
+ )
+ def test_malformed_or_unknown_parts_do_not_crash(self, parts):
+ messages = [{"role": "user", "parts": parts}, {"role": "assistant", "content": "ok"}]
+ result = extract_text_from_messages(messages)
+ assert "assistant: ok" in result
+
+ def test_single_dict_parts_message(self):
+ message = {"role": "user", "parts": [{"type": "text", "content": "Hello"}]}
+ assert extract_text_from_messages(message) == "user: Hello"
+
def test_empty_dict_is_still_skipped(self):
# The JSON-stringify fallback must not regress the empty-dict skip path
# used by `test_completely_empty_message_is_skipped` — `{}` carries no