: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import uuid
from typing import Any, Literal, Self, cast
import structlog
from langchain_core.runnables import RunnableConfig
from pydantic import BaseModel, Field, create_model
from posthog.schema import (
AgentMode,
ArtifactMessage,
ArtifactSource,
AssistantEventType,
AssistantGenerationStatusEvent,
AssistantMessage,
AssistantTool,
AssistantUpdateEvent,
HumanMessage,
)
from posthog.models import Team, User
from ee.hogai.artifacts.utils import unwrap_notebook_artifact_content, unwrap_visualization_artifact_content
from ee.hogai.context.context import AssistantContextManager
from ee.hogai.stream.redis_stream import get_subagent_stream_key
from ee.hogai.tool import MaxTool, ToolMessagesArtifact
from ee.hogai.utils.helpers import build_insight_url
from ee.hogai.utils.prompt import format_prompt_string
from ee.hogai.utils.types.base import AssistantState, NodePath
logger = structlog.get_logger(__name__)
TASK_TOOL_PROMPT = """
Use this tool to spin up a dedicated agent that can independently tackle a complex, multi-step task.
Use this tool only when you need to run multiple tasks in parallel, calling this tool once per task.
# Modes:
The agent can be started in a specific mode, which will determine the tools and capabilities available to it.
The agent can then switch between these modes independently, depending on the task at hand.
Available modes:
{{{available_modes}}}
When using the `task` tool, you must specify a `agent_mode` parameter to select what initial mode to use.
# When not to use the `task` tool
- If you already know the exact event or entity to search for, use the read_data, read_taxonomy or search tool instead of `task`.
- If your current to-do doesn't require parallelization, complete the job yourself without using this tool.
# Usage guidelines
- *Parallelize when possible*: when you have multiple independent tasks, start several agents at once in a single message by issuing multiple Agent tool calls in parallel to improve latency and throughput.
- *You see the report, not the raw result*: when an agent finishes, it sends back exactly one message containing its findings. This output is visible only to you (the calling system), not directly to the end user. You are responsible for returning a concise, user-facing summary of the agent’s result.
- *Each task run is stateless and one-shot*: every invocation is independent, you cannot have a back-and-forth with the agent, and it will not be able to ask you clarifying questions. Your prompt must therefore contain a rich, detailed task description and explicitly specify what information the agent should include in its single final response.
- *Treat the agent’s output as generally reliable*: in most cases you can trust its conclusions, though you may still apply light sanity checks where appropriate.
- *Be explicit about the kind of work*: clearly indicate what you expect out of the agent; the agent does not directly know the user’s intent unless you spell it out.
# Examples
<example>
user: "I want to understand what user [email protected] has been doing in our product"
assistant: I'll help you understand this user's activity. Let me first search for this user.
assistant: Uses the read_taxonomy tool to find the "email" property, then again to find that "[email protected]" is a valid property value.
assistant: Uses switches to SQL mode to execute a SQL query to find the user's properties from the `persons` table.
assistant: Found the user with distinct_id "user_123". Now I'll gather comprehensive information about their activity.
<commentary>
This requires multiple types of analysis that can run in parallel: session summaries, activity patterns, and deeper SQL analysis.
</commentary>
assistant: Uses the `task` tool three times in parallel:
- Task 1 (session_replay mode): "Summarize the recent sessions for user with distinct_id 'user_123'. Include session duration, pages visited, and key actions taken."
- Task 2 (product_analytics mode): "Create a trends insight showing the activity frequency for user 'user_123' over the last 30 days, broken down by event type."
- Task 3 (sql mode): "Write a SQL query to find the user's most common user journey paths and any errors or friction points they encountered."
</example>
<example>
user: "How many users are active in GMT+2"
assistant: First let me use the read_taxonomy tool to check for a timezone event property.
assistant: Good, I've found a $geoip_time_zone property in the user's taxonomy.
<commentary>
Since the assistant can create the insight autonomously, there is no need to use the `task` tool.
</commentary>
assistant: Uses the create_insight tool directly.
</example>
# Artifacts
If you want to list artifacts generated by tasks, use the list_data tool with the "artifacts" kind, after using this tool.
""".strip()
TASK_RESULT_PROMPT = """
The agent has completed the task with the following result:
```
{{{result}}}
```
{{{artifacts_prompt}}}
"""
TASK_ARTIFACTS_PROMPT = """
The following artifacts have been generated:
{{{artifacts_list}}}
{{#has_transient_artifacts}}
Any `Artifact ID` above is scoped to this conversation, not an insight short ID, so an `/insights/...` link built from it would 404. If the user wants a saved insight, tell them to open the chart as a new insight from the icon below it and save it from there. Any `Insight ID` above is a saved insight, and its insight URL is a real link you can give the user.
{{/has_transient_artifacts}}
"""
class TaskToolArgs(BaseModel):
title: str = Field(description="A short title for the task")
task: str = Field(
description="A clear, detailed description of the task for the subagent to complete. Include all relevant context and desired outcome."
)
agent_mode: AgentMode = Field(description="The name of the starting mode to use.")
class TaskTool(MaxTool):
name: Literal[AssistantTool.TASK] = AssistantTool.TASK
description: str = TASK_TOOL_PROMPT
args_schema: type[BaseModel] = TaskToolArgs
async def _arun_impl(self, title: str, task: str, agent_mode: AgentMode) -> tuple[str, ToolMessagesArtifact | None]:
# Deferred: SubagentExecutor (and the chat_agent workflow) pull in ee.hogai.core.executor ->
# posthog.temporal.ai -> chat_agent -> toolkit, which reaches back into ee.hogai.tools. At module
# level that cycle only resolved by import-order luck; the lazy API router removed that luck (the
# agent core is no longer pre-imported at django.setup), so the first MCP-tools request in a fresh
# worker hit the half-initialized cycle. Importing both lazily here breaks it.
from posthog.temporal.ai.chat_agent import ChatAgentWorkflow, ChatAgentWorkflowInputs # noqa: PLC0415
from ee.hogai.tools.subagent_executor import SubagentExecutor # noqa: PLC0415
thread_id = self._get_thread_id(self._config)
if not thread_id:
# make mypy happy
raise ValueError("Thread id can't be empty")
conversation = await self._aget_conversation(thread_id)
if not conversation:
raise ValueError("Conversation not found")
# Generate a span ID for this subagent invocation so all its events are nested under this span
subagent_span_id = str(uuid.uuid4())
is_agent_billable = (self._config.get("configurable") or {}).get("is_agent_billable", True)
inputs = ChatAgentWorkflowInputs(
team_id=self._team.id,
user_id=self._user.id,
conversation_id=conversation.id,
stream_key=get_subagent_stream_key(conversation.id, f"{self.tool_call_id}-{subagent_span_id}"),
message=HumanMessage(content=task).model_dump(),
trace_id=self._get_trace_id(self._config),
parent_span_id=subagent_span_id,
session_id=self._get_session_id(self._config),
billing_context=self._context_manager.get_billing_context(),
agent_mode=agent_mode,
use_checkpointer=False,
is_agent_billable=is_agent_billable,
)
executor = SubagentExecutor(
conversation=conversation,
tool_call_id=self.tool_call_id,
execution_id=subagent_span_id,
)
final_content = ""
artifact_messages: list[ArtifactMessage] = []
try:
async for event_type, message in executor.astream(ChatAgentWorkflow, inputs):
if event_type == AssistantEventType.MESSAGE:
# Only parse completed messages
if isinstance(message, AssistantGenerationStatusEvent) or not getattr(message, "id", None):
continue
if isinstance(message, AssistantMessage):
final_content = message.content
if message.tool_calls:
for tool_call in message.tool_calls:
self.dispatcher.update(content=tool_call)
if isinstance(message, ArtifactMessage):
artifact_messages.append(message)
elif event_type == AssistantEventType.UPDATE:
self.dispatcher.update(cast(AssistantUpdateEvent, message).content)
except Exception as e:
logger.exception(f"[SUBAGENT:{self.tool_call_id}] Error running subagent", error=e)
return f"Error running subagent: {e}", None
if not final_content:
return "Something went wrong, no answer received from subagent", None
artifacts_prompt = ""
if len(artifact_messages) > 0:
artifacts_list_prompt = []
has_transient_artifacts = False
for message in artifact_messages:
viz_content = unwrap_visualization_artifact_content(message)
if viz_content:
if message.source == ArtifactSource.INSIGHT:
artifacts_list_prompt.append(
f"- Insight ID: {message.artifact_id}\nName: {viz_content.name}\nDescription: {viz_content.description}\nQuery: {viz_content.query}\nInsight URL: {build_insight_url(message.artifact_id)}"
)
else:
has_transient_artifacts = True
artifacts_list_prompt.append(
f"- Artifact ID: {message.artifact_id}\nName: {viz_content.name}\nDescription: {viz_content.description}\nQuery: {viz_content.query}"
)
continue
notebook_content = unwrap_notebook_artifact_content(message)
if notebook_content:
artifacts_list_prompt.append(
f"- Notebook ID: {message.artifact_id}\nTitle: {notebook_content.title}"
)
artifacts_prompt = format_prompt_string(
TASK_ARTIFACTS_PROMPT,
artifacts_list="\n\n".join(artifacts_list_prompt),
has_transient_artifacts=has_transient_artifacts,
)
result_prompt = format_prompt_string(
TASK_RESULT_PROMPT, result=final_content, artifacts_prompt=artifacts_prompt
)
return result_prompt, None
@classmethod
async def create_tool_class(
cls,
*,
team: Team,
user: User,
node_path: tuple[NodePath, ...] | None = None,
state: AssistantState | None = None,
config: RunnableConfig | None = None,
context_manager: AssistantContextManager | None = None,
) -> Self:
from ee.hogai.chat_agent.mode_manager import DEFAULT_CHAT_AGENT_MODE_REGISTRY
modes_list = list(DEFAULT_CHAT_AGENT_MODE_REGISTRY.keys())
# Fix the mode types to the chat agent modes, as there might be other unsupported modes in the AgentMode enum
SubAgentArgsWithModes = create_model(
"SubAgentArgsWithModes",
__base__=TaskToolArgs,
agent_mode=(
cast(Any, Literal[*modes_list]),
Field(description=TaskToolArgs.model_fields["agent_mode"].description),
),
)
modes_prompt = ""
for mode_definition in DEFAULT_CHAT_AGENT_MODE_REGISTRY.values():
modes_prompt += f"- {mode_definition.mode.value}: {mode_definition.mode_description}\n"
description = format_prompt_string(TASK_TOOL_PROMPT, available_modes=modes_prompt)
return cls(
team=team,
user=user,
state=state,
config=config,
node_path=node_path,
args_schema=SubAgentArgsWithModes,
description=description,
context_manager=context_manager,
)