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.

fix(conversations): finish support drafts that end without json (#105707)

Alex V4e3c6fae08eb
diff --git a/products/conversations/backend/temporal/ai_reply/activities/draft.py b/products/conversations/backend/temporal/ai_reply/activities/draft.py
index 605bedd50854..c1aff0f649cb 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/draft.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/draft.py
@@ -1,10 +1,12 @@
from __future__ import annotations
+import json
from time import monotonic
from typing import Any
from uuid import UUID
import structlog
+from pydantic import ValidationError
from temporalio import activity
from posthog.sync import database_sync_to_async
@@ -18,6 +20,7 @@ from products.conversations.backend.playbook import compose_support_playbook, is
from products.conversations.backend.temporal.ai_reply.constants import (
BASE_DRAFT_SCOPES,
DIAGNOSTIC_SCOPES_PRESET,
+ DRAFT_ACTIVITY_MAX_ATTEMPTS,
DRAFT_MODEL,
DRAFT_POLL_SECONDS,
DRAFT_RUNTIME_ADAPTER,
@@ -35,17 +38,92 @@ from products.conversations.backend.temporal.ai_reply.constants import (
PUBLISHABLE_DRAFT_SCOPES,
TICKET_TYPE_HINTS,
)
-from products.conversations.backend.temporal.ai_reply.llms import anthropic_json_schema
+from products.conversations.backend.temporal.ai_reply.llms import llm_attempts
from products.conversations.backend.temporal.ai_reply.schemas import DraftInput, DraftOutput, SupportReplyDraft
from products.conversations.backend.temporal.helpers import (
get_or_create_support_sandbox_env,
resolve_user_id_for_support,
)
from products.tasks.backend.facade import api as tasks_facade
-from products.tasks.backend.facade.agents import MultiTurnSession
+from products.tasks.backend.facade.agents import EmptyAgentTurnError, MultiTurnSession
logger = structlog.get_logger(__name__)
+_DRAFT_JSON_NUDGE = (
+ "You ended the turn before the draft JSON. Do not wait and do not send a status update. "
+ "Return only the JSON object now, using what you already have."
+)
+# The first poll uses DRAFT_POLL_SECONDS. The nudge can poll twice on an empty reply, and both
+# polls together must fit inside the draft activity's start_to_close timeout.
+_DRAFT_NUDGE_POLL_SECONDS = 90
+
+
+class DraftNotProducedError(RuntimeError):
+ """The draft agent gave no usable draft. Raised only while a retry attempt remains."""
+
+
+def _parse_draft(text: str | None) -> SupportReplyDraft | None:
+ """Return the last JSON object in `text` that is a valid draft.
+
+ The agent may quote an example or echo ticket JSON before its answer, so the final
+ object wins over the first one.
+ """
+ if not text:
+ return None
+ decoder = json.JSONDecoder()
+ candidates: list[Any] = []
+ start = 0
+ while (brace := text.find("{", start)) != -1:
+ try:
+ value, _ = decoder.raw_decode(text, brace)
+ except json.JSONDecodeError:
+ value = None
+ if isinstance(value, dict):
+ candidates.append(value)
+ start = brace + 1
+ for candidate in reversed(candidates):
+ try:
+ return SupportReplyDraft.model_validate(candidate)
+ except ValidationError:
+ continue
+ return None
+
+
+def _give_up(reason: str) -> SupportReplyDraft:
+ """Retry while an attempt remains. On the last attempt, return a draft that blocks auto-send.
+
+ A raise on the last attempt fails the workflow before it records a result, which leaves the
+ ticket in_progress.
+ """
+ if llm_attempts() < DRAFT_ACTIVITY_MAX_ATTEMPTS:
+ raise DraftNotProducedError(reason)
+ logger.warning("support_draft_blocked_last_attempt", reason=reason)
+ return SupportReplyDraft(
+ reply="",
+ citations=[],
+ confidence=0.0,
+ verdict="blocked_on_knowledge",
+ investigation_summary=reason,
+ )
+
+
+async def _draft_from_session(session: MultiTurnSession, first_text: str) -> SupportReplyDraft:
+ draft = _parse_draft(first_text)
+ if draft is not None:
+ return draft
+ logger.warning("support_draft_no_json_nudging", task_run_id=str(session.task_run.id))
+ session.max_poll_seconds = _DRAFT_NUDGE_POLL_SECONDS
+ try:
+ followup = await session.send_followup_raw(_DRAFT_JSON_NUDGE, label="support draft json")
+ except Exception:
+ logger.warning("support_draft_json_nudge_failed", task_run_id=str(session.task_run.id), exc_info=True)
+ return _give_up("The draft agent failed while it was asked for the draft JSON.")
+ draft = _parse_draft(followup)
+ if draft is not None:
+ return draft
+ return _give_up("The draft agent ended without a JSON object.")
+
+
_TEAM_DOCS_SOURCE_TYPES = frozenset({"url", "file"})
@@ -312,29 +390,38 @@ INSTRUCTIONS:
- The KNOWLEDGE BASE RESULTS above are a starting point, not a ceiling. Use the tools listed in TOOLS YOU HAVE ON THIS RUN to search for additional information.
- Ground your reply in sources. Include citations (chunk_id UUIDs or doc URLs) and populate `sources` with the supporting excerpts so the reply can be validated.
- Do NOT make up information -- only use what your tools return.
+- Do not end the turn while a tool or search is still running. Wait for it to finish. A status update is not a finished draft.
Return your response as a JSON object with keys: reply, citations, confidence (a number from 0 to 1, never a word), sources (a list of {{ref, excerpt}}), verdict, clarifying_questions, investigation_summary, unknowns."""
session: MultiTurnSession | None = None
started = monotonic()
try:
- session, result = await MultiTurnSession.start(
- prompt,
- context,
- model=SupportReplyDraft,
- step_name="support_reply",
- origin_product=tasks_facade.TaskOriginProduct.SUPPORT_REPLY,
- mcp_builtin_agent_key="support",
- internal=True,
- max_poll_seconds=DRAFT_POLL_SECONDS,
- output_schema=anthropic_json_schema(SupportReplyDraft),
- )
+ try:
+ session, first_text = await MultiTurnSession.start_raw(
+ prompt,
+ context,
+ step_name="support_reply",
+ origin_product=tasks_facade.TaskOriginProduct.SUPPORT_REPLY,
+ mcp_builtin_agent_key="support",
+ internal=True,
+ max_poll_seconds=DRAFT_POLL_SECONDS,
+ )
+ except EmptyAgentTurnError:
+ # start_raw already ended the run, so there is no session to nudge.
+ logger.warning("support_draft_empty_first_turn", team_id=input.team_id)
+ result = _give_up("The draft agent ended the turn with no reply.")
+ except Exception:
+ logger.exception("support_draft_agent_failed", team_id=input.team_id)
+ result = _give_up("The draft agent failed before it returned a reply.")
+ else:
+ result = await _draft_from_session(session, first_text)
return DraftOutput(
reply=result.reply,
citations=result.citations,
confidence=result.confidence,
sources=[{"ref": s.ref, "excerpt": s.excerpt[:MAX_EXCERPT_CHARS]} for s in result.sources[:MAX_SOURCES]],
- task_run_id=str(session.task_run.id),
+ task_run_id=str(session.task_run.id) if session is not None else "",
sandbox_seconds=monotonic() - started,
verdict=result.verdict if result.verdict in DRAFT_VERDICTS else "blocked_on_knowledge",
clarifying_questions=[q for q in result.clarifying_questions if q][:MAX_CLARIFYING_QUESTIONS],
diff --git a/products/conversations/backend/temporal/ai_reply/constants.py b/products/conversations/backend/temporal/ai_reply/constants.py
index b58fe46c47ab..e788215a06bf 100644
--- a/products/conversations/backend/temporal/ai_reply/constants.py
+++ b/products/conversations/backend/temporal/ai_reply/constants.py
@@ -40,6 +40,8 @@ LEARNED_CHUNK_NOTE = (
PUBLISHABLE_TICKET_TYPES = {"how_to"}
RETRIEVE_LIMIT = 15
DRAFT_POLL_SECONDS = 900
+# The draft activity returns a blocked draft on its last attempt instead of raising.
+DRAFT_ACTIVITY_MAX_ATTEMPTS = 2
WIDEN_RADIUS = 3
# Temporal records every activity input/output in workflow history (per-payload limit ~2 MiB,
diff --git a/products/conversations/backend/temporal/pipeline.py b/products/conversations/backend/temporal/pipeline.py
index 680ea061c849..f935d5ceceea 100644
--- a/products/conversations/backend/temporal/pipeline.py
+++ b/products/conversations/backend/temporal/pipeline.py
@@ -34,6 +34,7 @@ with workflow.unsafe.imports_passed_through():
AI_REPLY_TRACE_NAMESPACE,
BLOCKER_AWARE_LOOP_PATCH,
DEFER_KNOWLEDGE_GAPS_UNTIL_RESOLUTION_PATCH,
+ DRAFT_ACTIVITY_MAX_ATTEMPTS,
LEGACY_MAX_ATTEMPTS,
MAX_ATTEMPTS,
MAX_CLARIFICATION_ROUNDS,
@@ -383,7 +384,7 @@ class SupportReplyWorkflow:
custom_instructions=ctx_output.custom_instructions,
),
start_to_close_timeout=timedelta(minutes=20),
- retry_policy=RetryPolicy(maximum_attempts=2),
+ retry_policy=RetryPolicy(maximum_attempts=DRAFT_ACTIVITY_MAX_ATTEMPTS),
),
)
sandbox_seconds += draft_output.sandbox_seconds or 0.0
diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.py
index ae9a7e15ea9b..d1e6afd9fd60 100644
--- a/products/conversations/backend/temporal/tests/test_pipeline.py
+++ b/products/conversations/backend/temporal/tests/test_pipeline.py
@@ -17,7 +17,7 @@ from posthog.models import Organization, Team
from products.conversations.backend.models.ticket import Ticket
from products.conversations.backend.temporal.ai_reply.activities.clarify import _clarify_sync
from products.conversations.backend.temporal.ai_reply.activities.classify import _classify
-from products.conversations.backend.temporal.ai_reply.activities.draft import _draft_async
+from products.conversations.backend.temporal.ai_reply.activities.draft import DraftNotProducedError, _draft_async
from products.conversations.backend.temporal.ai_reply.activities.persist_knowledge_gap import (
support_persist_knowledge_gap_activity,
)
@@ -60,7 +60,6 @@ from products.conversations.backend.temporal.ai_reply.schemas import (
ReviewReplyOutput,
SafetyFilterInput,
SafetyFilterOutput,
- SupportReplyDraft,
SupportReplyInput,
ValidateInput,
ValidateOutput,
@@ -80,6 +79,7 @@ from products.conversations.backend.temporal.pipeline import (
support_safety_filter_activity,
support_validate_activity,
)
+from products.tasks.backend.facade.agents import EmptyAgentTurnError
@pytest.fixture
@@ -1983,6 +1983,9 @@ class TestUtilityCallsUseStructuredOutput:
assert fmt["schema"]["additionalProperties"] is False
+_OK_DRAFT_JSON = '{"reply": "ok", "citations": [], "confidence": 0.0, "sources": [], "verdict": "answerable"}'
+
+
def _mock_gateway_client(text: str) -> MagicMock:
"""Build a mock Anthropic gateway client whose messages.create returns `text`."""
block = MagicMock()
@@ -2048,14 +2051,13 @@ class TestUntrustedTicketGuard:
async def fake_start(prompt, context, **kwargs):
captured["prompt"] = prompt
- result = SupportReplyDraft(reply="ok", citations=[], confidence=0.0, sources=[])
- return AsyncMock(), result
+ return AsyncMock(), _OK_DRAFT_JSON
with (
patch(f"{DRAFT_MODULE}._hydrate_chunks", return_value=[]),
patch(f"{DRAFT_MODULE}.resolve_user_id_for_support", return_value=1),
patch(f"{DRAFT_MODULE}.get_or_create_support_sandbox_env", return_value="env-1"),
- patch(f"{DRAFT_MODULE}.MultiTurnSession.start", new=AsyncMock(side_effect=fake_start)),
+ patch(f"{DRAFT_MODULE}.MultiTurnSession.start_raw", new=AsyncMock(side_effect=fake_start)),
):
await _draft_async(DraftInput(team_id=1, ticket_context=injection, chunk_ids=[]))
@@ -2073,22 +2075,18 @@ class TestUntrustedTicketGuard:
async def fake_start(prompt, context, **kwargs):
captured["prompt"] = prompt
- captured["output_schema"] = kwargs["output_schema"]
- result = SupportReplyDraft(reply="ok", citations=[], confidence=0.0, sources=[])
- return AsyncMock(), result
+ return AsyncMock(), _OK_DRAFT_JSON
with (
patch(f"{DRAFT_MODULE}._hydrate_chunks", return_value=[]),
patch(f"{DRAFT_MODULE}.resolve_user_id_for_support", return_value=1),
patch(f"{DRAFT_MODULE}.get_or_create_support_sandbox_env", return_value="env-1"),
- patch(f"{DRAFT_MODULE}.MultiTurnSession.start", new=AsyncMock(side_effect=fake_start)),
+ patch(f"{DRAFT_MODULE}.MultiTurnSession.start_raw", new=AsyncMock(side_effect=fake_start)),
):
output = await _draft_async(DraftInput(team_id=1, ticket_context="how do I install", chunk_ids=[]))
- schema = captured["output_schema"]
- assert schema["additionalProperties"] is False
- assert schema["properties"]["confidence"]["type"] == "number"
prompt = captured["prompt"]
+ assert "Do not end the turn while a tool or search is still running" in prompt
assert "PLAN first" in prompt
assert "blocked_on_customer" in prompt
assert "blocked_on_knowledge" in prompt
@@ -2103,14 +2101,13 @@ class TestUntrustedTicketGuard:
async def fake_start(prompt, context, **kwargs):
captured["prompt"] = prompt
- result = SupportReplyDraft(reply="ok", citations=[], confidence=0.0, sources=[])
- return AsyncMock(), result
+ return AsyncMock(), _OK_DRAFT_JSON
with (
patch(f"{DRAFT_MODULE}._hydrate_chunks", return_value=[]),
patch(f"{DRAFT_MODULE}.resolve_user_id_for_support", return_value=1),
patch(f"{DRAFT_MODULE}.get_or_create_support_sandbox_env", return_value="env-1"),
- patch(f"{DRAFT_MODULE}.MultiTurnSession.start", new=AsyncMock(side_effect=fake_start)),
+ patch(f"{DRAFT_MODULE}.MultiTurnSession.start_raw", new=AsyncMock(side_effect=fake_start)),
):
await _draft_async(
DraftInput(
@@ -2126,6 +2123,83 @@ class TestUntrustedTicketGuard:
assert "If a fact you need can only come from the customer" not in captured["prompt"]
+_EMPTY_TURN = EmptyAgentTurnError("empty", total_lines=1, printed_lines=0)
+
+
+class TestDraftWithoutJson:
+ async def _draft(self, *, attempt: int, start_raw: AsyncMock) -> DraftOutput:
+ with (
+ patch(f"{DRAFT_MODULE}._hydrate_chunks", return_value=[]),
+ patch(f"{DRAFT_MODULE}.resolve_user_id_for_support", return_value=1),
+ patch(f"{DRAFT_MODULE}.get_or_create_support_sandbox_env", return_value="env-1"),
+ patch(f"{DRAFT_MODULE}.llm_attempts", return_value=attempt),
+ patch(f"{DRAFT_MODULE}.MultiTurnSession.start_raw", new=start_raw),
+ ):
+ return await _draft_async(DraftInput(team_id=1, ticket_context="how do I install", chunk_ids=[]))
+
+ @staticmethod
+ def _session(followup: object) -> MagicMock:
+ session = MagicMock()
+ session.end = AsyncMock()
+ if isinstance(followup, Exception):
+ session.send_followup_raw = AsyncMock(side_effect=followup)
+ else:
+ session.send_followup_raw = AsyncMock(return_value=followup)
+ return session
+
+ @parameterized.expand(
+ [
+ ("first_turn_json", _OK_DRAFT_JSON, None, "ok"),
+ (
+ "example_json_before_answer",
+ '{"reply": "example", "citations": [], "confidence": 0.9} then ' + _OK_DRAFT_JSON,
+ None,
+ "ok",
+ ),
+ ("nudge_returns_json", "I'll wait for the background search", _OK_DRAFT_JSON, "ok"),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_uses_the_final_draft_json(
+ self, _name: str, first_text: str, followup: object, expected: str
+ ) -> None:
+ session = self._session(followup)
+
+ output = await self._draft(attempt=1, start_raw=AsyncMock(return_value=(session, first_text)))
+
+ assert (output.reply, output.verdict) == (expected, "answerable")
+ session.end.assert_awaited_once()
+
+ @parameterized.expand(
+ [
+ ("nudge_still_prose", "I'll wait for the background search", "still waiting"),
+ ("nudge_empty", "", _EMPTY_TURN),
+ ("nudge_crash", "I'll wait", RuntimeError("Agent server crashed")),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_no_draft_retries_then_blocks(self, _name: str, first_text: str, followup: object) -> None:
+ with pytest.raises(DraftNotProducedError):
+ await self._draft(attempt=1, start_raw=AsyncMock(return_value=(self._session(followup), first_text)))
+
+ output = await self._draft(attempt=2, start_raw=AsyncMock(return_value=(self._session(followup), first_text)))
+ assert (output.reply, output.verdict, output.confidence) == ("", "blocked_on_knowledge", 0.0)
+
+ @parameterized.expand(
+ [
+ ("empty_first_turn", _EMPTY_TURN),
+ ("agent_crash", RuntimeError("Agent server crashed: Internal error")),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_failed_first_turn_retries_then_blocks(self, _name: str, error: Exception) -> None:
+ with pytest.raises(DraftNotProducedError):
+ await self._draft(attempt=1, start_raw=AsyncMock(side_effect=error))
+
+ output = await self._draft(attempt=2, start_raw=AsyncMock(side_effect=error))
+ assert (output.verdict, output.confidence, output.task_run_id) == ("blocked_on_knowledge", 0.0, "")
+
+
class TestDiagnosticScopes:
"""Customer-data scopes are granted only when the org opted in AND the reply won't be
auto-sent to the (untrusted) author. `auto_publishable` mirrors persist_reply's publish gate
@@ -2147,14 +2221,13 @@ class TestDiagnosticScopes:
captured["prompt"] = prompt
captured["scopes"] = context.posthog_mcp_scopes
captured["exclude_tools"] = context.mcp_exclude_tools
- result = SupportReplyDraft(reply="ok", citations=[], confidence=0.0, sources=[])
- return AsyncMock(), result
+ return AsyncMock(), _OK_DRAFT_JSON
with (
patch(f"{DRAFT_MODULE}._hydrate_chunks", return_value=[]),
patch(f"{DRAFT_MODULE}.resolve_user_id_for_support", return_value=1),
patch(f"{DRAFT_MODULE}.get_or_create_support_sandbox_env", return_value="env-1"),
- patch(f"{DRAFT_MODULE}.MultiTurnSession.start", new=AsyncMock(side_effect=fake_start)),
+ patch(f"{DRAFT_MODULE}.MultiTurnSession.start_raw", new=AsyncMock(side_effect=fake_start)),
):
await _draft_async(
DraftInput(
@@ -2322,14 +2395,13 @@ class TestDiagnosticScopes:
async def fake_start(prompt, context, **kwargs):
captured["prompt"] = prompt
- result = SupportReplyDraft(reply="ok", citations=[], confidence=0.0, sources=[])
- return AsyncMock(), result
+ return AsyncMock(), _OK_DRAFT_JSON
with (
patch(f"{DRAFT_MODULE}._hydrate_chunks", return_value=[]),
patch(f"{DRAFT_MODULE}.resolve_user_id_for_support", return_value=1),
patch(f"{DRAFT_MODULE}.get_or_create_support_sandbox_env", return_value="env-1"),
- patch(f"{DRAFT_MODULE}.MultiTurnSession.start", new=AsyncMock(side_effect=fake_start)),
+ patch(f"{DRAFT_MODULE}.MultiTurnSession.start_raw", new=AsyncMock(side_effect=fake_start)),
):
await _draft_async(
DraftInput(