: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
feat(customer-analytics): read and write account relationships from posthog ai tools (#69001)
Arthur Moreira de Deus0b03e4fe4bf9
diff --git a/ee/hogai/context/account/context.py b/ee/hogai/context/account/context.pyindex b3f4ba486260..a9d9f01c03d5 100644--- a/ee/hogai/context/account/context.py+++ b/ee/hogai/context/account/context.py@@ -25,7 +25,6 @@ from .prompts import (ACCOUNT_TAGS_TEMPLATE,)-_ROLE_LABELS = [("CSM", "csm"), ("Account executive", "account_executive"), ("Account owner", "account_owner")]_EXTERNAL_ID_LABELS = [("Stripe customer id", "stripe_customer_id"),("HubSpot deal id", "hubspot_deal_id"),@@ -87,11 +86,10 @@ class AccountContext:return await self.format_account(account)def _roles_section(self, account: AccountContextData) -> str:- properties = account.propertieslines = [- f"- {label}: {assignment.email} (user {assignment.id})"- for label, field in _ROLE_LABELS- if (assignment := getattr(properties, field)) is not None+ f"- {relationship.definition.name}: {relationship.user.email} (user {relationship.user.id})"+ for relationship in account.relationships+ if relationship.user is not None]if not lines:return ""diff --git a/ee/hogai/context/account/prompts.py b/ee/hogai/context/account/prompts.pyindex c7ae8fdba2d8..cbbc0634a9e5 100644--- a/ee/hogai/context/account/prompts.py+++ b/ee/hogai/context/account/prompts.py@@ -13,7 +13,7 @@ ACCOUNT_CONTEXT_TEMPLATE = """""".strip()ACCOUNT_ROLES_TEMPLATE = """-### Roles+### Relationships{roles_list}""".strip()diff --git a/ee/hogai/context/account/test/test_context.py b/ee/hogai/context/account/test/test_context.pyindex f4ea38917b10..da2d05baa938 100644--- a/ee/hogai/context/account/test/test_context.py+++ b/ee/hogai/context/account/test/test_context.py@@ -14,9 +14,11 @@ from posthog.api.tagged_item import set_tags_on_objectfrom products.notebooks.backend.models import Notebook, ResourceNotebookif TYPE_CHECKING:- from products.customer_analytics.backend.models import Account+ from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinitionelse:Account = apps.get_model("customer_analytics", "Account")+ AccountRelationship = apps.get_model("customer_analytics", "AccountRelationship")+ AccountRelationshipDefinition = apps.get_model("customer_analytics", "AccountRelationshipDefinition")from ee.hogai.context.account.context import AccountContext@@ -81,16 +83,24 @@ class TestAccountContext(NonAtomicBaseTest):assert "**External ID:** Not set" in result- async def test_format_includes_roles(self):- account = await self._create_account(- name="Acme Corp",- _properties={"csm": {"id": 42, "email": "[email protected]"}},+ async def test_format_includes_relationships(self):+ account = await self._create_account(name="Acme Corp")+ definition = await AccountRelationshipDefinition.objects.unscoped().acreate(team=self.team, name="CSM")+ await AccountRelationship.objects.unscoped().acreate(+ team=self.team, account=account, definition=definition, user=self.user)result = await AccountContext(team=self.team, user=self.user, account_id=str(account.id)).execute_and_format()- assert "### Roles" in result- assert "CSM: [email protected] (user 42)" in result+ assert "### Relationships" in result+ assert f"CSM: {self.user.email} (user {self.user.id})" in result++ async def test_format_omits_relationships_section_without_assignments(self):+ account = await self._create_account(name="Acme Corp")++ result = await AccountContext(team=self.team, user=self.user, account_id=str(account.id)).execute_and_format()++ assert "### Relationships" not in resultasync def test_format_includes_external_system_ids(self):account = await self._create_account(name="Acme Corp", _properties={"stripe_customer_id": "cus_123"})diff --git a/ee/hogai/core/agent_modes/presets/customer_analytics.py b/ee/hogai/core/agent_modes/presets/customer_analytics.pyindex e65b69317941..d6a88c35701c 100644--- a/ee/hogai/core/agent_modes/presets/customer_analytics.py+++ b/ee/hogai/core/agent_modes/presets/customer_analytics.py@@ -48,13 +48,13 @@ User: Make Jane the CSM for Acme CorpAssistant: Let me find the Acme Corp account first.*Uses list_data with the account kind to find the account's id*Assistant: Found it. I'll assign Jane as the CSM.-*Uses the upsert_account tool with action=update, account_id=<uuid>, properties={csm: {id, email}}*+*Uses the upsert_account tool with action=update, account_id=<uuid>, relationships={CSM: <user id>}*""".strip()POSITIVE_EXAMPLE_ASSIGN_ROLE_REASONING = """1. The account must be looked up by its id before it can be updated.2. Assigning a single role is a one-step task, so no todo list is needed.-3. The CSM assignment requires the assignee's user id and email.+3. The CSM assignment requires the assignee's user id.""".strip()POSITIVE_EXAMPLE_ACCOUNT_USAGE = """diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex bf7f067e4f4a..24a79c5b71cf 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -146,6 +146,7 @@ def get_account_context_data(properties=_to_account_properties(account.properties),tags=_account_tags(account),notes=_account_notes(account),+ relationships=list_account_relationships(team_id=team_id, account_id=account.id),)diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex 7988efd8ff46..2f15f52529cf 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -123,6 +123,7 @@ class AccountContextData:properties: AccountPropertiestags: list[str] = field(default_factory=list)notes: list[AccountNote] = field(default_factory=list)+ relationships: list[AccountRelationship] = field(default_factory=list)@dataclass(frozen=True)diff --git a/products/customer_analytics/backend/max_tools.py b/products/customer_analytics/backend/max_tools.pyindex 3974fa9b8289..12a98451aed7 100644--- a/products/customer_analytics/backend/max_tools.py+++ b/products/customer_analytics/backend/max_tools.py@@ -10,12 +10,12 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom posthog.api.tagged_item import set_tags_on_objectfrom posthog.exceptions_capture import capture_exception+from posthog.models import OrganizationMembershipfrom posthog.rbac.user_access_control import AccessControlLevelfrom posthog.scopes import APIScopeObject-from products.customer_analytics.backend.constants import ACCOUNT_ASSIGNMENT_ROLE_FIELDSfrom products.customer_analytics.backend.logic import relationships as relationships_logic-from products.customer_analytics.backend.models import Account+from products.customer_analytics.backend.models import Account, AccountRelationshipDefinitionfrom products.notebooks.backend.models import Notebook, ResourceNotebookfrom ee.hogai.tool import MaxTool@@ -108,34 +108,33 @@ UPSERT_ACCOUNT_TOOL_DESCRIPTION = dedent("""Resolve `account_id` (a UUID) first via `read_data`/`list_data` with the account kind.# Properties- `properties` carries typed fields. Assignment fields (csm, account_executive, account_owner) take- an object `{id, email}` (the PostHog user id and email) or null to clear. External-system ids- (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id) are strings.+ `properties` carries typed fields. External-system ids (stripe_customer_id, hubspot_deal_id,+ billing_id, sfdc_id, zendesk_id) are strings.On **update**, only the property keys you pass are changed (others are preserved); pass a key asnull to clear it.+ # Relationships+ Pass `relationships` to assign users to the account's relationships (CSM, Account executive, or+ any definition the team has created), keyed by definition name: the value is the PostHog user id,+ or null to end the current assignment. Only the named definitions are changed.+# TagsPass `tags` to set the account's tags. On update this REPLACES the existing tag set.# Examples- "Add an account for Acme Corp whose PostHog group key is acme-123": action=create, name="Acme Corp", external_id="acme-123"- - "Assign Jane (user 42, [email protected]) as CSM for that account": action=update, account_id=<uuid>,- properties={csm: {id: 42, email: "[email protected]"}}+ - "Assign Jane (user 42) as CSM for that account": action=update, account_id=<uuid>,+ relationships={CSM: 42}- "Tag it enterprise and priority": action=update, account_id=<uuid>, tags=["enterprise", "priority"]""").strip()-class AccountAssignment(BaseModel):- model_config = ConfigDict(extra="forbid")- id: int = Field(description="PostHog user id of the assignee")- email: str = Field(description="Email of the assignee")+class RelationshipAssignmentError(Exception):+ passclass AccountPropertiesInput(BaseModel):model_config = ConfigDict(extra="forbid")- csm: AccountAssignment | None = Field(default=None, description="Customer success manager assignment")- account_executive: AccountAssignment | None = Field(default=None, description="Account executive assignment")- account_owner: AccountAssignment | None = Field(default=None, description="Account owner assignment")stripe_customer_id: str | None = Field(default=None, description="Stripe customer id")hubspot_deal_id: str | None = Field(default=None, description="HubSpot deal id")billing_id: str | None = Field(default=None, description="Billing system id")@@ -157,6 +156,13 @@ class CreateAccountAction(BaseModel):)tags: list[str] | None = Field(default=None, description="Tag names to attach to the account")properties: AccountPropertiesInput | None = Field(default=None, description="Typed account properties")+ relationships: dict[str, int | None] | None = Field(+ default=None,+ description=(+ "Relationship assignments keyed by definition name (e.g. 'CSM'); each value is the "+ "PostHog user id to assign, or null to end the current assignment."+ ),+ )class UpdateAccountAction(BaseModel):@@ -171,6 +177,14 @@ class UpdateAccountAction(BaseModel):properties: AccountPropertiesInput | None = Field(default=None, description="Property keys to merge; pass a key as null to clear it")+ relationships: dict[str, int | None] | None = Field(+ default=None,+ description=(+ "Relationship assignments keyed by definition name (e.g. 'CSM'); each value is the "+ "PostHog user id to assign, or null to end the current assignment. Only the named "+ "definitions are changed."+ ),+ )UpsertAccountAction = Union[CreateAccountAction, UpdateAccountAction]@@ -204,6 +218,8 @@ class UpsertAccountTool(MaxTool):return f"An account with external_id '{action.external_id}' already exists for this team.", {"error": "duplicate_external_id",}+ except RelationshipAssignmentError as e:+ return str(e), {"error": "invalid_relationship_assignment"}except Exception as e:capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})return f"Failed to create account: {str(e)}", {"error": "creation_failed", "details": str(e)}@@ -220,7 +236,13 @@ class UpsertAccountTool(MaxTool):await self.check_object_access(account, "editor", resource="account", action="edit")- if action.name is None and action.external_id is None and action.tags is None and action.properties is None:+ if (+ action.name is None+ and action.external_id is None+ and action.tags is None+ and action.properties is None+ and action.relationships is None+ ):return "No changes provided. Specify at least one field to update.", {"error": "no_changes"}try:@@ -229,6 +251,8 @@ class UpsertAccountTool(MaxTool):return f"An account with external_id '{action.external_id}' already exists for this team.", {"error": "duplicate_external_id",}+ except RelationshipAssignmentError as e:+ return str(e), {"error": "invalid_relationship_assignment"}except Exception as e:capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})return f"Failed to update account: {str(e)}", {"error": "update_failed", "details": str(e)}@@ -258,8 +282,8 @@ class UpsertAccountTool(MaxTool):)if action.tags is not None:set_tags_on_object(action.tags, account)- if any(field in (account._properties or {}) for field in ACCOUNT_ASSIGNMENT_ROLE_FIELDS):- relationships_logic.sync_from_account_properties(account, created_by=self._user)+ if action.relationships:+ self._apply_relationship_assignments(account, action.relationships)return account@sync_to_async@@ -277,10 +301,46 @@ class UpsertAccountTool(MaxTool):account = Account.objects.update_account(account, **update_kwargs)if action.tags is not None:set_tags_on_object(action.tags, account)- if action.properties is not None:- relationships_logic.sync_from_account_properties(account, created_by=self._user)+ if action.relationships:+ self._apply_relationship_assignments(account, action.relationships)return account+ def _apply_relationship_assignments(self, account: Account, assignments: dict[str, int | None]) -> None:+ definitions = {+ definition.name: definition+ for definition in AccountRelationshipDefinition.objects.for_team(self._team.id).filter(+ name__in=assignments.keys()+ )+ }+ unknown = next((name for name in assignments if name not in definitions), None)+ if unknown is not None:+ available = AccountRelationshipDefinition.objects.for_team(self._team.id).values_list("name", flat=True)+ raise RelationshipAssignmentError(+ f"Unknown relationship definition '{unknown}'. Available: {', '.join(sorted(available)) or 'none'}."+ )+ user_ids = {user_id for user_id in assignments.values() if user_id is not None}+ memberships = {+ membership.user_id: membership+ for membership in OrganizationMembership.objects.select_related("user").filter(+ organization_id=self._team.organization_id, user_id__in=user_ids+ )+ }+ missing = sorted(user_ids - memberships.keys())+ if missing:+ raise RelationshipAssignmentError(f"User {missing[0]} is not a member of this organization.")+ for name, user_id in assignments.items():+ definition = definitions[name]+ if user_id is None:+ relationships_logic.end_active(team_id=self._team.id, account=account, definition=definition)+ continue+ relationships_logic.assign(+ team_id=self._team.id,+ account=account,+ definition=definition,+ user=memberships[user_id].user,+ created_by=self._user,+ )+UPSERT_ACCOUNT_NOTEBOOK_TOOL_DESCRIPTION = dedent("""Create or update a note attached to a customer account — a call recap, a meeting summary, andiff --git a/products/customer_analytics/backend/test/test_upsert_account.py b/products/customer_analytics/backend/test/test_upsert_account.pyindex 834f63fbada3..1b7989dad5b6 100644--- a/products/customer_analytics/backend/test/test_upsert_account.py+++ b/products/customer_analytics/backend/test/test_upsert_account.py@@ -6,16 +6,15 @@ from posthog.test.base import BaseTestfrom asgiref.sync import sync_to_asyncfrom langchain_core.runnables import RunnableConfig-from posthog.models import TaggedItem, Team+from posthog.models import TaggedItem, Team, Userfrom products.customer_analytics.backend.max_tools import (- AccountAssignment,AccountPropertiesInput,CreateAccountAction,UpdateAccountAction,UpsertAccountTool,)-from products.customer_analytics.backend.models import Account+from products.customer_analytics.backend.models import Account, AccountRelationship, AccountRelationshipDefinitionclass TestUpsertAccountTool(BaseTest):@@ -31,6 +30,19 @@ class TestUpsertAccountTool(BaseTest):lambda: sorted(TaggedItem.objects.filter(account=account).values_list("tag__name", flat=True)))()+ @sync_to_async+ def _create_definition(self, name: str = "CSM") -> AccountRelationshipDefinition:+ return AccountRelationshipDefinition.objects.for_team(self.team.id).create(team_id=self.team.id, name=name)++ async def _active_holder_ids(self, account: Account) -> set[int]:+ return await sync_to_async(+ lambda: set(+ AccountRelationship.objects.for_team(self.team.id)+ .filter(account=account, ended_at__isnull=True)+ .values_list("user_id", flat=True)+ )+ )()+@pytest.mark.django_db@pytest.mark.asyncioasync def test_create_account(self):@@ -47,18 +59,22 @@ class TestUpsertAccountTool(BaseTest):@pytest.mark.django_db@pytest.mark.asyncio- async def test_create_with_properties_and_tags(self):+ async def test_create_with_properties_tags_and_relationships(self):+ await self._create_definition("CSM")+_, artifact = await self._tool()._arun_impl(action=CreateAccountAction(name="Acme Corp",- properties=AccountPropertiesInput(csm=AccountAssignment(id=self.user.id, email=self.user.email)),+ properties=AccountPropertiesInput(stripe_customer_id="cus_42"),tags=["enterprise", "priority"],+ relationships={"CSM": self.user.id},))account = await sync_to_async(Account.objects.unscoped().get)(id=artifact["account_id"])- assert account._properties["csm"] == {"id": self.user.id, "email": self.user.email}+ assert account._properties["stripe_customer_id"] == "cus_42"assert await self._tags_for(account) == ["enterprise", "priority"]+ assert await self._active_holder_ids(account) == {self.user.id}@pytest.mark.django_db@pytest.mark.asyncio@@ -71,23 +87,55 @@ class TestUpsertAccountTool(BaseTest):@pytest.mark.django_db@pytest.mark.asyncio- async def test_update_assigns_role_and_merges_properties(self):- account = await sync_to_async(Account.objects.unscoped().create)(- team=self.team, name="Acme Corp", _properties={"csm": {"id": 1, "email": "[email protected]"}}- )+ async def test_update_relationships_assigns_hands_off_and_ends(self):+ await self._create_definition("CSM")+ successor = await sync_to_async(self._create_user)("[email protected]")+ account = await sync_to_async(Account.objects.unscoped().create)(team=self.team, name="Acme")_, artifact = await self._tool()._arun_impl(- action=UpdateAccountAction(- account_id=str(account.id),- properties=AccountPropertiesInput(- account_owner=AccountAssignment(id=self.user.id, email=self.user.email)- ),- )+ action=UpdateAccountAction(account_id=str(account.id), relationships={"CSM": self.user.id})+ )+ assert "error" not in artifact+ assert await self._active_holder_ids(account) == {self.user.id}++ await self._tool()._arun_impl(+ action=UpdateAccountAction(account_id=str(account.id), relationships={"CSM": successor.id})+ )+ assert await self._active_holder_ids(account) == {successor.id}++ await self._tool()._arun_impl(+ action=UpdateAccountAction(account_id=str(account.id), relationships={"CSM": None})+ )+ assert await self._active_holder_ids(account) == set()++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_create_with_unknown_relationship_name_persists_nothing(self):+ await self._create_definition("CSM")++ content, artifact = await self._tool()._arun_impl(+ action=CreateAccountAction(name="Acme", relationships={"Account executive": self.user.id})+ )++ assert artifact["error"] == "invalid_relationship_assignment"+ assert "Account executive" in content+ assert "CSM" in content+ assert not await sync_to_async(Account.objects.unscoped().filter(team=self.team).exists)()++ @pytest.mark.django_db+ @pytest.mark.asyncio+ async def test_update_relationship_with_non_member_user_returns_error(self):+ await self._create_definition("CSM")+ outsider = await sync_to_async(User.objects.create_user)("[email protected]", None, "")+ account = await sync_to_async(Account.objects.unscoped().create)(team=self.team, name="Acme")++ content, artifact = await self._tool()._arun_impl(+ action=UpdateAccountAction(account_id=str(account.id), relationships={"CSM": outsider.id}))- refreshed = await sync_to_async(Account.objects.unscoped().get)(id=account.id)- assert refreshed._properties["csm"] == {"id": 1, "email": "[email protected]"}- assert refreshed._properties["account_owner"] == {"id": self.user.id, "email": self.user.email}+ assert artifact["error"] == "invalid_relationship_assignment"+ assert content == f"User {outsider.id} is not a member of this organization."+ assert await self._active_holder_ids(account) == set()@pytest.mark.django_db@pytest.mark.asyncio