feat(voice): specialize prompt for Isfahan Industrial Parks, emit source excerpts, and bound generation
- Specialize voice assistant identity and agent system prompt for «شرکت شهرکهای صنعتی اصفهان» (English instructions with Persian proper names) - Emit bounded chunk text excerpts (up to 2000 chars) and identify primary_source in realtime sources events - Bound OpenAI output generation via OPENAI_REALTIME_MAX_OUTPUT_TOKENS and add answer_limited event - Handle old-turn search cancellation safely on turn supersession - Add end-to-end search tracing pipeline and diagnostic CLI - Add database organization title and settings update script
This commit is contained in:
+116
-30
@@ -103,6 +103,9 @@ class Response:
|
||||
transcript_delivered: bool = False
|
||||
parent_response: str | None = None
|
||||
transcript_parts: dict = field(default_factory=dict)
|
||||
pending_transcript: "Control | None" = None
|
||||
limited: bool = False
|
||||
terminal_digest: bytes | None = None
|
||||
cancel_event: str | None = None
|
||||
cancel_deadline: float | None = None
|
||||
final_deadline: float | None = None
|
||||
@@ -374,6 +377,7 @@ class VoiceRuntime:
|
||||
for cancel in pending_cancels:
|
||||
self.command(cancel)
|
||||
for response in self.responses.values():
|
||||
self.discard_pending_transcript(response)
|
||||
if not response.terminal and not response.cancel_event:
|
||||
response.cancel_event = identity()
|
||||
self.command(dict(type="response.cancel", response_id=response.id,
|
||||
@@ -855,7 +859,7 @@ class VoiceRuntime:
|
||||
responses = [r for r in self.responses.values() if r.turn is turn]
|
||||
return (turn.initial and responses and
|
||||
not (self.pending_create and self.pending_create[1] is turn) and
|
||||
all(r.terminal and r.status in ("completed", "waiting_tools")
|
||||
all(r.terminal and (r.status in ("completed", "waiting_tools") or r.limited)
|
||||
and (not r.calls or r.continued) for r in responses)
|
||||
and all(a.state == "retired" or (
|
||||
a.done and a.generated == a.sent == a.played == 0
|
||||
@@ -878,6 +882,7 @@ class VoiceRuntime:
|
||||
affected = [r for r in self.responses.values() if r.turn is old]
|
||||
for response in affected:
|
||||
response.interrupted = True
|
||||
self.discard_pending_transcript(response)
|
||||
if response.final_deadline is None:
|
||||
has_audio = any(a.response is response and a.state != "retired"
|
||||
for a in self.audio.values())
|
||||
@@ -960,11 +965,19 @@ class VoiceRuntime:
|
||||
self.command(dict(type="conversation.item.create",
|
||||
item=dict(type="function_call_output", call_id=call_id,
|
||||
output=canonical_json(call["result"]))))
|
||||
sources = [{k: v for k, v in s.items() if k != "text"}
|
||||
for s in call["result"]["sources"]]
|
||||
raw_sources = call["result"].get("sources", [])
|
||||
sources = []
|
||||
for index, s in enumerate(raw_sources):
|
||||
item = {k: v for k, v in s.items() if k != "text"}
|
||||
full_text = s.get("text", "")
|
||||
item["excerpt"] = full_text[:2000] if len(full_text) > 2000 else full_text
|
||||
item["is_primary"] = (index == 0)
|
||||
sources.append(item)
|
||||
primary_source = sources[0] if sources else None
|
||||
response.visible = True
|
||||
self.control(dict(type="sources", turn_ref=turn.ref,
|
||||
tool_call_id=call["ref"], sources=sources))
|
||||
tool_call_id=call["ref"], sources=sources,
|
||||
primary_source=primary_source))
|
||||
if call["result"]["status"] == "error":
|
||||
self.control(dict(type="error", turn_ref=turn.ref,
|
||||
error=call["result"]["error"]))
|
||||
@@ -1083,7 +1096,7 @@ class VoiceRuntime:
|
||||
if a.state != "open":
|
||||
continue
|
||||
if not a.started and (a.data or (
|
||||
a.done and a.response.terminal and a.response.status == "completed")):
|
||||
a.done and a.response.terminal and (a.response.status == "completed" or a.response.limited))):
|
||||
a.started = True
|
||||
self.control(dict(type="audio_started", turn_ref=a.response.turn.ref,
|
||||
audio_ref=a.ref), response=a.response)
|
||||
@@ -1399,11 +1412,27 @@ class VoiceRuntime:
|
||||
raise ValueError("Unsupported output layout")
|
||||
elif kind in ("response.done", "provider.tools_requested"):
|
||||
wire = event["response"]
|
||||
if (not isinstance(wire, dict) or not isinstance(wire.get("output"), list)
|
||||
or any(not isinstance(item, dict) for item in wire["output"])):
|
||||
raise ValueError("Malformed terminal output")
|
||||
if wire["status"] == "waiting_tools" and kind != "provider.tools_requested":
|
||||
raise ValueError("Invalid native tool phase")
|
||||
response = self.responses[wire["id"]]
|
||||
if response.terminal and response.status != wire["status"]:
|
||||
raise ValueError("Conflicting terminal")
|
||||
# Semantic terminal replay ignores only the outer event ID.
|
||||
terminal_digest = provider_event_digest(dict(type=kind, response=wire), self.settings.max_provider_message_bytes)
|
||||
if response.terminal:
|
||||
if response.terminal_digest != terminal_digest:
|
||||
raise ValueError("Conflicting terminal")
|
||||
return
|
||||
limited = bool(getattr(self.adapter, "token_limited", lambda _: False)(wire))
|
||||
if wire["status"] not in ("completed", "cancelled", "waiting_tools") and not limited:
|
||||
self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn)
|
||||
return
|
||||
# Unfinished tool context cannot safely be reused; fail before execution.
|
||||
if limited and (response.calls or any(
|
||||
item.get("type") != "message" for item in wire["output"])):
|
||||
self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn)
|
||||
return
|
||||
terminal_calls = set()
|
||||
terminal_items = {item["id"] for item in wire["output"]}
|
||||
if len(terminal_items) != len(wire["output"]):
|
||||
@@ -1413,6 +1442,9 @@ class VoiceRuntime:
|
||||
# Validate the complete identity set before scheduling any terminal-discovered call.
|
||||
for item in wire["output"]:
|
||||
if item["type"] == "function_call":
|
||||
if (wire["status"] in ("completed", "waiting_tools")
|
||||
and item.get("status", "completed") != "completed"):
|
||||
raise ValueError("Incomplete terminal tool")
|
||||
self.bind_function_item(item["id"], item["call_id"], response)
|
||||
if item["call_id"] in terminal_calls:
|
||||
raise ValueError("Repeated terminal call")
|
||||
@@ -1432,20 +1464,33 @@ class VoiceRuntime:
|
||||
or len(content) != 1 or content[0]["type"] != "audio"):
|
||||
raise ValueError("Unsupported output layout")
|
||||
elif item_type == "function_call":
|
||||
await self.dispatch(response, item["call_id"], item["name"], item["arguments"], item["id"])
|
||||
await self.dispatch(response, item["call_id"], item["name"], item["arguments"], item["id"], execute=False)
|
||||
else:
|
||||
raise ValueError("Unsupported output type")
|
||||
if terminal_calls != set(response.calls):
|
||||
raise ValueError("Terminal call-set mismatch")
|
||||
if limited and any(not a.done for a in self.audio.values() if a.response is response):
|
||||
raise ValueError("Limited response before audio completion")
|
||||
if wire["status"] in ("completed", "waiting_tools"):
|
||||
for item in wire["output"]:
|
||||
if item["type"] == "function_call":
|
||||
await self.dispatch(response, item["call_id"], item["name"], item["arguments"], item["id"], execute=True)
|
||||
response.terminal, response.status = True, wire["status"]
|
||||
response.limited, response.terminal_digest = limited, terminal_digest
|
||||
if limited and not response.interrupted and not response.turn.superseded:
|
||||
self.control(dict(type="answer_limited", turn_ref=response.turn.ref,
|
||||
reason="output_token_limit"), response=response)
|
||||
if response.pending_transcript is not None:
|
||||
pending = response.pending_transcript
|
||||
self.discard_pending_transcript(response)
|
||||
self.assistant_transcript(response, pending.event, completed=True)
|
||||
self.wake.set()
|
||||
if wire["status"] not in ("completed", "cancelled", "waiting_tools"):
|
||||
self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn)
|
||||
elif wire["status"] == "cancelled" and not response.interrupted:
|
||||
if wire["status"] == "cancelled" and not response.interrupted:
|
||||
raise ValueError("Unexpected cancellation")
|
||||
elif kind == "response.function_call_arguments.done":
|
||||
response = self.correlated_response(event)
|
||||
await self.dispatch(response, event["call_id"], event["name"], event["arguments"], event["item_id"])
|
||||
await self.dispatch(response, event["call_id"], event["name"], event["arguments"], event["item_id"],
|
||||
execute=not getattr(self.adapter, "defer_tool_execution", False))
|
||||
elif kind in ("response.output_audio.delta", "response.output_audio.done"):
|
||||
response = self.correlated_response(event)
|
||||
if response.terminal:
|
||||
@@ -1532,14 +1577,15 @@ class VoiceRuntime:
|
||||
response.transcript_parts[key] = fingerprint
|
||||
elif key in response.transcript_parts:
|
||||
raise ValueError("Transcript delta after completion")
|
||||
if (not response.interrupted and not response.turn.superseded
|
||||
and (response.turn is self.current or response.status == "completed")):
|
||||
response.visible = True
|
||||
entry = self.control(dict(type="transcript", turn_ref=response.turn.ref, role="assistant",
|
||||
text=text, status="completed" if completed else "partial"),
|
||||
response=response, completed_transcript=completed)
|
||||
if entry and completed:
|
||||
response.transcript_completed = True
|
||||
transcript = dict(type="transcript", turn_ref=response.turn.ref, role="assistant", text=text)
|
||||
if completed and not response.terminal and getattr(self.adapter, "defer_tool_execution", False):
|
||||
if not response.interrupted and not response.turn.superseded:
|
||||
entry = self.control(dict(transcript, status="completed"), response=response)
|
||||
if entry is not None:
|
||||
self.controls.pop()
|
||||
response.pending_transcript = entry
|
||||
else:
|
||||
self.assistant_transcript(response, transcript, completed=completed)
|
||||
elif kind == "conversation.item.truncated":
|
||||
matches = [a for a in self.audio.values() if a.cleanup_dispatched
|
||||
and a.item == event["item_id"] and a.index == event["content_index"]]
|
||||
@@ -1565,6 +1611,14 @@ class VoiceRuntime:
|
||||
if a.cleanup_dispatched and a.cleanup == error.get("event_id")), None)
|
||||
if len(matches) == 1:
|
||||
if not self.adapter.is_no_active(error):
|
||||
diagnostic(self.session_id, "provider_handle", "CANCELLATION_ERROR_SIGNATURE",
|
||||
event_type=kind,
|
||||
cancellation_type_match=int(error.get("type") == "invalid_request_error"),
|
||||
cancellation_code_match=int(error.get("code") == "response_cancel_not_active"),
|
||||
cancellation_param_match=int(error.get("param") is None),
|
||||
cancellation_profile_2_1_shimmer=int(
|
||||
getattr(self.adapter, "model", None) == "gpt-realtime-2.1"
|
||||
and getattr(self.adapter, "voice", None) == "shimmer"))
|
||||
self.sync_failed("CANCELLATION_PROVIDER_ERROR", turn=matches[0].turn, phase="provider_handle", event_type=kind)
|
||||
elif cleanup:
|
||||
self.sync_failed("TRUNCATION_PROVIDER_ERROR", turn=cleanup.response.turn, phase="provider_handle", event_type=kind, audio=cleanup)
|
||||
@@ -1582,7 +1636,22 @@ class VoiceRuntime:
|
||||
exc=exc, code="LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
self.fail("LIVE_PROVIDER_PROTOCOL_ERROR", turn=affected)
|
||||
|
||||
async def dispatch(self, response, call_id, name, raw, item_id):
|
||||
def discard_pending_transcript(self, response):
|
||||
if response.pending_transcript is not None:
|
||||
self.release_control(response.pending_transcript)
|
||||
response.pending_transcript = None
|
||||
|
||||
def assistant_transcript(self, response, event, *, completed):
|
||||
if (response.interrupted or response.turn.superseded or
|
||||
(response.turn is not self.current and not (response.status == "completed" or response.limited))):
|
||||
return
|
||||
response.visible = True
|
||||
status = ("limited" if response.limited else "completed") if completed else "partial"
|
||||
entry = self.control(dict(event, status=status), response=response, completed_transcript=completed)
|
||||
if entry and completed:
|
||||
response.transcript_completed = True
|
||||
|
||||
async def dispatch(self, response, call_id, name, raw, item_id, *, execute=True):
|
||||
self.bind_function_item(item_id, call_id, response)
|
||||
rejected_digest = argument_digest(raw)
|
||||
try:
|
||||
@@ -1600,16 +1669,22 @@ class VoiceRuntime:
|
||||
old_response, old = self.calls[call_id]
|
||||
if old_response is not response or old["hash"] != fingerprint or old["item"] != item_id:
|
||||
raise ValueError("Forged/rebound call")
|
||||
call = old
|
||||
if not execute or call["scheduled"] or call["result"] is not None:
|
||||
return
|
||||
else:
|
||||
if response.continued or response.terminal:
|
||||
raise ValueError("Late unknown tool")
|
||||
if len(self.calls) >= self.max_calls:
|
||||
self.overflow("TOOL_CALL_CAPACITY")
|
||||
return
|
||||
call = dict(hash=fingerprint, result=None, sent=False, output_queued=False,
|
||||
scheduled=False, name=name, raw=raw, item=item_id, ref=str(uuid4()))
|
||||
self.calls[call_id] = (response, call)
|
||||
response.calls[call_id] = call
|
||||
if not execute and parsed is not None and name == "search_knowledge":
|
||||
return
|
||||
if response.continued or response.terminal:
|
||||
raise ValueError("Late unknown tool")
|
||||
if len(self.calls) >= self.max_calls:
|
||||
self.overflow("TOOL_CALL_CAPACITY")
|
||||
return
|
||||
call = dict(hash=fingerprint, result=None, sent=False, output_queued=False,
|
||||
name=name, raw=raw, item=item_id, ref=str(uuid4()))
|
||||
self.calls[call_id] = (response, call)
|
||||
response.calls[call_id] = call
|
||||
call["scheduled"] = True
|
||||
if response.interrupted or response.turn.superseded or response.turn is not self.current:
|
||||
return
|
||||
ctx = ToolContext(response.turn.execution, self.clock() + self.tool_seconds,
|
||||
@@ -1647,6 +1722,15 @@ class VoiceRuntime:
|
||||
except Exception as exc:
|
||||
from app.modules.voice.durable_tools import failure_code
|
||||
async with self.lock:
|
||||
# DurableTools has already persisted TOOL_CANCELLED. Only trusted
|
||||
# supersession of this search's old turn makes it nonterminal.
|
||||
if (type(exc) is ValueError and str(exc) == "CANCELLED"
|
||||
and self.responses.get(response.id) is response
|
||||
and ctx.execution is response.turn.execution
|
||||
and ctx.cancelled is response.turn.cancelled
|
||||
and ctx.cancelled.is_set() and response.interrupted
|
||||
and response.turn.superseded and response.turn is not self.current):
|
||||
return
|
||||
self.fail(failure_code(exc), turn=response.turn)
|
||||
return
|
||||
async with self.lock:
|
||||
@@ -1676,6 +1760,8 @@ class VoiceRuntime:
|
||||
while self.controls:
|
||||
self.release_control(self.controls.popleft())
|
||||
self.input_released = True
|
||||
for response in self.responses.values():
|
||||
self.discard_pending_transcript(response)
|
||||
for audio in self.audio.values():
|
||||
audio.data.clear()
|
||||
self.retire(audio)
|
||||
|
||||
Reference in New Issue
Block a user