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): stop failed drafts leaving tickets processing (#105049)

Alex Vd31f450a47da
diff --git a/products/conversations/backend/temporal/ai_reply/activities/classify.py b/products/conversations/backend/temporal/ai_reply/activities/classify.py
index 918724c3fdb9..9768cbddf5af 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/classify.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/classify.py
@@ -2,8 +2,10 @@ from __future__ import annotations
import json as json_module
from dataclasses import replace
+from typing import Literal
import structlog
+from pydantic import BaseModel, Field
from temporalio import activity
from posthog.llm.gateway_client import get_async_anthropic_gateway_client
@@ -11,6 +13,7 @@ from posthog.temporal.common.heartbeat import Heartbeater
from products.conversations.backend.temporal.ai_reply.constants import TICKET_TYPES, UTILITY_MODEL
from products.conversations.backend.temporal.ai_reply.llms import (
+ anthropic_output_config,
anthropic_text,
create_message,
llm_attempts,
@@ -22,6 +25,12 @@ from products.conversations.backend.temporal.ai_reply.schemas import ClassifyInp
logger = structlog.get_logger(__name__)
+class ClassifyResult(BaseModel):
+ ticket_type: Literal["how_to", "diagnostic", "account_billing", "bug", "unactionable"]
+ needs_diagnostics: bool = Field(description="True only when answering requires the customer's own data")
+ seed_queries: list[str] = Field(description="2-4 concise search queries; empty for unactionable")
+
+
@activity.defn
async def support_classify_activity(input: ClassifyInput) -> ClassifyOutput:
"""One-shot LLM triage of a ticket into a type + diagnostics flag + seed search queries."""
@@ -61,6 +70,7 @@ classify the customer's support question."""
max_tokens=512,
system=system,
messages=[{"role": "user", "content": user_content}],
+ **anthropic_output_config(ClassifyResult),
**tracing_kwargs(input.trace_id, input.ticket_id),
)
content = anthropic_text(message)
diff --git a/products/conversations/backend/temporal/ai_reply/activities/draft.py b/products/conversations/backend/temporal/ai_reply/activities/draft.py
index 82ca29c3f4de..605bedd50854 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/draft.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/draft.py
@@ -35,6 +35,7 @@ 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.schemas import DraftInput, DraftOutput, SupportReplyDraft
from products.conversations.backend.temporal.helpers import (
get_or_create_support_sandbox_env,
@@ -312,7 +313,7 @@ INSTRUCTIONS:
- 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.
-Return your response as a JSON object with keys: reply, citations, confidence, sources (a list of {{ref, excerpt}}), verdict, clarifying_questions, investigation_summary, unknowns."""
+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()
@@ -326,6 +327,7 @@ Return your response as a JSON object with keys: reply, citations, confidence, s
mcp_builtin_agent_key="support",
internal=True,
max_poll_seconds=DRAFT_POLL_SECONDS,
+ output_schema=anthropic_json_schema(SupportReplyDraft),
)
return DraftOutput(
reply=result.reply,
diff --git a/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py b/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py
index bc87912a380e..a32c7ba302d6 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/refine_queries.py
@@ -1,7 +1,9 @@
from __future__ import annotations
+import json as json_module
from dataclasses import replace
+from pydantic import BaseModel, Field
from temporalio import activity
from posthog.llm.gateway_client import get_async_anthropic_gateway_client
@@ -9,14 +11,50 @@ from posthog.temporal.common.heartbeat import Heartbeater
from products.conversations.backend.temporal.ai_reply.constants import TICKET_TYPE_HINTS, UTILITY_MODEL
from products.conversations.backend.temporal.ai_reply.llms import (
+ anthropic_output_config,
anthropic_text,
create_message,
llm_attempts,
+ strip_json_fence,
tracing_kwargs,
)
from products.conversations.backend.temporal.ai_reply.schemas import RefineQueriesInput, RefineQueriesOutput
+class RefineQueriesResult(BaseModel):
+ queries: list[str] = Field(description="2-4 concise search queries")
+
+
+def _queries_from_reply(content: str) -> list[str]:
+ """Read search queries from a model reply.
+
+ A JSON object with a bad `queries` shape must not become the search string.
+ One query per line stays for replies that are not JSON.
+ """
+ stripped = content.strip()
+ try:
+ loaded = json_module.loads(strip_json_fence(stripped))
+ except json_module.JSONDecodeError:
+ return [line.strip() for line in stripped.split("\n") if line.strip()]
+ if isinstance(loaded, list):
+ items: object = loaded
+ elif isinstance(loaded, dict):
+ raw = loaded.get("queries", [])
+ items = [raw] if isinstance(raw, str) else raw
+ else:
+ items = []
+ if not isinstance(items, list):
+ return []
+ queries: list[str] = []
+ for item in items:
+ if not isinstance(item, str):
+ continue
+ text = item.strip()
+ if text:
+ queries.append(text)
+ return queries
+
+
@activity.defn
async def support_refine_queries_activity(input: RefineQueriesInput) -> RefineQueriesOutput:
"""Use a lightweight LLM to generate search queries from ticket context + missing gaps."""
@@ -29,7 +67,7 @@ async def _refine_queries(input: RefineQueriesInput) -> RefineQueriesOutput:
system = f"""You are a search query generator for a customer support knowledge base.
Given a customer ticket and optionally a list of missing information from a previous attempt,
generate 2-4 concise search queries that would find the most relevant documentation.
-Return ONLY the queries, one per line. No numbering, no explanation.
+Return a JSON object with key "queries": a list of those query strings. No numbering, no explanation.
Ticket type: {input.ticket_type}. {type_hint}
@@ -55,10 +93,11 @@ derive search queries about the customer's support question."""
max_tokens=512,
system=system,
messages=[{"role": "user", "content": "\n".join(user_parts)}],
+ **anthropic_output_config(RefineQueriesResult),
**tracing_kwargs(input.trace_id, input.ticket_id),
)
content = anthropic_text(message)
- queries = [line.strip() for line in content.strip().split("\n") if line.strip()]
+ queries = _queries_from_reply(content)
# On the first attempt (no `missing` yet) lead with the triage seeds so retrieval starts
# from the classifier's hypothesis, then dedupe the LLM's own queries after them.
if input.seed_queries and not input.missing:
diff --git a/products/conversations/backend/temporal/ai_reply/activities/review_reply.py b/products/conversations/backend/temporal/ai_reply/activities/review_reply.py
index c369f84fc7bd..b5aed7eee87f 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/review_reply.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/review_reply.py
@@ -12,6 +12,7 @@ from posthog.temporal.common.heartbeat import Heartbeater
from products.conversations.backend.temporal.ai_reply.constants import MAX_SOURCES, VALIDATOR_MODEL
from products.conversations.backend.temporal.ai_reply.llms import (
+ anthropic_output_config,
anthropic_text,
create_message,
llm_attempts,
@@ -109,6 +110,7 @@ TICKET TYPE: {input.ticket_type}"""
max_tokens=512,
system=REPLY_REVIEW_SYSTEM_PROMPT,
messages=[{"role": "user", "content": user_content}],
+ **anthropic_output_config(ReplyReviewResult),
**tracing_kwargs(input.trace_id, input.ticket_id),
)
content = anthropic_text(message)
diff --git a/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py b/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py
index 925f5a7214a7..de0af5831d8c 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/safety_filter.py
@@ -12,6 +12,7 @@ from posthog.temporal.common.heartbeat import Heartbeater
from products.conversations.backend.temporal.ai_reply.constants import MAX_SAFETY_REVIEWED_CHARS, UTILITY_MODEL
from products.conversations.backend.temporal.ai_reply.llms import (
+ anthropic_output_config,
anthropic_text,
create_message,
llm_attempts,
@@ -133,6 +134,7 @@ async def _safety_filter(input: SafetyFilterInput) -> SafetyFilterOutput:
max_tokens=512,
system=SAFETY_FILTER_SYSTEM_PROMPT,
messages=[{"role": "user", "content": user_content}],
+ **anthropic_output_config(SafetyFilterResult),
**tracing_kwargs(input.trace_id, input.ticket_id),
)
content = anthropic_text(message)
diff --git a/products/conversations/backend/temporal/ai_reply/activities/validate.py b/products/conversations/backend/temporal/ai_reply/activities/validate.py
index 84c1d0122cee..37a995948f97 100644
--- a/products/conversations/backend/temporal/ai_reply/activities/validate.py
+++ b/products/conversations/backend/temporal/ai_reply/activities/validate.py
@@ -2,8 +2,10 @@ from __future__ import annotations
import json as json_module
from dataclasses import replace
+from typing import Literal
import structlog
+from pydantic import BaseModel, Field
from temporalio import activity
from posthog.llm.gateway_client import get_async_anthropic_gateway_client
@@ -21,17 +23,26 @@ from products.conversations.backend.temporal.ai_reply.constants import (
VALIDATOR_MODEL,
)
from products.conversations.backend.temporal.ai_reply.llms import (
+ anthropic_output_config,
anthropic_text,
create_message,
llm_attempts,
strip_json_fence,
tracing_kwargs,
)
-from products.conversations.backend.temporal.ai_reply.schemas import ValidateInput, ValidateOutput
+from products.conversations.backend.temporal.ai_reply.schemas import ValidateInput, ValidateOutput, coerce_unit_interval
logger = structlog.get_logger(__name__)
+class ValidateResult(BaseModel):
+ grounded: bool
+ coverage: float = Field(description="Fraction of the customer's question the reply addresses, from 0 to 1")
+ confidence: float = Field(description="Confidence the reply is correct and complete, from 0 to 1")
+ missing: list[str] = Field(description="Topics the customer asked about that the reply or chunks do not cover")
+ blocker: Literal["none", "customer_info", "knowledge", "contradiction"]
+
+
@activity.defn
async def support_validate_activity(input: ValidateInput) -> ValidateOutput:
"""Validate the draft reply against the source chunks for groundedness and coverage."""
@@ -89,6 +100,7 @@ CITED CHUNKS:
max_tokens=1024,
system=system,
messages=[{"role": "user", "content": user_content}],
+ **anthropic_output_config(ValidateResult),
**tracing_kwargs(input.trace_id, input.ticket_id),
)
content = anthropic_text(message)
@@ -100,8 +112,8 @@ CITED CHUNKS:
blocker = "knowledge"
return ValidateOutput(
grounded=bool(parsed.get("grounded", False)),
- coverage=float(parsed.get("coverage", 0.0)),
- confidence=float(parsed.get("confidence", 0.0)),
+ coverage=coerce_unit_interval(parsed.get("coverage", 0.0)),
+ confidence=coerce_unit_interval(parsed.get("confidence", 0.0)),
missing=list(parsed.get("missing", [])),
blocker=blocker,
)
diff --git a/products/conversations/backend/temporal/ai_reply/llms.py b/products/conversations/backend/temporal/ai_reply/llms.py
index ac213f1233b1..7ff5e66606a6 100644
--- a/products/conversations/backend/temporal/ai_reply/llms.py
+++ b/products/conversations/backend/temporal/ai_reply/llms.py
@@ -3,6 +3,8 @@ from __future__ import annotations
from typing import Any
from anthropic import APIError
+from anthropic.lib._parse._transform import transform_schema
+from pydantic import BaseModel
from temporalio import activity
from temporalio.exceptions import ApplicationError
@@ -14,6 +16,19 @@ def anthropic_text(message: Any) -> str:
return "".join(block.text for block in message.content if getattr(block, "type", None) == "text")
+def anthropic_json_schema(model: type[BaseModel]) -> dict[str, Any]:
+ """Schema Anthropic's structured-output grammar accepts.
+
+ A raw ``model_json_schema()`` is rejected (``additionalProperties``, defaults). The grammar
+ then forces a number field to be a number, so a token like ``medium`` cannot be emitted.
+ """
+ return transform_schema(model)
+
+
+def anthropic_output_config(model: type[BaseModel]) -> dict[str, Any]:
+ return {"output_config": {"format": {"type": "json_schema", "schema": anthropic_json_schema(model)}}}
+
+
def tracing_kwargs(trace_id: str, ticket_id: str) -> dict[str, Any]:
"""Per-ticket gateway attribution to splat into a `create_message(...)` call.
diff --git a/products/conversations/backend/temporal/ai_reply/schemas.py b/products/conversations/backend/temporal/ai_reply/schemas.py
index 07208a3c15a7..55108f9e7088 100644
--- a/products/conversations/backend/temporal/ai_reply/schemas.py
+++ b/products/conversations/backend/temporal/ai_reply/schemas.py
@@ -7,6 +7,7 @@ structured LLM response schemas used by the draft sandbox step.
from __future__ import annotations
+import math
from dataclasses import dataclass, field
from typing import Any, Literal, TypeVar
@@ -281,6 +282,28 @@ class PersistKnowledgeGapInput:
outcome: str = ""
+def coerce_unit_interval(value: object) -> float:
+ """Map a model score onto 0–1. Anything else becomes 0.
+
+ The structured-output grammar only checks that the field is a number, so ``80``
+ or ``"medium"`` still arrives. ``80`` would clear the auto-send floor.
+ """
+ if isinstance(value, bool) or (isinstance(value, str) and not value.strip()):
+ return 0.0
+ if isinstance(value, str):
+ try:
+ number = float(value.strip())
+ except ValueError:
+ return 0.0
+ elif isinstance(value, (int, float)):
+ number = float(value)
+ else:
+ return 0.0
+ if not math.isfinite(number) or number < 0 or number > 1:
+ return 0.0
+ return number
+
+
class SupportReplySource(BaseModel):
ref: str = Field(description="The citation reference: a chunk_id UUID or a documentation URL")
excerpt: str = Field(description="The exact text from this source that supports the reply")
@@ -311,6 +334,12 @@ class SupportReplyDraft(BaseModel):
description="Facts that remain unknown after the investigation",
)
+ @field_validator("confidence", mode="before")
+ @classmethod
+ def _coerce_confidence(cls, value: object) -> float:
+ # A bad token used to raise here and leave the ticket in_progress.
+ return coerce_unit_interval(value)
+
@field_validator("verdict", mode="before")
@classmethod
def _coerce_verdict(cls, value: object) -> str:
diff --git a/products/conversations/backend/temporal/tests/test_gate.py b/products/conversations/backend/temporal/tests/test_gate.py
index 887d665dc24d..7964ea7b221d 100644
--- a/products/conversations/backend/temporal/tests/test_gate.py
+++ b/products/conversations/backend/temporal/tests/test_gate.py
@@ -26,6 +26,26 @@ class TestFailClosedDefaults(SimpleTestCase):
draft = SupportReplyDraft(reply="ok", citations=[], confidence=0.9, verdict="idk")
assert draft.verdict == "blocked_on_knowledge"
+ @parameterized.expand(
+ [
+ ("medium",),
+ ("high",),
+ ("",),
+ (None,),
+ (80,),
+ ("80",),
+ (1.5,),
+ (True,),
+ ]
+ )
+ def test_non_numeric_confidence_fails_closed(self, raw: object) -> None:
+ draft = SupportReplyDraft.model_validate({"reply": "ok", "citations": [], "confidence": raw})
+ assert draft.confidence == 0.0
+
+ def test_numeric_confidence_string_is_kept(self) -> None:
+ draft = SupportReplyDraft.model_validate({"reply": "ok", "citations": [], "confidence": "0.85"})
+ assert draft.confidence == 0.85
+
def test_activity_defaults_do_not_auto_send(self):
draft = DraftOutput(reply="Looks right.", citations=[], confidence=0.9)
validate = ValidateOutput(grounded=True, coverage=0.9, confidence=0.9, missing=[])
diff --git a/products/conversations/backend/temporal/tests/test_pipeline.py b/products/conversations/backend/temporal/tests/test_pipeline.py
index 20a51f9bd137..ae9a7e15ea9b 100644
--- a/products/conversations/backend/temporal/tests/test_pipeline.py
+++ b/products/conversations/backend/temporal/tests/test_pipeline.py
@@ -1,6 +1,7 @@
from __future__ import annotations
from collections.abc import Callable, Sequence
+from contextlib import ExitStack
from typing import Any
import pytest
@@ -1939,6 +1940,49 @@ class TestStripJsonFence:
assert _strip_json_fence(input_text) == expected
+class TestUtilityCallsUseStructuredOutput:
+ @parameterized.expand(
+ [
+ ("classify", CLASSIFY_MODULE, "classify"),
+ ("refine", REFINE_QUERIES_MODULE, "refine"),
+ ("validate", VALIDATE_MODULE, "validate"),
+ ("safety", SAFETY_FILTER_MODULE, "safety"),
+ ("review", REVIEW_REPLY_MODULE, "review"),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_sends_json_schema(self, _name: str, module: str, kind: str) -> None:
+ client = _mock_gateway_client("{}")
+ with ExitStack() as stack:
+ stack.enter_context(patch(f"{module}.get_async_anthropic_gateway_client", return_value=client))
+ if kind == "validate":
+ stack.enter_context(patch(f"{VALIDATE_MODULE}._hydrate_chunks", return_value=[]))
+ if kind == "classify":
+ await _classify(ClassifyInput(team_id=1, ticket_context="how do I install"))
+ elif kind == "refine":
+ await _refine_queries(RefineQueriesInput(team_id=1, ticket_context="how do I install"))
+ elif kind == "validate":
+ await _validate(
+ ValidateInput(
+ team_id=1,
+ ticket_context="how do I install",
+ reply="Use the docs.",
+ citations=[],
+ chunk_ids=[],
+ )
+ )
+ elif kind == "safety":
+ await _safety_filter(SafetyFilterInput(team_id=1, ticket_context="how do I install"))
+ else:
+ await _review_reply(
+ ReviewReplyInput(team_id=1, ticket_context="how do I install", reply="Use the docs.")
+ )
+
+ fmt = client.messages.create.call_args.kwargs["output_config"]["format"]
+ assert fmt["type"] == "json_schema"
+ assert fmt["schema"]["additionalProperties"] is False
+
+
def _mock_gateway_client(text: str) -> MagicMock:
"""Build a mock Anthropic gateway client whose messages.create returns `text`."""
block = MagicMock()
@@ -1951,6 +1995,29 @@ def _mock_gateway_client(text: str) -> MagicMock:
return client
+class TestRefineQueryParse:
+ @parameterized.expand(
+ [
+ ("lines", "query one\nquery two", [], ["query one", "query two"]),
+ ("json_queries", '{"queries": ["install", "sdk"]}', [], ["install", "sdk"]),
+ ("json_string_field", '{"queries": "install"}', [], ["install"]),
+ ("empty_object", "{}", [], ["help"]),
+ ("empty_object_keeps_seeds", "{}", ["setup"], ["setup"]),
+ ("json_array", '["install", "sdk"]', [], ["install", "sdk"]),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_malformed_json_is_not_a_search_query(
+ self, _name: str, text: str, seeds: list[str], expected: list[str]
+ ) -> None:
+ client = _mock_gateway_client(text)
+ with patch(f"{REFINE_QUERIES_MODULE}.get_async_anthropic_gateway_client", return_value=client):
+ result = await _refine_queries(
+ RefineQueriesInput(team_id=1, ticket_context="how do I install", seed_queries=seeds)
+ )
+ assert result.queries == expected
+
+
class TestUntrustedTicketGuard:
"""Ticket content is attacker-controlled (public widget/email). These guard against the
injection-hardening being silently dropped again: untrusted ticket text must stay wrapped
@@ -2002,10 +2069,11 @@ class TestUntrustedTicketGuard:
@pytest.mark.asyncio
async def test_draft_prompt_requires_plan_and_verdict(self):
- captured: dict[str, str] = {}
+ captured: dict[str, Any] = {}
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
@@ -2017,6 +2085,9 @@ class TestUntrustedTicketGuard:
):
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 "PLAN first" in prompt
assert "blocked_on_customer" in prompt
@@ -2592,6 +2663,15 @@ class TestValidateActivity:
[],
"knowledge",
),
+ (
+ "percent_style_scores",
+ '{"grounded": true, "coverage": 80, "confidence": 90, "missing": [], "blocker": "none"}',
+ True,
+ 0.0,
+ 0.0,
+ [],
+ "none",
+ ),
]
)
@pytest.mark.asyncio
diff --git a/products/tasks/backend/logic/services/custom_prompt_internals.py b/products/tasks/backend/logic/services/custom_prompt_internals.py
index b49a661060c9..fbe04685f9e6 100644
--- a/products/tasks/backend/logic/services/custom_prompt_internals.py
+++ b/products/tasks/backend/logic/services/custom_prompt_internals.py
@@ -266,6 +266,7 @@ async def create_task_and_trigger(
mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,
mcp_credential_owner_id: int | None = None,
mcp_gateway_server_ids: list[str] | None = None,
+ output_schema: dict[str, Any] | None = None,
):
title = f"[sandbox_prompt:{step_name}] {description[:80]}" if step_name else description[:100]
team = await sync_to_async(Team.objects.get)(id=context.team_id)
@@ -310,6 +311,7 @@ async def create_task_and_trigger(
mcp_gateway_server_ids=mcp_gateway_server_ids,
interaction_origin=context.interaction_origin,
extra_run_state=extra_run_state,
+ output_schema=output_schema,
)
# lambda wrap: task.latest_run is a lazy ORM property; sync_to_async needs a callable
task_run = await sync_to_async(lambda: task.latest_run)()
diff --git a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
index fcc95612597b..7b822c699c8f 100644
--- a/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
+++ b/products/tasks/backend/logic/services/custom_prompt_multi_turn_runner.py
@@ -5,7 +5,7 @@ import asyncio
import logging
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, TypeVar
+from typing import TYPE_CHECKING, Any, TypeVar
from pydantic import BaseModel
@@ -77,6 +77,7 @@ class MultiTurnSession:
mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,
mcp_credential_owner_id: int | None = None,
mcp_gateway_server_ids: list[str] | None = None,
+ output_schema: dict[str, Any] | None = None,
) -> tuple[MultiTurnSession, _ModelT]:
"""Start a multi-turn sandbox session and wait for the first structured response.
@@ -114,6 +115,7 @@ class MultiTurnSession:
mcp_builtin_agent_key=mcp_builtin_agent_key,
mcp_credential_owner_id=mcp_credential_owner_id,
mcp_gateway_server_ids=mcp_gateway_server_ids,
+ output_schema=output_schema,
)
try:
parsed = cls._parse_and_validate(last_message, model, label="initial turn")
@@ -172,6 +174,7 @@ class MultiTurnSession:
mcp_builtin_agent_key: MCPBuiltInAgentKey | None = None,
mcp_credential_owner_id: int | None = None,
mcp_gateway_server_ids: list[str] | None = None,
+ output_schema: dict[str, Any] | None = None,
) -> tuple[MultiTurnSession, str]:
"""Start a multi-turn sandbox session and return the first raw agent response.
@@ -202,6 +205,7 @@ class MultiTurnSession:
mcp_builtin_agent_key=mcp_builtin_agent_key,
mcp_credential_owner_id=mcp_credential_owner_id,
mcp_gateway_server_ids=mcp_gateway_server_ids,
+ output_schema=output_schema,
)
logger.info("multi_turn: started task=%s run=%s step=%s", task.id, task_run.id, step_name or "unknown")
# Get session's parent workflow to send heartbeats to keep the agent alive while waiting for turns.