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.

feat(llma): give LLM judge full tool context for agentic evals (#57085)

Richard Solomoud182d16550e1
diff --git a/posthog/temporal/llm_analytics/message_utils.py b/posthog/temporal/llm_analytics/message_utils.py
index 8bc41d7e2062..489be05f27af 100644
--- a/posthog/temporal/llm_analytics/message_utils.py
+++ b/posthog/temporal/llm_analytics/message_utils.py
@@ -10,7 +10,8 @@ def extract_text_from_messages(messages: Union[str, list, dict, None]) -> str:
Handles common message formats from various LLM providers:
- OpenAI: [{"role": "user", "content": "text"}]
- - OpenAI tool calling: assistant messages with `tool_calls` (rendered alongside any content)
+ - 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": "..."}]}]
- Simple strings
@@ -29,31 +30,49 @@ def extract_text_from_messages(messages: Union[str, list, dict, None]) -> str:
formatted_parts = []
for msg in messages:
if isinstance(msg, dict):
- role = msg.get("role", "")
- content = msg.get("content", "")
-
- # Extract text from content and any OpenAI-style tool_calls
- text = _extract_content_text(content)
- tool_calls_text = _format_tool_calls(msg.get("tool_calls"))
-
- rendered = " ".join(part for part in (text, tool_calls_text) if part)
- if rendered:
- formatted_parts.append(f"{role}: {rendered}" if role else rendered)
- elif role:
- # Preserve the conversation slot when a message has a role
- # but no body (e.g. a tool that returned nothing).
- formatted_parts.append(f"{role}:")
+ rendered_msg = _render_message(msg)
+ if rendered_msg is not None:
+ formatted_parts.append(rendered_msg)
elif isinstance(msg, str):
formatted_parts.append(msg)
return "\n".join(formatted_parts)
- # Handle single dict message
- if isinstance(messages, dict):
- content = messages.get("content", "")
- text = _extract_content_text(content)
- tool_calls_text = _format_tool_calls(messages.get("tool_calls"))
- return " ".join(part for part in (text, tool_calls_text) if part)
+ # 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 ""
+
+
+def _render_message(msg: dict) -> str | None:
+ """Render a single message dict into a `role: body` line.
+
+ Returns None when the message has neither a role nor any body to render
+ (so the caller can skip it).
+ """
+ role = msg.get("role", "")
+ content = msg.get("content", "")
+ text = _extract_content_text(content)
+ tool_calls_text = _format_tool_calls(msg.get("tool_calls"))
+
+ rendered = " ".join(part for part in (text, tool_calls_text) if part)
+
+ # Surface tool_call_id on `role: "tool"` results so the judge can correlate
+ # a tool's output with the assistant call that produced it. Without this,
+ # multi-tool agentic flows lose the call/result pairing entirely.
+ role_label = role
+ if role == "tool":
+ tool_call_id = msg.get("tool_call_id")
+ if tool_call_id:
+ role_label = f"tool[{tool_call_id}]"
+
+ if rendered:
+ return f"{role_label}: {rendered}" if role_label else rendered
+ if role_label:
+ # Preserve the conversation slot when a message has a role
+ # but no body (e.g. a tool that returned nothing).
+ return f"{role_label}:"
+ return None
def _extract_content_text(content: Union[str, list, dict, None]) -> str:
@@ -103,6 +122,9 @@ def _format_tool_calls(tool_calls: Any) -> str:
assistant messages that *only* invoke a tool (content is null) disappear
from the formatted conversation entirely, leaving an LLM judge unable to
see what the agent actually did.
+
+ The call id is included so a downstream `role: "tool"` result rendered as
+ `tool[<id>]:` can be paired back to the call that produced it.
"""
if not isinstance(tool_calls, list):
return ""
@@ -119,5 +141,107 @@ def _format_tool_calls(tool_calls: Any) -> str:
args = fn.get("arguments", "")
if not isinstance(args, str):
args = json.dumps(args, default=str)
- parts.append(f"[tool_call: {name}({args})]")
+ call_id = tc.get("id")
+ prefix = f"tool_call {call_id}" if call_id else "tool_call"
+ parts.append(f"[{prefix}: {name}({args})]")
return " ".join(parts)
+
+
+def format_tool_definitions(tools: Any) -> str:
+ """Render the `$ai_tools` property (the tool catalog available to the agent)
+ into a compact, judge-readable summary.
+
+ For evaluating agentic behavior, the judge often needs to know not just
+ which tools were called but which tools were *callable*. A prompt like
+ "did the agent pick the right tool?" is unanswerable without that catalog.
+
+ Accepts the OpenAI-style `[{"type": "function", "function": {"name": ..., "description": ..., "parameters": {...}}}]`
+ shape, the Anthropic `[{"name": ..., "description": ..., "input_schema": {...}}]`
+ shape, and falls back to JSON-stringifying anything unrecognized rather than
+ silently dropping it.
+ """
+ if not tools:
+ return ""
+
+ if isinstance(tools, str):
+ return tools
+
+ if isinstance(tools, dict):
+ # A bare dict is either a single tool spec (carrying `function`,
+ # `name`, or Gemini's `functionDeclarations`) or a
+ # `{tool_name: tool_spec, ...}` mapping. Wrap a recognized spec in a
+ # one-element list; otherwise flatten the mapping into a list of
+ # specs, carrying the mapping key over as the tool's name when the
+ # value itself doesn't declare one.
+ if "function" in tools or "name" in tools or "functionDeclarations" in tools:
+ tools = [tools]
+ else:
+ tools = [
+ {**spec, "name": spec.get("name") or key} if isinstance(spec, dict) else spec
+ for key, spec in tools.items()
+ ]
+
+ if not isinstance(tools, list):
+ return json.dumps(tools, default=str)
+
+ parts: list[str] = []
+ for tool in tools:
+ if not isinstance(tool, dict):
+ parts.append(str(tool))
+ continue
+ # Gemini wraps multiple tools in `functionDeclarations`; expand them so
+ # each declared function gets its own line in the catalog.
+ declarations = tool.get("functionDeclarations")
+ tools_to_render = declarations if isinstance(declarations, list) else [tool]
+ for entry in tools_to_render:
+ if not isinstance(entry, dict):
+ parts.append(str(entry))
+ continue
+ rendered = _format_single_tool_definition(entry)
+ if rendered:
+ parts.append(rendered)
+ return "\n".join(parts)
+
+
+def _format_single_tool_definition(tool: dict) -> str:
+ # OpenAI nests the spec under `function`; Anthropic / Gemini-unwrapped lay
+ # it out at the top level. Read from the nested dict when present, falling
+ # back to the top-level tool dict for each individual field.
+ fn_raw = tool.get("function")
+ fn: dict = fn_raw if isinstance(fn_raw, dict) else {}
+ name = fn.get("name") or tool.get("name") or ""
+ description = fn.get("description") or tool.get("description") or ""
+ # Schema lives under different keys across providers: `parameters` for OpenAI
+ # function-calling and Gemini, `input_schema` for Anthropic, and `inputSchema`
+ # for the camelCase OpenAI Responses API variant.
+ parameters = fn.get("parameters") or tool.get("parameters") or tool.get("input_schema") or tool.get("inputSchema")
+
+ if not name:
+ # Unrecognized shape — stringify so the judge still sees something.
+ return json.dumps(tool, default=str)
+
+ line = f"- {name}"
+ if description:
+ line += f": {description}"
+ params_summary = _compact_params(parameters)
+ if params_summary:
+ line += f" ({params_summary})"
+ return line
+
+
+def _compact_params(parameters: Any) -> str:
+ """Summarise a JSON-schema-style `parameters` block as `arg1, arg2?, arg3`.
+
+ Tool catalogs can be large — dumping the full schema for every tool can
+ push the judge prompt over context limits. For evaluating "did the agent
+ call the right tool with the right info?", the parameter *names* (and
+ which are optional) are usually all the judge needs.
+ """
+ if not isinstance(parameters, dict):
+ return ""
+ properties = parameters.get("properties")
+ if not isinstance(properties, dict) or not properties:
+ return ""
+ required = parameters.get("required") or []
+ required_set = set(required) if isinstance(required, list) else set()
+ return ", ".join(key if key in required_set else f"{key}?" for key in properties)
diff --git a/posthog/temporal/llm_analytics/run_evaluation.py b/posthog/temporal/llm_analytics/run_evaluation.py
index c918386bb2f6..8235868ae28a 100644
--- a/posthog/temporal/llm_analytics/run_evaluation.py
+++ b/posthog/temporal/llm_analytics/run_evaluation.py
@@ -17,7 +17,7 @@ from posthog.api.capture import capture_internal
from posthog.models.team import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.base import PostHogWorkflow
-from posthog.temporal.llm_analytics.message_utils import extract_text_from_messages
+from posthog.temporal.llm_analytics.message_utils import extract_text_from_messages, format_tool_definitions
from posthog.temporal.llm_analytics.metrics import (
increment_emit_event_outcome,
increment_errors,
@@ -664,19 +664,26 @@ async def execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> LLMJudgeR
# Extract input/output based on event type
input_raw, output_raw = extract_event_io(event_type, properties)
+ tools_raw = extract_event_tools(properties)
# Extract readable text from message structures
input_data = extract_text_from_messages(input_raw)
output_data = extract_text_from_messages(output_raw)
+ tools_data = format_tool_definitions(tools_raw)
# Build judge prompt based on allows_na config
type_config = get_output_type_config(allows_na)
system_prompt = build_system_prompt(prompt, allows_na)
response_format = type_config.response_format
- user_prompt = f"""Input: {input_data}
-
-Output: {output_data}"""
+ # Insert a `Tools available:` section between Input and Output when the
+ # event captured the tool catalog. The judge needs to see what the agent
+ # *could* call to evaluate prompts like "did it pick the right tool?".
+ sections = [f"Input: {input_data}"]
+ if tools_data:
+ sections.append(f"Tools available:\n{tools_data}")
+ sections.append(f"Output: {output_data}")
+ user_prompt = "\n\n".join(sections)
# Get eval-specific config when using PostHog defaults (no provider_key)
config = get_eval_config(provider) if provider_key is None else None
@@ -832,6 +839,18 @@ def extract_event_io(event_type: str, properties: dict[str, Any]) -> tuple[Any,
return input_raw, output_raw
+def extract_event_tools(properties: dict[str, Any]) -> Any:
+ """Extract the tool catalog (`$ai_tools`) captured on the event, regardless
+ of event type.
+
+ `$ai_generation` is the canonical carrier today, but custom span/trace
+ events (e.g. an agent loop's `run_summary`) may also forward the catalog,
+ and the judge prompt benefits from it for any event shape. Presence of
+ `$ai_tools` drives whether the Tools section renders.
+ """
+ return properties.get("$ai_tools")
+
+
def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = False) -> dict[str, Any]:
"""Run compiled Hog bytecode against a single event.
diff --git a/posthog/temporal/llm_analytics/test_message_utils.py b/posthog/temporal/llm_analytics/test_message_utils.py
index ddf393f472e8..831d311437e7 100644
--- a/posthog/temporal/llm_analytics/test_message_utils.py
+++ b/posthog/temporal/llm_analytics/test_message_utils.py
@@ -1,8 +1,10 @@
"""Tests for message extraction utilities."""
+import json
+
import pytest
-from posthog.temporal.llm_analytics.message_utils import extract_text_from_messages
+from posthog.temporal.llm_analytics.message_utils import extract_text_from_messages, format_tool_definitions
class TestExtractTextFromMessages:
@@ -81,10 +83,17 @@ class TestExtractTextFromMessages:
assert "assistant:" in result
def test_single_dict_message(self):
+ # Single-dict input renders symmetrically with the list path so the
+ # role prefix and tool_call_id correlation reach the judge regardless
+ # of whether the caller wraps the message in a list.
message = {"role": "user", "content": "Hello"}
result = extract_text_from_messages(message)
- assert result == "Hello"
- assert result != ""
+ assert result == "user: Hello"
+
+ def test_single_dict_tool_result_surfaces_call_id(self):
+ message = {"role": "tool", "tool_call_id": "call_42", "content": "done"}
+ result = extract_text_from_messages(message)
+ assert result == "tool[call_42]: done"
@pytest.mark.parametrize(
"messages,expected_substrings",
@@ -193,9 +202,38 @@ class TestExtractTextFromMessages:
assert "user: Update placement status." in result
assert "update_placement_status" in result
assert '{"status": "approved"}' in result
- assert "tool: Status updated." in result
+ # The tool result should be paired back to the call that produced it
+ # via tool_call_id, so the judge can correlate multi-step flows.
+ assert "tool[call_1]: Status updated." in result
+ assert "tool_call call_1" in result
assert "assistant: Done." in result
+ def test_tool_call_id_correlation_across_parallel_calls(self):
+ # When the model issues two parallel tool calls, the rendered output
+ # should let the judge pair each result back to its originating call.
+ messages = [
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "call_a", "type": "function", "function": {"name": "lookup_user", "arguments": "{}"}},
+ {"id": "call_b", "type": "function", "function": {"name": "lookup_org", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_b", "content": "org found"},
+ {"role": "tool", "tool_call_id": "call_a", "content": "user found"},
+ ]
+ result = extract_text_from_messages(messages)
+ assert "tool_call call_a: lookup_user" in result
+ assert "tool_call call_b: lookup_org" in result
+ assert "tool[call_a]: user found" in result
+ assert "tool[call_b]: org found" in result
+
+ def test_tool_result_without_id_falls_back_to_role_only(self):
+ messages = [{"role": "tool", "content": "raw output"}]
+ result = extract_text_from_messages(messages)
+ assert result == "tool: raw output"
+
@pytest.mark.parametrize(
"tool_calls",
[
@@ -227,7 +265,7 @@ class TestExtractTextFromMessages:
]
result = extract_text_from_messages(messages)
assert "user: did anything happen?" in result
- assert "tool:" in result
+ assert "tool[1]:" in result
assert "assistant: yes" in result
def test_completely_empty_message_is_skipped(self):
@@ -258,3 +296,226 @@ class TestExtractTextFromMessages:
}
result = extract_text_from_messages(message)
assert "send_email" in result
+
+
+class TestFormatToolDefinitions:
+ @pytest.mark.parametrize(
+ "tools",
+ [
+ pytest.param(None, id="none"),
+ pytest.param("", id="empty_string"),
+ pytest.param([], id="empty_list"),
+ ],
+ )
+ def test_empty_inputs_render_as_empty(self, tools):
+ assert format_tool_definitions(tools) == ""
+
+ def test_string_passthrough(self):
+ assert format_tool_definitions("custom-stringified-tools") == "custom-stringified-tools"
+
+ def test_openai_function_shape(self):
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "send_email",
+ "description": "Send an email to a recipient.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "to": {"type": "string"},
+ "body": {"type": "string"},
+ "subject": {"type": "string"},
+ },
+ "required": ["to", "body"],
+ },
+ },
+ }
+ ]
+ result = format_tool_definitions(tools)
+ assert "- send_email" in result
+ assert "Send an email to a recipient." in result
+ # Parameter names are surfaced compactly with `?` for optional ones,
+ # rather than dumping the full JSON schema. Specifically, the per-property
+ # type info should not leak into the prompt.
+ assert "(to, body, subject?)" in result
+ assert '"type": "string"' not in result
+ assert '"required"' not in result
+
+ def test_anthropic_input_schema_shape(self):
+ tools = [
+ {
+ "name": "lookup_user",
+ "description": "Look up a user by id.",
+ "input_schema": {
+ "type": "object",
+ "properties": {"id": {"type": "string"}},
+ "required": ["id"],
+ },
+ }
+ ]
+ result = format_tool_definitions(tools)
+ assert "- lookup_user" in result
+ assert "Look up a user by id." in result
+ assert "(id)" in result
+
+ def test_multiple_tools_each_on_own_line(self):
+ tools = [
+ {"type": "function", "function": {"name": "tool_a", "description": "A"}},
+ {"type": "function", "function": {"name": "tool_b", "description": "B"}},
+ ]
+ result = format_tool_definitions(tools)
+ lines = result.split("\n")
+ assert len(lines) == 2
+ assert lines[0].startswith("- tool_a")
+ assert lines[1].startswith("- tool_b")
+
+ def test_single_dict_is_treated_as_one_tool(self):
+ tools = {"type": "function", "function": {"name": "solo", "description": "Only one"}}
+ result = format_tool_definitions(tools)
+ assert result.startswith("- solo")
+ assert "Only one" in result
+
+ def test_unrecognized_shape_is_stringified_not_dropped(self):
+ tools = [{"weird_key": "weird_value"}]
+ result = format_tool_definitions(tools)
+ assert "weird_key" in result
+ assert "weird_value" in result
+
+ def test_name_only_renders_without_description_or_params(self):
+ tools = [{"type": "function", "function": {"name": "noop"}}]
+ assert format_tool_definitions(tools) == "- noop"
+
+ def test_dict_of_tools_is_flattened(self):
+ # A `{tool_name: tool_spec}` mapping should render each value as its
+ # own tool rather than being treated as a single nameless tool.
+ tools = {
+ "lov-view": {"name": "lov-view", "description": "View something"},
+ "supabase-migration": {"name": "supabase-migration", "description": "Run a migration"},
+ }
+ result = format_tool_definitions(tools)
+ lines = result.split("\n")
+ assert len(lines) == 2
+ assert any(line.startswith("- lov-view") for line in lines)
+ assert any(line.startswith("- supabase-migration") for line in lines)
+
+ def test_gemini_function_declarations_shape(self):
+ tools = [
+ {
+ "functionDeclarations": [
+ {
+ "name": "send_email",
+ "description": "Send an email.",
+ "parameters": {"type": "object", "properties": {"to": {"type": "string"}}},
+ },
+ {
+ "name": "lookup_user",
+ "description": "Look up a user.",
+ "parameters": {"type": "object", "properties": {"id": {"type": "string"}}},
+ },
+ ]
+ }
+ ]
+ result = format_tool_definitions(tools)
+ lines = result.split("\n")
+ assert len(lines) == 2
+ assert lines[0].startswith("- send_email")
+ assert lines[1].startswith("- lookup_user")
+ assert "(to?)" in result
+ assert "(id?)" in result
+
+ def test_gemini_function_declarations_at_top_level(self):
+ # Some captures send Gemini's tool catalog as a bare dict rather than
+ # a list-wrapped one — `functionDeclarations` should be recognized as
+ # a tool spec carrier in either shape.
+ tools = {
+ "functionDeclarations": [
+ {"name": "send_email", "description": "Send an email."},
+ {"name": "lookup_user", "description": "Look up a user."},
+ ]
+ }
+ result = format_tool_definitions(tools)
+ lines = result.split("\n")
+ assert len(lines) == 2
+ assert lines[0].startswith("- send_email")
+ assert lines[1].startswith("- lookup_user")
+
+ def test_openai_camel_case_input_schema_shape(self):
+ tools = [
+ {
+ "name": "lookup_user",
+ "description": "Look up a user by id.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"id": {"type": "string"}},
+ "required": ["id"],
+ },
+ }
+ ]
+ result = format_tool_definitions(tools)
+ assert "- lookup_user" in result
+ assert "Look up a user by id." in result
+ assert "(id)" in result
+
+ def test_dict_of_tools_with_name_in_key_only(self):
+ # When tools come as `{tool_name: {description, inputSchema}}` with no
+ # explicit `name` key on the value, fall back to using the mapping key.
+ tools = {
+ "search_docs": {
+ "description": "Search docs",
+ "inputSchema": {
+ "type": "object",
+ "properties": {"query": {"type": "string"}},
+ "required": ["query"],
+ },
+ }
+ }
+ result = format_tool_definitions(tools)
+ assert result.startswith("- search_docs: Search docs")
+ assert "(query)" in result
+
+ def test_compact_params_omits_full_schema_payload(self):
+ # The full JSON schema (types, descriptions per property, etc.) must
+ # not leak into the prompt — we only want parameter names, since
+ # dumping a full schema for every tool can blow past the judge's context.
+ # Assert against JSON delimiters that can only come from a schema dump
+ # (rather than free-form words that could legitimately appear in a
+ # tool's name or description).
+ tools = [
+ {
+ "name": "do_thing",
+ "input_schema": {
+ "type": "object",
+ "properties": {
+ "a": {"type": "string", "description": "A long description that should not appear"},
+ "b": {"type": "integer", "minimum": 0, "maximum": 100},
+ },
+ "required": ["a"],
+ },
+ }
+ ]
+ result = format_tool_definitions(tools)
+ assert "(a, b?)" in result
+ assert '"type"' not in result
+ assert '"minimum"' not in result
+ assert '"description"' not in result
+
+ def test_empty_parameters_dict_is_skipped(self):
+ # An explicitly-empty schema (`{}`) is treated as "no params" and
+ # the `(...)` parameter suffix is omitted entirely.
+ tools = [{"type": "function", "function": {"name": "noop", "description": "Does nothing", "parameters": {}}}]
+ assert format_tool_definitions(tools) == "- noop: Does nothing"
+
+ @pytest.mark.parametrize(
+ "tools",
+ [
+ pytest.param(42, id="int"),
+ pytest.param(3.14, id="float"),
+ pytest.param(True, id="bool"),
+ ],
+ )
+ def test_non_list_non_dict_falls_through_to_json(self, tools):
+ # Anything we can't iterate as a list of tool specs gets stringified
+ # rather than silently dropped — the judge can still see something.
+ result = format_tool_definitions(tools)
+ assert result == json.dumps(tools, default=str)
diff --git a/posthog/temporal/llm_analytics/test_run_evaluation.py b/posthog/temporal/llm_analytics/test_run_evaluation.py
index 93fd8a0b7f3d..60d87b5e07a9 100644
--- a/posthog/temporal/llm_analytics/test_run_evaluation.py
+++ b/posthog/temporal/llm_analytics/test_run_evaluation.py
@@ -31,6 +31,7 @@ from .run_evaluation import (
emit_evaluation_event_activity,
execute_hog_eval_activity,
execute_llm_judge_activity,
+ extract_event_tools,
fetch_evaluation_activity,
increment_trial_eval_count_activity,
run_hog_eval,
@@ -1260,3 +1261,127 @@ class TestSendEvaluationDisabledEmailActivity:
)
mock_email_class.assert_not_called()
+
+
+class TestExtractEventTools:
+ def test_returns_tools_when_property_present(self):
+ properties = {
+ "$ai_tools": [{"type": "function", "function": {"name": "send_email", "description": "Send email"}}],
+ }
+ tools = extract_event_tools(properties)
+ assert tools is not None
+ assert isinstance(tools, list)
+ assert tools[0]["function"]["name"] == "send_email"
+
+ def test_returns_none_when_property_missing(self):
+ assert extract_event_tools({}) is None
+
+
+class TestJudgePromptAssembly:
+ """Asserts on the actual user prompt sent to the judge — guards against
+ regressions in section ordering, tool catalog inclusion, and tool_call_id
+ correlation that the unit tests for the helpers can't catch alone."""
+
+ @pytest.mark.asyncio
+ @pytest.mark.django_db(transaction=True)
+ async def test_prompt_contains_input_tools_and_output_sections_in_order(self, setup_data):
+ evaluation_obj = setup_data["evaluation"]
+ team = setup_data["team"]
+ evaluation = {
+ "id": str(evaluation_obj.id),
+ "name": "Test Evaluation",
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Did the agent call the right tool?"},
+ "output_type": "boolean",
+ "output_config": {},
+ "team_id": team.id,
+ }
+ event_data = create_mock_event_data(
+ team.id,
+ properties={
+ "$ai_input": [
+ {"role": "user", "content": "Send the welcome email."},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "send_email", "arguments": '{"to": "[email protected]"}'},
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_1", "content": "ok"},
+ ],
+ "$ai_output_choices": [{"role": "assistant", "content": "Done."}],
+ "$ai_tools": [
+ {"type": "function", "function": {"name": "send_email", "description": "Send an email."}},
+ {"type": "function", "function": {"name": "lookup_user", "description": "Look up a user."}},
+ ],
+ },
+ )
+
+ with patch("posthog.temporal.llm_analytics.run_evaluation.Client") as mock_client_class:
+ mock_client = MagicMock()
+ mock_client_class.return_value = mock_client
+ mock_response = MagicMock()
+ mock_response.parsed = BooleanEvalResult(verdict=True, reasoning="ok")
+ mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)
+ mock_client.complete.return_value = mock_response
+
+ await execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
+
+ completion_request = mock_client.complete.call_args[0][0]
+ user_prompt = completion_request.messages[0]["content"]
+
+ # Section ordering: Input first, then Tools available, then Output.
+ input_idx = user_prompt.index("Input:")
+ tools_idx = user_prompt.index("Tools available:")
+ output_idx = user_prompt.index("Output:")
+ assert input_idx < tools_idx < output_idx
+
+ # Tool calls and their results are paired via tool_call_id.
+ assert "tool_call call_1: send_email" in user_prompt
+ assert "tool[call_1]: ok" in user_prompt
+
+ # Tool catalog is rendered compactly, one entry per line.
+ assert "- send_email: Send an email." in user_prompt
+ assert "- lookup_user: Look up a user." in user_prompt
+
+ @pytest.mark.asyncio
+ @pytest.mark.django_db(transaction=True)
+ async def test_prompt_omits_tools_section_when_catalog_absent(self, setup_data):
+ evaluation_obj = setup_data["evaluation"]
+ team = setup_data["team"]
+ evaluation = {
+ "id": str(evaluation_obj.id),
+ "name": "Test Evaluation",
+ "evaluation_type": "llm_judge",
+ "evaluation_config": {"prompt": "Is this correct?"},
+ "output_type": "boolean",
+ "output_config": {},
+ "team_id": team.id,
+ }
+ event_data = create_mock_event_data(
+ team.id,
+ properties={
+ "$ai_input": [{"role": "user", "content": "What is 2+2?"}],
+ "$ai_output_choices": [{"role": "assistant", "content": "4"}],
+ },
+ )
+
+ with patch("posthog.temporal.llm_analytics.run_evaluation.Client") as mock_client_class:
+ mock_client = MagicMock()
+ mock_client_class.return_value = mock_client
+ mock_response = MagicMock()
+ mock_response.parsed = BooleanEvalResult(verdict=True, reasoning="ok")
+ mock_response.usage = MagicMock(input_tokens=10, output_tokens=5, total_tokens=15)
+ mock_client.complete.return_value = mock_response
+
+ await execute_llm_judge_activity(ExecuteLLMJudgeInputs(evaluation=evaluation, event_data=event_data))
+
+ user_prompt = mock_client.complete.call_args[0][0].messages[0]["content"]
+ assert "Tools available:" not in user_prompt
+ assert "Input:" in user_prompt
+ assert "Output:" in user_prompt