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.

42.4 KB
Raw Blame
"""
MaxTool for AI-powered survey creation and analysis.
"""

from datetime import timedelta
from textwrap import dedent
from typing import Any, Literal

import django.utils.timezone

from asgiref.sync import sync_to_async
from pydantic import BaseModel, ConfigDict, Field
from rest_framework import serializers

from posthog.schema import SurveyAnalysisQuestionGroup, SurveyAnalysisResponseItem

from posthog.constants import DEFAULT_SURVEY_APPEARANCE
from posthog.exceptions_capture import capture_exception
from posthog.models import Team

from products.feature_flags.backend.models.feature_flag import FeatureFlag
from products.surveys.backend.api.survey import SurveySerializerCreateUpdateOnly
from products.surveys.backend.models import MAX_ITERATION_COUNT, MAX_ITERATION_FREQUENCY_DAYS, Survey
from products.surveys.backend.summarization.fetch import fetch_responses

from ee.hogai.tool import MaxTool

SEMANTIC_QUESTION_TYPE = Literal[
    "open",
    "single_choice",
    "multiple_choice",
    "nps",
    "csat",
    "emoji_scale",
    "thumbs",
    "link",
]

QUESTION_TYPE_MAP: dict[str, dict[str, Any]] = {
    "open": {"type": "open"},
    "single_choice": {"type": "single_choice"},
    "multiple_choice": {"type": "multiple_choice"},
    "nps": {"type": "rating", "scale": 10, "display": "number"},
    "csat": {"type": "rating", "scale": 5, "display": "number"},
    "emoji_scale": {"type": "rating", "scale": 5, "display": "emoji"},
    "thumbs": {"type": "rating", "scale": 2, "display": "emoji"},
    "link": {"type": "link"},
}


class SimpleSurveyQuestion(BaseModel):
    model_config = ConfigDict(extra="ignore")

    id: str | None = Field(
        default=None,
        description="Existing question identifier. Accepts either the question number from the survey "
        "context (e.g. '1', '2', '3') or the question's real UUID. Reuse to preserve question identity "
        "and historical response data. Omit for new questions.",
    )
    type: SEMANTIC_QUESTION_TYPE
    question: str
    description: str | None = None
    optional: bool | None = None
    choices: list[str] | None = None
    scale: int | None = Field(
        default=None,
        description="Rating scale (3, 5, 7, or 10). Only set to change an existing rating's scale; "
        "omit to preserve it.",
    )
    display: Literal["number", "emoji"] | None = Field(
        default=None,
        description="Rating display format. Only set to change it; omit to preserve the existing one.",
    )
    lower_bound_label: str | None = None
    upper_bound_label: str | None = None
    link: str | None = None
    button_text: str | None = None


def get_team_survey_config(team: Team) -> dict[str, Any]:
    """Get team survey configuration for context."""
    survey_config = getattr(team, "survey_config", {}) or {}
    return {
        "appearance": survey_config.get("appearance", {}),
        "default_settings": {"type": "popover", "enable_partial_responses": True},
    }


async def _validate_linked_flag_id(team: Team, linked_flag_id: int | None) -> None:
    if linked_flag_id is None:
        return
    if not await FeatureFlag.objects.filter(pk=linked_flag_id, team_id=team.id).aexists():
        raise serializers.ValidationError("Feature Flag with this ID does not exist")


# SimpleSurveyQuestion attribute -> internal question dict key. Rating-only fields (scale, display)
# are handled separately in _apply_question_overrides since they depend on the question type.
_QUESTION_FIELD_MAP: dict[str, str] = {
    "description": "description",
    "optional": "optional",
    "choices": "choices",
    "lower_bound_label": "lowerBoundLabel",
    "upper_bound_label": "upperBoundLabel",
    "link": "link",
    "button_text": "buttonText",
}


def _apply_question_overrides(result: dict[str, Any], q: SimpleSurveyQuestion) -> None:
    """Write the explicitly-provided SimpleSurveyQuestion fields onto an internal question dict.

    Shared by the build (from QUESTION_TYPE_MAP) and merge (onto an existing question) paths so
    both apply the exact same set of fields. Only non-None values are written; scale/display only
    apply to rating questions.
    """
    result["question"] = q.question
    for attr, key in _QUESTION_FIELD_MAP.items():
        value = getattr(q, attr)
        if value is not None:
            result[key] = value
    is_rating = result.get("type") == "rating"
    if is_rating and q.scale is not None:
        result["scale"] = q.scale
    if is_rating and q.display is not None:
        result["display"] = q.display


def _build_question(q: SimpleSurveyQuestion) -> dict[str, Any]:
    """Convert a SimpleSurveyQuestion to the internal question dict."""
    if q.type in ("single_choice", "multiple_choice") and not q.choices:
        raise serializers.ValidationError(f"Question of type '{q.type}' must include a non-empty 'choices' list")
    result = dict(QUESTION_TYPE_MAP[q.type])
    _apply_question_overrides(result, q)
    return result


def _merge_question(existing: dict[str, Any], q: SimpleSurveyQuestion) -> dict[str, Any]:
    """Overlay only the explicitly-provided fields onto an existing question.

    Used on edit when the underlying type is unchanged. The semantic SimpleSurveyQuestion can't
    represent everything a stored question holds (rating scale, display, branching), so rebuilding
    from QUESTION_TYPE_MAP on a reorder or text tweak would silently discard that config. Merging
    keeps the existing question's id and untouched fields intact.
    """
    if q.type in ("single_choice", "multiple_choice") and not (q.choices or existing.get("choices")):
        raise serializers.ValidationError(f"Question of type '{q.type}' must include a non-empty 'choices' list")
    merged = dict(existing)
    _apply_question_overrides(merged, q)
    return merged


def _resolve_edited_question(simple_q: SimpleSurveyQuestion, existing: dict[str, Any] | None) -> dict[str, Any]:
    """Build one replacement question, preserving identity and (for same-type edits) stored config."""
    if existing is not None and QUESTION_TYPE_MAP[simple_q.type]["type"] == existing.get("type"):
        return _merge_question(existing, simple_q)
    built = _build_question(simple_q)
    if existing is not None and existing.get("id"):
        built["id"] = existing["id"]  # preserve identity even when the type changes
    return built


def _resolve_edited_questions(
    existing_questions: list[dict[str, Any]], questions: list[SimpleSurveyQuestion]
) -> list[dict[str, Any]]:
    """Build the replacement questions list for an edit, preserving identity and untouched config.

    A supplied id resolves against both the 1-indexed positional label shown in read_data and the
    question's real UUID, so passing either form keeps the question's identity (and its historical
    responses). Each resolved id is kept unique: if two inputs resolve to the same existing question,
    only the first keeps that id and the rest get a fresh one on save.
    """
    by_label = {str(i + 1): eq for i, eq in enumerate(existing_questions)}
    by_uuid = {eq["id"]: eq for eq in existing_questions if eq.get("id")}

    resolved: list[dict[str, Any]] = []
    used_ids: set[str] = set()
    for simple_q in questions:
        existing = (by_uuid.get(simple_q.id) or by_label.get(simple_q.id)) if simple_q.id else None
        question = _resolve_edited_question(simple_q, existing)
        question_id = question.get("id")
        if question_id and question_id in used_ids:
            # Another question already claimed this id (e.g. two inputs reference the same existing
            # question). Drop it so this one gets a fresh, unique id on save instead of colliding.
            question.pop("id", None)
        elif question_id:
            used_ids.add(question_id)
        resolved.append(question)
    return resolved


def _validate_and_sanitize_questions(questions: list[dict[str, Any]]) -> list[dict[str, Any]]:
    serializer = SurveySerializerCreateUpdateOnly()
    return serializer.validate_questions(questions)


def _build_appearance(team: Team) -> dict[str, Any]:
    """Build appearance dict with global + team defaults."""
    appearance = DEFAULT_SURVEY_APPEARANCE.copy()
    team_appearance = get_team_survey_config(team).get("appearance", {})
    if team_appearance:
        appearance.update(team_appearance)
    return appearance


URL_MATCH_ALIASES: dict[str, str] = {
    "exact": "exact",
    "contains": "icontains",
    "icontains": "icontains",
    "regex": "regex",
}


def _build_targeting_conditions(
    target_url: str | None,
    target_url_match: str | None,
    linked_flag_variant: str | None,
    wait_period_days: int | None = None,
) -> dict[str, Any]:
    conditions: dict[str, Any] = {}
    if target_url is not None:
        conditions["url"] = target_url
        conditions["urlMatchType"] = URL_MATCH_ALIASES[target_url_match or "contains"]
    if linked_flag_variant is not None:
        conditions["linkedFlagVariant"] = linked_flag_variant
    if wait_period_days is not None:
        conditions["seenSurveyWaitPeriodInDays"] = wait_period_days
    return conditions


SCHEDULE_OPTION = Literal["once", "recurring", "always"]

# Same defaults the survey editor applies when a user picks "Repeat on a schedule"
DEFAULT_ITERATION_COUNT = 2
DEFAULT_ITERATION_FREQUENCY_DAYS = 90

SCHEDULE_DESCRIPTION = (
    "How often a person can see the survey. "
    "'once' (default): show it one time per person. "
    "'recurring': show it again on a fixed schedule, set with iteration_count and iteration_frequency_days. "
    "'always': show it every time the display conditions are met, also after the person responds or dismisses it. "
    "In the survey editor, 'always' is the 'Every time the display conditions are met' option "
    "in the 'Completion conditions' section. For a widget survey it is also the "
    "'Allow survey to be displayed every time the button is clicked' checkbox in the 'Presentation' section."
)

SCHEDULE_PROMPT = """
    # Schedule (how often a person sees the survey)
    Use the schedule field. The survey editor shows it in the "Completion conditions" section as
    "How often should we show this survey to a person?". These are the only options:
    - "once" (default) -> "Once": a person sees the survey one time
    - "recurring" -> "Repeat on a schedule": the survey shows up to iteration_count times, once every
      iteration_frequency_days days (defaults: 2 times, every 90 days)
    - "always" -> "Every time the display conditions are met": the survey shows again each time the
      display conditions match, also after the person responds or dismisses it
    For a widget (feedback button) survey, the editor also shows "always" as the checkbox
    "Allow survey to be displayed every time the button is clicked" in the "Presentation" section.
    When you tell a user where to find this for a widget survey, name that checkbox first.
    Do not invent other options or labels. When a user asks to show a survey every time or keep showing it,
    use "always". An "always" popover with no display conditions (URL, wait period) appears again and again,
    so suggest a URL target or wait_period_days.

"""


def _build_schedule_fields(
    schedule: str | None,
    iteration_count: int | None,
    iteration_frequency_days: int | None,
    current_iteration_count: int | None = None,
    current_iteration_frequency_days: int | None = None,
) -> dict[str, Any]:
    # Iteration values alone configure repeats, the same as in the survey API serializer
    if schedule is None and (iteration_count is not None or iteration_frequency_days is not None):
        schedule = Survey.Schedule.RECURRING
    if schedule is None:
        return {}
    if schedule == Survey.Schedule.RECURRING:
        iteration_count = iteration_count or current_iteration_count or DEFAULT_ITERATION_COUNT
        iteration_frequency_days = (
            iteration_frequency_days or current_iteration_frequency_days or DEFAULT_ITERATION_FREQUENCY_DAYS
        )
        return {
            "schedule": schedule,
            "iteration_count": min(iteration_count, MAX_ITERATION_COUNT),
            "iteration_frequency_days": iteration_frequency_days,
        }
    # The iteration columns drive repeats on their own, so clear them for non-recurring schedules
    return {"schedule": schedule, "iteration_count": None, "iteration_frequency_days": None}


def _always_schedule_warning(survey_type: str, schedule: str | None, conditions: dict[str, Any] | None) -> str:
    if schedule != Survey.Schedule.ALWAYS or survey_type != Survey.SurveyType.POPOVER:
        return ""
    conditions = conditions or {}
    wait_period_days = conditions.get("seenSurveyWaitPeriodInDays") or 0
    if wait_period_days > 0:
        return (
            f" Note: this popover shows again every {wait_period_days} days, "
            "as long as its other display conditions are met."
        )
    has_display_conditions = bool(
        conditions.get("url")
        or conditions.get("selector")
        or (conditions.get("events") or {}).get("values")
        or conditions.get("deviceTypes")
    )
    if has_display_conditions:
        return (
            " Note: this popover shows again every time its display conditions are met, "
            "so people can see it very often. Add a wait period to limit this."
        )
    return (
        " Warning: this popover has no display conditions, so it shows again and again. "
        "Add a URL target or a wait period to limit this."
    )


SURVEY_CREATION_TOOL_DESCRIPTION = dedent(f"""
    Create and optionally launch a survey.

    # When to use
    - The user wants to create a new survey
    - The user mentions NPS, CSAT, PMF, or feedback surveys
    - The user wants a hosted survey with a shareable link

    # Design principles
    Keep to 1-3 questions. DO NOT set should_launch=true unless the user explicitly asks to launch.

    # Survey types
    - "popover" (default): small in-app overlay that appears on the page — use this for most surveys
    - "widget": persistent in-app tab/button on the page edge, good for always-available feedback
    - "external_survey": a hosted standalone page with a shareable public link — use this when the
      user wants to send a survey via a link (email, social, QR code) rather than show it inside their app
    - "api": headless, no UI — for custom implementations only

    # Targeting
    Targeting (target_url, feature flags, device types, wait period) only applies to in-app surveys.
    It does not apply to "external_survey" hosted surveys and is ignored for them.

    # Semantic question types
    - "nps": 0-10 numeric rating (Net Promoter Score)
    - "csat": 1-5 numeric rating (Customer Satisfaction)
    - "emoji_scale": 1-5 emoji rating
    - "thumbs": thumbs up/down (2-point emoji)
    - "open": free-form text
    - "single_choice": pick one from choices
    - "multiple_choice": pick many from choices
    - "link": call-to-action link
    {SCHEDULE_PROMPT}
    # After creation
    Always share the survey link with the user so they can view and configure it.
    The link is included in the tool response.
    """).strip()


class CreateSurveyToolArgs(BaseModel):
    model_config = ConfigDict(extra="ignore")

    name: str = Field(description="Survey name")
    description: str = Field(default="", description="Brief survey description")
    questions: list[SimpleSurveyQuestion] = Field(description="List of questions")
    survey_type: Literal["popover", "widget", "external_survey", "api"] = Field(
        default="popover", description="Survey display type"
    )
    should_launch: bool = Field(default=False, description="Launch immediately after creation")
    target_url: str | None = Field(default=None, description="URL path to target (e.g. '/pricing')")
    target_url_match: Literal["exact", "contains", "regex"] | None = Field(
        default=None, description="How to match the target URL"
    )
    linked_flag_id: int | None = Field(default=None, description="Feature flag ID for targeting")
    linked_flag_variant: str | None = Field(default=None, description="Feature flag variant to target")
    wait_period_days: int | None = Field(
        default=None, description="Days to wait after user has seen any survey before showing this one"
    )
    responses_limit: int | None = Field(default=None, description="Maximum number of responses to collect")
    schedule: SCHEDULE_OPTION | None = Field(default=None, description=SCHEDULE_DESCRIPTION)
    iteration_count: int | None = Field(
        default=None,
        ge=1,
        le=MAX_ITERATION_COUNT,
        description="With schedule='recurring': how many times in total to show the survey (default 2, max 500)",
    )
    iteration_frequency_days: int | None = Field(
        default=None,
        ge=1,
        le=MAX_ITERATION_FREQUENCY_DAYS,
        description="With schedule='recurring': days between repeats (default 90)",
    )


class CreateSurveyTool(MaxTool):
    name: str = "create_survey"
    description: str = SURVEY_CREATION_TOOL_DESCRIPTION
    args_schema: type[BaseModel] = CreateSurveyToolArgs

    def get_required_resource_access(self):
        return [("survey", "editor")]

    async def is_dangerous_operation(self, should_launch: bool = False, **kwargs) -> bool:
        return should_launch is True

    async def format_dangerous_operation_preview(
        self, name: str = "Untitled Survey", questions: list[SimpleSurveyQuestion] | None = None, **kwargs
    ) -> str:
        question_count = len(questions) if questions else 0
        return f"**Create and launch** survey '{name}' with {question_count} question(s). It will immediately start collecting responses."

    def _build_survey_data(
        self,
        *,
        name: str,
        description: str,
        questions: list[SimpleSurveyQuestion],
        survey_type: str,
        target_url: str | None,
        target_url_match: str | None,
        linked_flag_id: int | None,
        linked_flag_variant: str | None,
        wait_period_days: int | None,
        responses_limit: int | None,
        schedule: str | None = None,
        iteration_count: int | None = None,
        iteration_frequency_days: int | None = None,
    ) -> dict[str, Any]:
        survey_data: dict[str, Any] = {
            "name": name,
            "description": description,
            "type": survey_type,
            "questions": [_build_question(q) for q in questions],
            "appearance": _build_appearance(self._team),
            "archived": False,
            "enable_partial_responses": True,
        }

        if responses_limit is not None:
            survey_data["responses_limit"] = responses_limit

        # Hosted (external) surveys are standalone pages with no in-app display context, so the
        # backend rejects flag/URL/device targeting on them. Skip targeting entirely for those.
        if survey_type != Survey.SurveyType.EXTERNAL_SURVEY:
            if linked_flag_id is not None:
                survey_data["linked_flag_id"] = linked_flag_id

            conditions = _build_targeting_conditions(
                target_url, target_url_match, linked_flag_variant, wait_period_days
            )
            if conditions:
                survey_data["conditions"] = conditions

            survey_data.update(_build_schedule_fields(schedule, iteration_count, iteration_frequency_days))

        if self.context.get("insight_id"):
            survey_data["linked_insight_id"] = self.context["insight_id"]

        return survey_data

    async def _arun_impl(
        self,
        name: str = "Untitled Survey",
        description: str = "",
        questions: list[SimpleSurveyQuestion] | None = None,
        survey_type: str = "popover",
        should_launch: bool = False,
        target_url: str | None = None,
        target_url_match: str | None = None,
        linked_flag_id: int | None = None,
        linked_flag_variant: str | None = None,
        wait_period_days: int | None = None,
        responses_limit: int | None = None,
        schedule: str | None = None,
        iteration_count: int | None = None,
        iteration_frequency_days: int | None = None,
    ) -> tuple[str, dict[str, Any]]:
        try:
            if not questions:
                return "Survey must have at least one question", {
                    "error": "validation_failed",
                    "error_message": "No questions provided in the survey configuration.",
                }

            if survey_type != Survey.SurveyType.EXTERNAL_SURVEY:
                await _validate_linked_flag_id(self._team, linked_flag_id)

            survey_data = self._build_survey_data(
                name=name,
                description=description,
                questions=questions,
                survey_type=survey_type,
                target_url=target_url,
                target_url_match=target_url_match,
                linked_flag_id=linked_flag_id,
                linked_flag_variant=linked_flag_variant,
                wait_period_days=wait_period_days,
                responses_limit=responses_limit,
                schedule=schedule,
                iteration_count=iteration_count,
                iteration_frequency_days=iteration_frequency_days,
            )
            survey_data["questions"] = _validate_and_sanitize_questions(survey_data["questions"])

            if should_launch:
                survey_data["start_date"] = django.utils.timezone.now()

            created_survey = await Survey.objects.acreate(team=self._team, created_by=self._user, **survey_data)

            launch_msg = " and launched" if should_launch else ""
            survey_id = str(created_survey.id)
            if survey_type == "popover":
                survey_url = f"/surveys/guided/{survey_id}"
            else:
                survey_url = f"/surveys/{survey_id}?edit=true"

            message = f"Survey '{created_survey.name}' created{launch_msg} successfully! [View survey]({survey_url})"
            if survey_type == Survey.SurveyType.EXTERNAL_SURVEY:
                # The public shareable link only works once the survey is running.
                share_hint = (
                    "Its public shareable link is on the survey page."
                    if should_launch
                    else "Launch it to activate its public shareable link, which you'll find on the survey page."
                )
                message = f"{message} {share_hint}"
            message += _always_schedule_warning(survey_type, survey_data.get("schedule"), survey_data.get("conditions"))

            return message, {
                "survey_id": created_survey.id,
                "survey_name": created_survey.name,
                "survey_type": survey_type,
            }

        except serializers.ValidationError as e:
            error_message = str(e.detail if hasattr(e, "detail") else e)
            return f"Survey validation failed: {error_message}", {
                "error": "validation_failed",
                "error_message": error_message,
            }
        except Exception as e:
            capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})
            return f"Failed to create survey: {str(e)}", {"error": "creation_failed", "details": str(e)}


SURVEY_EDIT_TOOL_DESCRIPTION = dedent(f"""
    Edit an existing survey.

    # When to use
    - User wants to modify a survey's name, description, or questions
    - User wants to launch, stop, or archive a survey
    - User wants to change survey targeting conditions

    # Finding the survey
    First use the search tool with kind="surveys" to find the survey ID.

    # Lifecycle
    - Set launch=true to start collecting responses
    - Set stop=true to stop collecting responses
    - Set archive=true to archive the survey

    # Removing targeting
    - Set remove_url_targeting=true to remove URL targeting
    - Set remove_linked_flag=true to remove linked feature flag targeting
    - Set remove_linked_flag_variant=true to remove only feature flag variant targeting
    - Set remove_wait_period=true to remove the survey wait period
    {SCHEDULE_PROMPT}
    # Question identity
    - When updating questions, use read_data(kind="survey") first to see the current questions
    - Each question is shown with a number (1, 2, 3, ...) — pass that number (or the question's real UUID) as the question's `id` to preserve its identity and historical response data
    - Omit `id` for entirely new questions; they will be assigned a fresh ID automatically
    - For an existing question, only fields you set are changed; everything else (including a rating's scale, display, and labels) is preserved. To change a rating's scale, set `scale` explicitly.

    # Important
    - Only include fields you want to change
    - Omitted targeting fields are preserved. Use the remove_* fields when the user explicitly asks to remove targeting.
    - When updating questions, provide the complete list (it replaces existing)
    """).strip()


class EditSurveyToolArgs(BaseModel):
    model_config = ConfigDict(extra="ignore")

    survey_id: str = Field(description="UUID of the survey to edit")
    name: str | None = Field(default=None, description="New survey name")
    description: str | None = Field(default=None, description="New survey description")
    questions: list[SimpleSurveyQuestion] | None = Field(default=None, description="Replacement questions list")
    target_url: str | None = Field(default=None, description="URL path to target")
    target_url_match: Literal["exact", "contains", "regex"] | None = Field(
        default=None, description="How to match the target URL"
    )
    linked_flag_id: int | None = Field(default=None, description="Feature flag ID for targeting")
    linked_flag_variant: str | None = Field(default=None, description="Feature flag variant to target")
    wait_period_days: int | None = Field(
        default=None, description="Minimum days before showing this survey again to a user who has seen any survey"
    )
    remove_url_targeting: bool = Field(default=False, description="Remove URL targeting from the survey")
    remove_linked_flag: bool = Field(default=False, description="Remove linked feature flag targeting from the survey")
    remove_linked_flag_variant: bool = Field(
        default=False, description="Remove feature flag variant targeting from the survey"
    )
    remove_wait_period: bool = Field(default=False, description="Remove the survey wait period")
    responses_limit: int | None = Field(default=None, description="Maximum number of responses")
    schedule: SCHEDULE_OPTION | None = Field(default=None, description=SCHEDULE_DESCRIPTION)
    iteration_count: int | None = Field(
        default=None,
        ge=1,
        le=MAX_ITERATION_COUNT,
        description="With schedule='recurring': how many times in total to show the survey (max 500)",
    )
    iteration_frequency_days: int | None = Field(
        default=None,
        ge=1,
        le=MAX_ITERATION_FREQUENCY_DAYS,
        description="With schedule='recurring': days between repeats",
    )
    launch: bool | None = Field(default=None, description="Set to true to launch the survey")
    stop: bool | None = Field(default=None, description="Set to true to stop the survey")
    archive: bool | None = Field(default=None, description="Set to true to archive the survey")


class EditSurveyTool(MaxTool):
    name: str = "edit_survey"
    description: str = SURVEY_EDIT_TOOL_DESCRIPTION
    args_schema: type[BaseModel] = EditSurveyToolArgs

    def get_required_resource_access(self):
        return [("survey", "editor")]

    async def is_dangerous_operation(
        self,
        survey_id: str,
        launch: bool | None = None,
        stop: bool | None = None,
        archive: bool | None = None,
        remove_url_targeting: bool = False,
        remove_linked_flag: bool = False,
        remove_linked_flag_variant: bool = False,
        remove_wait_period: bool = False,
        **kwargs,
    ) -> bool:
        return (
            launch is True
            or stop is True
            or archive is True
            or remove_url_targeting is True
            or remove_linked_flag is True
            or remove_linked_flag_variant is True
            or remove_wait_period is True
        )

    async def format_dangerous_operation_preview(
        self,
        survey_id: str,
        launch: bool | None = None,
        stop: bool | None = None,
        archive: bool | None = None,
        remove_url_targeting: bool = False,
        remove_linked_flag: bool = False,
        remove_linked_flag_variant: bool = False,
        remove_wait_period: bool = False,
        **kwargs,
    ) -> str:
        survey_name = survey_id
        try:
            survey = await sync_to_async(Survey.objects.get)(id=survey_id, team=self._team)
            survey_name = f"'{survey.name}'"
        except Survey.DoesNotExist:
            survey_name = f"(ID: {survey_id})"

        actions = []
        if launch is True:
            actions.append("**Launch** the survey (it will start collecting responses)")
        if stop is True:
            actions.append("**Stop** the survey (it will stop collecting responses)")
        if archive is True:
            actions.append("**Archive** the survey")
        if remove_url_targeting is True:
            actions.append("**Remove URL targeting** from the survey")
        if remove_linked_flag is True:
            actions.append("**Remove linked feature flag targeting** from the survey")
        if remove_linked_flag_variant is True:
            actions.append("**Remove feature flag variant targeting** from the survey")
        if remove_wait_period is True:
            actions.append("**Remove the survey wait period**")

        if len(actions) == 1:
            return f"{actions[0]} {survey_name}"
        else:
            action_list = "\n".join(f"- {action}" for action in actions)
            return f"Perform the following actions on survey {survey_name}:\n{action_list}"

    async def _arun_impl(
        self,
        survey_id: str,
        name: str | None = None,
        description: str | None = None,
        questions: list[SimpleSurveyQuestion] | None = None,
        target_url: str | None = None,
        target_url_match: str | None = None,
        linked_flag_id: int | None = None,
        linked_flag_variant: str | None = None,
        wait_period_days: int | None = None,
        remove_url_targeting: bool = False,
        remove_linked_flag: bool = False,
        remove_linked_flag_variant: bool = False,
        remove_wait_period: bool = False,
        responses_limit: int | None = None,
        schedule: str | None = None,
        iteration_count: int | None = None,
        iteration_frequency_days: int | None = None,
        launch: bool | None = None,
        stop: bool | None = None,
        archive: bool | None = None,
    ) -> tuple[str, dict[str, Any]]:
        try:
            team = self._team

            try:
                survey = await sync_to_async(Survey.objects.get)(id=survey_id, team=team)
            except Survey.DoesNotExist:
                return f"Survey with ID '{survey_id}' not found", {
                    "error": "not_found",
                    "error_message": f"No survey found with ID '{survey_id}' in your team.",
                }

            await _validate_linked_flag_id(team, linked_flag_id)

            update_data: dict[str, Any] = {}

            if name is not None:
                update_data["name"] = name
            if description is not None:
                update_data["description"] = description
            if questions is not None:
                new_questions = _resolve_edited_questions(survey.questions or [], questions)
                update_data["questions"] = _validate_and_sanitize_questions(new_questions)
            if linked_flag_id is not None:
                update_data["linked_flag_id"] = linked_flag_id
            elif remove_linked_flag:
                update_data["linked_flag_id"] = None
            if responses_limit is not None:
                update_data["responses_limit"] = responses_limit

            existing_conditions = dict(survey.conditions or {})
            updated_conditions = dict(existing_conditions)
            if remove_url_targeting:
                updated_conditions.pop("url", None)
                updated_conditions.pop("urlMatchType", None)
            if remove_linked_flag or remove_linked_flag_variant:
                updated_conditions.pop("linkedFlagVariant", None)
            if remove_wait_period:
                updated_conditions.pop("seenSurveyWaitPeriodInDays", None)

            conditions = _build_targeting_conditions(
                target_url, target_url_match, linked_flag_variant, wait_period_days
            )
            if conditions:
                updated_conditions.update(conditions)
            if updated_conditions != existing_conditions:
                update_data["conditions"] = updated_conditions

            schedule_fields = _build_schedule_fields(
                schedule,
                iteration_count,
                iteration_frequency_days,
                current_iteration_count=survey.iteration_count,
                current_iteration_frequency_days=survey.iteration_frequency_days,
            )
            new_iteration_count = schedule_fields.get("iteration_count")
            if survey.current_iteration and new_iteration_count and survey.current_iteration > new_iteration_count:
                raise serializers.ValidationError(
                    f"Cannot change survey recurrence to {new_iteration_count}, should be at least {survey.current_iteration}"
                )
            update_data.update(schedule_fields)

            # Lifecycle bools
            lifecycle_actions = []
            if launch is True:
                update_data["start_date"] = django.utils.timezone.now()
                lifecycle_actions.append("launched")
            if stop is True:
                update_data["end_date"] = django.utils.timezone.now()
                lifecycle_actions.append("stopped")
            if archive is True:
                update_data["archived"] = True
                lifecycle_actions.append("archived")

            if not update_data:
                return "No updates provided", {
                    "error": "no_updates",
                    "error_message": "No fields were provided to update.",
                }

            for field, value in update_data.items():
                setattr(survey, field, value)

            await sync_to_async(survey.save)()

            if lifecycle_actions:
                action_str = " and ".join(lifecycle_actions)
                message = f"Survey '{survey.name}' has been {action_str} successfully!"
            else:
                fields_str = ", ".join(update_data.keys())
                message = f"Survey '{survey.name}' updated successfully! Modified fields: {fields_str}"
            if schedule is not None:
                message += _always_schedule_warning(survey.type, survey.schedule, survey.conditions)

            return message, {
                "survey_id": str(survey.id),
                "survey_name": survey.name,
                "updated_fields": list(update_data.keys()),
            }

        except serializers.ValidationError as e:
            error_message = str(e.detail if hasattr(e, "detail") else e)
            return f"Survey validation failed: {error_message}", {
                "error": "validation_failed",
                "error_message": error_message,
            }
        except Exception as e:
            capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})
            return f"Failed to edit survey: {str(e)}", {"error": "edit_failed", "details": str(e)}


class SurveyAnalysisArgs(BaseModel):
    """Retrieve survey responses for analysis."""

    survey_id: str | None = Field(
        default=None,
        description="UUID of the survey to analyze. If not provided, uses survey from current context.",
    )


class SurveyAnalysisTool(MaxTool):
    name: str = "analyze_survey_responses"
    description: str = dedent("""
        Retrieve survey responses for analysis.

        # When to use
        - User asks to analyze survey responses or feedback
        - User wants to find themes, patterns, or insights from survey data
        - User asks about sentiment or recommendations from survey feedback

        # Finding the Survey
        If you don't have a survey_id, first use the search tool with kind="surveys" to find it.

        # What this tool returns
        Returns the raw open-ended responses from the survey which you should then analyze
        to extract themes, sentiment, and actionable insights.
    """).strip()
    args_schema: type[BaseModel] = SurveyAnalysisArgs

    def get_required_resource_access(self):
        return [("survey", "viewer")]

    def _format_responses_for_analysis(self, question_groups: list[SurveyAnalysisQuestionGroup]) -> str:
        """
        Format the grouped responses into a string for analysis.
        """
        formatted_sections = []

        for group in question_groups:
            question_name = group.questionName
            responses = group.responses

            formatted_sections.append(f'Question: "{question_name}"')

            response_texts = []
            if responses:
                for response in responses:
                    response_text = response.responseText
                    response_texts.append(f'- "{response_text}"')

            if response_texts:
                formatted_sections.append("Responses:\n" + "\n".join(response_texts))
            else:
                formatted_sections.append("Responses: (none)")
            formatted_sections.append("")

        return "\n".join(formatted_sections)

    async def _fetch_survey_responses(self, survey: Survey) -> list[SurveyAnalysisQuestionGroup]:
        """Fetch open-ended responses for a survey from the database."""
        questions = survey.questions or []
        question_groups: list[SurveyAnalysisQuestionGroup] = []

        # Use survey start_date or created_at as the start, and now as the end
        start_date = survey.start_date or survey.created_at or (django.utils.timezone.now() - timedelta(days=365))
        end_date = survey.end_date or django.utils.timezone.now()

        for idx, question in enumerate(questions):
            q_type = question.get("type", "")
            # Only fetch open-ended questions
            if q_type != "open":
                continue

            question_id = question.get("id")
            question_text = question.get("question", f"Question {idx + 1}")

            # Fetch responses for this question
            responses_list = await sync_to_async(fetch_responses)(
                survey_id=str(survey.id),
                question_index=idx,
                question_id=question_id,
                start_date=start_date,
                end_date=end_date,
                team=self._team,
                limit=50,  # Limit responses per question
            )

            # Convert to SurveyAnalysisResponseItem objects
            response_items = [
                SurveyAnalysisResponseItem(
                    responseText=text,
                    isOpenEnded=True,
                )
                for text in responses_list
                if text and text.strip()
            ]

            if response_items:
                question_groups.append(
                    SurveyAnalysisQuestionGroup(
                        questionName=question_text,
                        questionId=question_id or str(idx),
                        responses=response_items,
                    )
                )

        return question_groups

    async def _arun_impl(self, survey_id: str | None = None) -> tuple[str, dict[str, Any]]:
        """
        Retrieve survey responses for the main agent to analyze.
        Returns the formatted responses so the agent can extract themes, sentiment, and insights.
        """
        try:
            # Try to get survey_id from argument first, then from context
            context = self.context or {}
            effective_survey_id = survey_id or context.get("survey_id")

            if not effective_survey_id:
                return (
                    "No survey ID provided. Please provide a survey_id or use the search tool to find a survey first.",
                    {
                        "error": "no_survey_id",
                        "details": "No survey_id argument provided and none found in context",
                    },
                )

            # Fetch the survey from database
            try:
                survey = await sync_to_async(Survey.objects.get)(id=effective_survey_id, team=self._team)
            except Survey.DoesNotExist:
                return f"Survey with ID '{effective_survey_id}' not found.", {
                    "error": "not_found",
                    "details": f"No survey found with ID '{effective_survey_id}' in your team.",
                }

            survey_name = survey.name

            # Fetch responses directly from database
            responses = await self._fetch_survey_responses(survey)

            if not responses:
                return (
                    f"No open-ended responses found in survey '{survey_name}'. The survey may not have open-ended questions or no responses yet.",
                    {
                        "survey_id": str(survey.id),
                        "survey_name": survey_name,
                        "response_count": 0,
                    },
                )

            total_response_count = sum(len(group.responses or []) for group in responses)

            if total_response_count == 0:
                return f"No open-ended responses found in survey '{survey_name}' to analyze.", {
                    "survey_id": str(survey.id),
                    "survey_name": survey_name,
                    "response_count": 0,
                }

            formatted_data = self._format_responses_for_analysis(responses)

            message = dedent(f"""
                Survey: "{survey_name}"
                Total open-ended responses: {total_response_count}

                {formatted_data}

                Please analyze these survey responses and provide:
                1. Key themes with example responses
                2. Overall sentiment (positive, negative, mixed, or neutral)
                3. Actionable insights
                4. Specific recommendations based on the feedback
            """).strip()

            return message, {
                "survey_id": str(survey.id),
                "survey_name": survey_name,
                "response_count": total_response_count,
            }

        except Exception as e:
            capture_exception(e, {"team_id": self._team.id, "user_id": self._user.id})
            return f"Failed to retrieve survey responses: {str(e)}", {"error": "retrieval_failed", "details": str(e)}