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.

2.0 KB
Raw Blame
from uuid import uuid4

from langchain_core.runnables import RunnableConfig

from posthog.schema import AssistantMessage, HumanMessage

from products.posthog_ai.backend.models.assistant import CoreMemory

from ee.hogai.chat_agent.slash_commands.commands import SlashCommand
from ee.hogai.core.agent_modes.const import SlashCommandName
from ee.hogai.utils.types import AssistantState, PartialAssistantState


class RememberCommand(SlashCommand):
    """
    Handles the /remember slash command.
    Appends the provided content to the team's core memory.
    """

    def get_memory_content(self, state: AssistantState) -> str | None:
        """Extract the content to remember from the last human message."""
        for msg in reversed(state.messages):
            if isinstance(msg, HumanMessage):
                content = msg.content
                if content.startswith(SlashCommandName.FIELD_REMEMBER):
                    return content[len(SlashCommandName.FIELD_REMEMBER) :].strip()
                return None
        return None

    async def execute(self, config: RunnableConfig, state: AssistantState) -> PartialAssistantState:
        memory_content = self.get_memory_content(state)

        if not memory_content:
            return PartialAssistantState(
                messages=[
                    AssistantMessage(
                        content="Please provide something to remember. Usage: `/remember <fact to remember>`",
                        id=str(uuid4()),
                    )
                ]
            )

        try:
            await self._append_to_memory(memory_content)
        except ValueError as e:
            return PartialAssistantState(messages=[AssistantMessage(content=str(e), id=str(uuid4()))])

        return PartialAssistantState(
            messages=[AssistantMessage(content="I'll remember that for you.", id=str(uuid4()))]
        )

    async def _append_to_memory(self, content: str) -> None:
        core_memory, _ = await CoreMemory.objects.aget_or_create(team=self._team)
        await core_memory.aappend_core_memory(content)