parlot.instrumentation.pipecat
parlot-instrumentation-pipecat: OTel instrumentation for Pipecat agents.
1"""parlot-instrumentation-pipecat: OTel instrumentation for Pipecat agents.""" 2 3from parlot.core import ( 4 add_platform_ref, 5 human_escalation, 6 record_human_rep, 7 set_session_attribute, 8 set_session_metadata, 9 stamp_platform_refs, 10) 11 12from ._auto import close_session, parlotize 13from ._hooks import attach_aggregators 14from ._processor import PipecatGenAIProcessor 15from ._recording import ParlotRecordingProcessor 16from parlot.core import stamp_external_recording 17 18__all__ = [ 19 "parlotize", 20 "attach_aggregators", 21 "close_session", 22 "PipecatGenAIProcessor", 23 "ParlotRecordingProcessor", 24 "stamp_external_recording", 25 "add_platform_ref", 26 "human_escalation", 27 "record_human_rep", 28 "set_session_attribute", 29 "set_session_metadata", 30 "stamp_platform_refs", 31]
25def parlotize( 26 agent_id: str, 27 *, 28 endpoint: Optional[str] = None, 29 api_key: Optional[str] = None, 30 capture_genai_content: Optional[bool] = None, 31 service_name: Optional[str] = None, 32 tracer_provider: TracerProvider | None = None, 33 version: Optional[str] = None, 34 capture_logs: bool | list[str] | None = None, 35 log_level: Optional[str] = None, 36 record: bool | list[str] | None = None, 37) -> ParlotContext: 38 """Parlotize Pipecat instrumentation and OTLP export. 39 40 Call before constructing ``Pipeline`` / ``PipelineWorker``. Builds a 41 ``TracerProvider`` with an OTLP exporter (unless one is adopted), registers 42 it as the global provider (so Pipecat's ``enable_tracing=True`` path uses 43 it), and patches ``PipelineWorker`` to default metrics + turn tracing on. 44 45 Do **not** call Pipecat's ``setup_tracing()`` afterward — it replaces the 46 global provider and would drop Parlot processors. ``parlotize`` is the 47 Parlot equivalent of that setup. 48 49 Shared parameters match every adapter — see ``parlot.core.ParlotizeProtocol``. 50 51 Args: 52 agent_id: Shared — required canonical ``session.agent_id``. 53 endpoint: Shared — Parlot OTLP base URL (or ``PARLOT_ENDPOINT``). 54 api_key: Shared — org API key (or ``PARLOT_API_KEY``). 55 capture_genai_content: Shared — GenAI payload capture override. 56 service_name: Shared — OTel ``service.name`` (defaults to ``agent_id``). 57 tracer_provider: Shared — existing ``TracerProvider``, or build one. 58 version: Shared — ``gen_ai.agent.version``. 59 capture_logs: Shared — session log capture. 60 log_level: Shared — minimum level for session log capture. 61 record: Audio recording policy. Boolean or agent-id glob patterns. 62 When enabled, place ``ParlotRecordingProcessor`` after 63 ``transport.output()`` (WAV segments by default). 64 65 Returns: 66 The ``ParlotContext`` for this process. 67 """ 68 global _configured, _configured_agent_id, _configured_agent_version 69 global _configured_record, _parlot_context 70 if _configured: 71 logger.debug("parlot-instrumentation.pipecat already configured — skipping") 72 assert _parlot_context is not None 73 return _parlot_context 74 75 from parlot.core import base_parlotize 76 from parlot.core.parlotize import normalize_glob_or_bool 77 from parlot.core.sdk_version import resolve_parlot_sdk_version 78 79 _configured_agent_version = (version or "").strip() or "unknown" 80 _configured_record = normalize_glob_or_bool(record) 81 82 res = base_parlotize( 83 agent_id, 84 endpoint=endpoint, 85 api_key=api_key, 86 capture_genai_content=capture_genai_content, 87 service_name=service_name, 88 tracer_provider=tracer_provider, 89 version=_configured_agent_version, 90 capture_logs=capture_logs, 91 log_level=log_level, 92 ) 93 _parlot_context = res.context 94 _configured_agent_id = res.agent_id 95 96 tracer_provider = res.tracer_provider 97 if tracer_provider is None: 98 if not res.endpoint: 99 raise ValueError( 100 "No OTLP endpoint configured. Pass endpoint= or set the " 101 "PARLOT_ENDPOINT environment variable." 102 ) 103 tracer_provider = _build_provider( 104 endpoint=res.endpoint, 105 api_key=res.api_key, 106 service_name=res.service_name, 107 service_version=_configured_agent_version or None, 108 context=res.context, 109 ) 110 else: 111 # Adopt existing provider: still attach our processor when possible. 112 _attach_processor_if_needed(tracer_provider, res.context) 113 114 from parlot.core.provider import try_set_global_tracer_provider 115 from parlot.core.parlotize import log_parlotize_ready 116 117 try_set_global_tracer_provider(tracer_provider) 118 119 from ._hooks import ( 120 install_aggregator_turn_hooks, 121 install_latency_observer_hooks, 122 install_pipeline_worker_hooks, 123 install_tool_call_hooks, 124 ) 125 from ._session import set_identity, set_tracer 126 127 set_identity(_configured_agent_id, _configured_agent_version) 128 set_tracer( 129 tracer_provider.get_tracer( 130 "parlot.instrumentation.pipecat", 131 resolve_parlot_sdk_version() or None, 132 ) 133 ) 134 _wire_session_logs(res.context, _configured_agent_id) 135 install_pipeline_worker_hooks() 136 install_tool_call_hooks() 137 install_aggregator_turn_hooks() 138 install_latency_observer_hooks() 139 _neutralize_pipecat_setup_tracing() 140 141 _configured = True 142 log_parlotize_ready( 143 "pipecat", 144 agent_id=res.agent_id, 145 endpoint=res.endpoint or "", 146 api_key=res.api_key or "", 147 log=logger, 148 ) 149 return res.context
Parlotize Pipecat instrumentation and OTLP export.
Call before constructing Pipeline / PipelineWorker. Builds a
TracerProvider with an OTLP exporter (unless one is adopted), registers
it as the global provider (so Pipecat's enable_tracing=True path uses
it), and patches PipelineWorker to default metrics + turn tracing on.
Do not call Pipecat's setup_tracing() afterward — it replaces the
global provider and would drop Parlot processors. parlotize is the
Parlot equivalent of that setup.
Shared parameters match every adapter — see parlot.core.ParlotizeProtocol.
Arguments:
- agent_id: Shared — required canonical
session.agent_id. - endpoint: Shared — Parlot OTLP base URL (or
PARLOT_ENDPOINT). - api_key: Shared — org API key (or
PARLOT_API_KEY). - capture_genai_content: Shared — GenAI payload capture override.
- service_name: Shared — OTel
service.name(defaults toagent_id). - tracer_provider: Shared — existing
TracerProvider, or build one. - version: Shared —
gen_ai.agent.version. - capture_logs: Shared — session log capture.
- log_level: Shared — minimum level for session log capture.
- record: Audio recording policy. Boolean or agent-id glob patterns.
When enabled, place
ParlotRecordingProcessoraftertransport.output()(WAV segments by default).
Returns:
The
ParlotContextfor this process.
264def attach_aggregators( 265 user_aggregator: Any = None, 266 assistant_aggregator: Any = None, 267) -> None: 268 """Bind Parlot turn handlers onto existing context aggregators. 269 270 Prefer calling ``parlotize()`` before constructing aggregators so the 271 ``__init__`` patch auto-wires them. Use this when aggregators already 272 exist (built before ``parlotize``, or handed in by a framework). 273 274 Idempotent — safe to call more than once on the same instances. 275 """ 276 bind_user_aggregator(user_aggregator) 277 bind_assistant_aggregator(assistant_aggregator)
Bind Parlot turn handlers onto existing context aggregators.
Prefer calling parlotize() before constructing aggregators so the
__init__ patch auto-wires them. Use this when aggregators already
exist (built before parlotize, or handed in by a framework).
Idempotent — safe to call more than once on the same instances.
373def close_session(conversation_id: str, *, reason: str = "completed") -> None: 374 """Public helper to close a Pipecat-owned session by conversation_id.""" 375 from ._session import close_session as _close 376 377 # Best-effort sync bridge: schedule finish if a loop is running. 378 try: 379 loop = asyncio.get_running_loop() 380 loop.create_task(finish_active_recordings()) 381 except RuntimeError: 382 try: 383 asyncio.run(finish_active_recordings()) 384 except Exception: 385 logger.debug("parlot: sync recording finish skipped", exc_info=True) 386 387 _close(conversation_id, reason=reason)
Public helper to close a Pipecat-owned session by conversation_id.
99class PipecatGenAIProcessor(ParlotBaseProcessor): 100 """Enrich and remap Pipecat OTEL spans for Parlot export.""" 101 102 def __init__(self, *, context: ParlotContext | None = None) -> None: 103 self._context = context 104 # Live parent spans (turn/conversation) so children can read attrs set 105 # after start_span (Pipecat sets conversation.id / turn.number post-start). 106 self._open_spans: dict[str, Any] = {} 107 self._active_conversation_id: str = "" 108 self._active_turn_number: int | None = None 109 110 @staticmethod 111 def _debug_log_span(name: str) -> bool: 112 """Skip FastAPI/httpx noise when PARLOT_DEBUG_LEVEL=DEBUG.""" 113 n = (name or "").lower() 114 if not n: 115 return False 116 if n in (NATIVE_CONVERSATION, NATIVE_TURN) or n.startswith("parlot."): 117 return True 118 if n in ("stt", "tts", "llm") or n.startswith( 119 ("stt", "tts", "llm", "chat", "execute_tool") 120 ): 121 return True 122 return False 123 124 def on_start(self, span, parent_context=None) -> None: # noqa: ANN001 125 # SDK Span (not API Span) — leave untyped like LiveKit processor. 126 name = getattr(span, "name", None) or "" 127 if self._debug_log_span(name): 128 super().on_start(span, parent_context) 129 sid = _span_id_hex(span) 130 if sid and name in (NATIVE_CONVERSATION, NATIVE_TURN): 131 self._open_spans[sid] = span 132 # Activate session as early as possible so INFO logs correlate. 133 if name == NATIVE_TURN: 134 parent_attrs = self._parent_attrs(span) 135 cid = str( 136 (getattr(span, "attributes", None) or {}).get(ATTR_PIPECAT_CONVERSATION_ID) 137 or parent_attrs.get(ATTR_PIPECAT_CONVERSATION_ID) 138 or self._active_conversation_id 139 or "" 140 ).strip() 141 if cid: 142 self._active_conversation_id = cid 143 ensure_session(cid) 144 145 def on_end(self, span: ReadableSpan) -> None: 146 name = span.name or "" 147 if self._debug_log_span(name): 148 super().on_end(span) 149 attrs = span.attributes or {} 150 sid = "" 151 try: 152 ctx = span.get_span_context() 153 if ctx is not None: 154 sid = format(int(ctx.span_id), "016x") 155 except Exception: 156 sid = "" 157 if sid: 158 self._open_spans.pop(sid, None) 159 160 # Passthrough contract / GenAI spans we mint (emit_turn / ensure_session). 161 if name in CONTRACT_SPAN_NAMES or is_genai_span_name(name): 162 return 163 164 if name == NATIVE_CONVERSATION: 165 cid = str(attrs.get(ATTR_PIPECAT_CONVERSATION_ID) or "").strip() 166 if cid: 167 self._active_conversation_id = cid 168 ensure_session(cid) 169 span._name = "__parlot_drop_conversation__" 170 close_session(cid, reason="completed") 171 return 172 173 if name == NATIVE_TURN: 174 self._note_turn_context(attrs, span) 175 # Contract turns come from aggregator events — drop native turn only. 176 span._name = "__parlot_drop_turn__" 177 return 178 179 exported = remap_pipecat_span_name(name, attrs) 180 if exported is None: 181 span._name = f"__parlot_drop_{name}__" 182 return 183 184 apply_pipecat_span_rename(span) 185 self._stamp_session_linkage(span) 186 self._stamp_agent_role(span) 187 self._map_pipecat_metrics(span) 188 self._map_transcript_text(span) 189 self._record_usage_metrics(span) 190 191 def _note_turn_context( 192 self, attrs: Mapping[str, AttributeValue], span: ReadableSpan 193 ) -> None: 194 cid = str(attrs.get(ATTR_PIPECAT_CONVERSATION_ID) or "").strip() 195 turn_n = self._turn_number(attrs) 196 if cid: 197 self._active_conversation_id = cid 198 ensure_session(cid) 199 if turn_n is not None: 200 self._active_turn_number = turn_n 201 202 def _parent_attrs(self, span: ReadableSpan) -> Mapping[str, AttributeValue]: 203 parent_id = _parent_span_id_hex(span) 204 if not parent_id: 205 return {} 206 parent = self._open_spans.get(parent_id) 207 if parent is None: 208 return {} 209 return getattr(parent, "attributes", None) or {} 210 211 def _resolve_conversation_and_turn( 212 self, span: ReadableSpan 213 ) -> tuple[str, int | None]: 214 attrs = span.attributes or {} 215 parent_attrs = self._parent_attrs(span) 216 cid = str( 217 attrs.get(ATTR_PIPECAT_CONVERSATION_ID) 218 or parent_attrs.get(ATTR_PIPECAT_CONVERSATION_ID) 219 or self._active_conversation_id 220 or "" 221 ).strip() 222 if not cid: 223 state = _pipecat_state(get_active_session()) 224 if state and state.conversation_id: 225 cid = state.conversation_id 226 turn_n = self._turn_number(attrs) or self._turn_number(parent_attrs) 227 if turn_n is None: 228 turn_n = self._active_turn_number 229 if turn_n is None: 230 state = lookup_session(cid) if cid else _pipecat_state(get_active_session()) 231 if state and state.open_turn_index is not None: 232 turn_n = state.open_turn_index 233 return cid, turn_n 234 235 @staticmethod 236 def _turn_number(attrs: Mapping[str, AttributeValue]) -> int | None: 237 raw = attrs.get(ATTR_PIPECAT_TURN_NUMBER) 238 if raw is None or isinstance(raw, (list, tuple)): 239 return None 240 try: 241 return int(raw) # type: ignore[arg-type] 242 except (TypeError, ValueError): 243 return None 244 245 @staticmethod 246 def _is_stt(name: str) -> bool: 247 return name == "stt" or name.startswith("stt") 248 249 @staticmethod 250 def _is_tts(name: str) -> bool: 251 return name == "tts" or name.startswith("tts") 252 253 @staticmethod 254 def _is_llm(name: str) -> bool: 255 # Native ``llm`` before rename, or GenAI ``chat`` / ``chat {model}`` after. 256 if name.startswith("llm_tool"): 257 return False 258 return ( 259 name == "llm" 260 or name.startswith("llm") 261 or name == "chat" 262 or name.startswith("chat") 263 ) 264 265 @staticmethod 266 def _is_tool(name: str) -> bool: 267 return name.startswith("execute_tool") or name.startswith("llm_tool") 268 269 def _parlot_turn_index_for_span( 270 self, span: ReadableSpan, state: _PipecatSessionState 271 ) -> int | None: 272 """Stamp pipeline spans with open aggregator indices (no new allocation). 273 274 The app nests ``stt`` / ``llm`` / ``tts`` under **agent** turns. Indices 275 are reserved when aggregator events mint ``parlot.turn`` — do not burn 276 new indices from STT/TTS end alone. 277 """ 278 name = span.name or "" 279 if self._is_stt(name) or self._is_tts(name) or self._is_llm(name) or self._is_tool( 280 name 281 ): 282 if state.open_agent_turn_index is not None: 283 return state.open_agent_turn_index 284 if state.open_user_turn_index is not None: 285 return state.open_user_turn_index 286 if state.turn_count > 0: 287 return state.turn_count 288 return None 289 return state.open_agent_turn_index or state.open_user_turn_index 290 291 def _stamp_session_linkage(self, span: ReadableSpan) -> None: 292 cid, pipecat_turn = self._resolve_conversation_and_turn(span) 293 state = lookup_session(cid) if cid else _pipecat_state(get_active_session()) 294 if state is None and cid: 295 state = ensure_session(cid) 296 if state is None: 297 return 298 if cid: 299 self._active_conversation_id = cid 300 if pipecat_turn is not None: 301 self._active_turn_number = pipecat_turn 302 parlot_turn = self._parlot_turn_index_for_span(span, state) 303 self._set(span, ATTR_SESSION_ID, state.session_id) 304 self._set(span, ATTR_SESSION_CONVERSATION_ID, state.conversation_id) 305 if parlot_turn is not None: 306 self._set(span, ATTR_TURN_INDEX, parlot_turn) 307 agent_id = configured_agent_id() 308 if agent_id: 309 self._set(span, ATTR_GEN_AI_AGENT_ID, agent_id) 310 self._set(span, ATTR_GEN_AI_AGENT_NAME, agent_id) 311 self._set(span, ATTR_SESSION_AGENT_ID, agent_id) 312 stamp_pipecat_platform_refs(span, conversation_id=state.conversation_id) 313 314 def _stamp_agent_role(self, span: ReadableSpan) -> None: 315 name = span.name or "" 316 attrs = span.attributes or {} 317 if attrs.get(ATTR_AGENT_ROLE): 318 return 319 if self._is_stt(name): 320 self._set(span, ATTR_AGENT_ROLE, "stt") 321 elif self._is_tts(name): 322 self._set(span, ATTR_AGENT_ROLE, "tts") 323 elif self._is_llm(name): 324 self._set(span, ATTR_AGENT_ROLE, "llm") 325 elif self._is_tool(name): 326 self._set(span, ATTR_AGENT_ROLE, "tool") 327 328 def _map_pipecat_metrics(self, span: ReadableSpan) -> None: 329 attrs = span.attributes or {} 330 name = span.name or "" 331 ttfb = _as_float(attrs.get(ATTR_PIPECAT_METRICS_TTFB)) 332 # Only TTS owns gen_ai.tts.ttfb_s — do not stamp LLM TTFB there. 333 if ( 334 ttfb is not None 335 and self._is_tts(name) 336 and not attrs.get(ATTR_GEN_AI_TTS_TTFB_S) 337 ): 338 self._set(span, ATTR_GEN_AI_TTS_TTFB_S, ttfb) 339 if not attrs.get(ATTR_GEN_AI_MODEL): 340 model = attrs.get("gen_ai.request.model") or attrs.get("model") 341 if model is not None and not isinstance(model, (list, tuple)): 342 self._set(span, ATTR_GEN_AI_MODEL, str(model)) 343 344 def _record_usage_metrics(self, span: ReadableSpan) -> None: 345 recorder = get_metrics_recorder() 346 if recorder is None: 347 return 348 attrs = span.attributes or {} 349 session_id = str(attrs.get(ATTR_SESSION_ID) or "").strip() 350 if not session_id: 351 return 352 name = span.name or "" 353 model = str(attrs.get(ATTR_GEN_AI_MODEL) or attrs.get("gen_ai.request.model") or "") 354 provider = str(attrs.get("gen_ai.provider.name") or "") 355 if self._is_stt(name): 356 audio = _as_float(attrs.get(ATTR_PIPECAT_METRICS_AUDIO_SECONDS)) 357 if audio: 358 recorder.record_stt_audio( 359 session_id=session_id, 360 audio_seconds=audio, 361 model=model, 362 provider=provider, 363 ) 364 elif self._is_tts(name): 365 raw_chars = attrs.get(ATTR_PIPECAT_METRICS_CHAR_COUNT) 366 try: 367 chars = int(raw_chars) if raw_chars is not None else 0 # type: ignore[arg-type] 368 except (TypeError, ValueError): 369 chars = 0 370 if chars: 371 recorder.record_tts_characters( 372 session_id=session_id, 373 characters=chars, 374 model=model, 375 provider=provider, 376 ) 377 elif self._is_llm(name): 378 try: 379 tin = int(attrs.get("gen_ai.usage.input_tokens") or 0) # type: ignore[arg-type] 380 except (TypeError, ValueError): 381 tin = 0 382 try: 383 tout = int(attrs.get("gen_ai.usage.output_tokens") or 0) # type: ignore[arg-type] 384 except (TypeError, ValueError): 385 tout = 0 386 if tin or tout: 387 recorder.record_llm_tokens( 388 session_id=session_id, 389 input_tokens=tin, 390 output_tokens=tout, 391 model=model, 392 provider=provider, 393 ) 394 # Keep session totals for session.* close histograms. 395 cid = str( 396 attrs.get(ATTR_SESSION_CONVERSATION_ID) 397 or attrs.get(ATTR_PIPECAT_CONVERSATION_ID) 398 or "" 399 ).strip() 400 sess = lookup_session(cid) if cid else _pipecat_state(get_active_session()) 401 if sess is not None and sess.session_id == session_id: 402 if tin: 403 sess.total_input_tokens += tin 404 if tout: 405 sess.total_output_tokens += tout 406 407 def _map_transcript_text(self, span: ReadableSpan) -> None: 408 """Stamp transcript attrs on pipeline spans for nesting; do not mint turns.""" 409 attrs = span.attributes or {} 410 name = span.name or "" 411 transcript = ( 412 attrs.get(ATTR_PIPECAT_TRANSCRIPT) 413 or attrs.get(ATTR_PIPECAT_TEXT) 414 or attrs.get("output") 415 ) 416 if transcript is None or isinstance(transcript, (list, tuple)): 417 return 418 text = str(transcript).strip() 419 if not text: 420 return 421 if self._is_stt(name): 422 if not attrs.get(ATTR_TURN_USER_TEXT): 423 self._set(span, ATTR_TURN_USER_TEXT, text) 424 elif self._is_tts(name) or self._is_llm(name): 425 if not attrs.get(ATTR_TURN_AGENT_TEXT): 426 self._set(span, ATTR_TURN_AGENT_TEXT, text)
Enrich and remap Pipecat OTEL spans for Parlot export.
102 def __init__(self, *, context: ParlotContext | None = None) -> None: 103 self._context = context 104 # Live parent spans (turn/conversation) so children can read attrs set 105 # after start_span (Pipecat sets conversation.id / turn.number post-start). 106 self._open_spans: dict[str, Any] = {} 107 self._active_conversation_id: str = "" 108 self._active_turn_number: int | None = None
124 def on_start(self, span, parent_context=None) -> None: # noqa: ANN001 125 # SDK Span (not API Span) — leave untyped like LiveKit processor. 126 name = getattr(span, "name", None) or "" 127 if self._debug_log_span(name): 128 super().on_start(span, parent_context) 129 sid = _span_id_hex(span) 130 if sid and name in (NATIVE_CONVERSATION, NATIVE_TURN): 131 self._open_spans[sid] = span 132 # Activate session as early as possible so INFO logs correlate. 133 if name == NATIVE_TURN: 134 parent_attrs = self._parent_attrs(span) 135 cid = str( 136 (getattr(span, "attributes", None) or {}).get(ATTR_PIPECAT_CONVERSATION_ID) 137 or parent_attrs.get(ATTR_PIPECAT_CONVERSATION_ID) 138 or self._active_conversation_id 139 or "" 140 ).strip() 141 if cid: 142 self._active_conversation_id = cid 143 ensure_session(cid)
Called when a opentelemetry.trace.Span is started.
This method is called synchronously on the thread that starts the span, therefore it should not block or throw an exception.
Arguments:
- span: The
opentelemetry.trace.Spanthat just started. - parent_context: The parent context of the span that just started.
145 def on_end(self, span: ReadableSpan) -> None: 146 name = span.name or "" 147 if self._debug_log_span(name): 148 super().on_end(span) 149 attrs = span.attributes or {} 150 sid = "" 151 try: 152 ctx = span.get_span_context() 153 if ctx is not None: 154 sid = format(int(ctx.span_id), "016x") 155 except Exception: 156 sid = "" 157 if sid: 158 self._open_spans.pop(sid, None) 159 160 # Passthrough contract / GenAI spans we mint (emit_turn / ensure_session). 161 if name in CONTRACT_SPAN_NAMES or is_genai_span_name(name): 162 return 163 164 if name == NATIVE_CONVERSATION: 165 cid = str(attrs.get(ATTR_PIPECAT_CONVERSATION_ID) or "").strip() 166 if cid: 167 self._active_conversation_id = cid 168 ensure_session(cid) 169 span._name = "__parlot_drop_conversation__" 170 close_session(cid, reason="completed") 171 return 172 173 if name == NATIVE_TURN: 174 self._note_turn_context(attrs, span) 175 # Contract turns come from aggregator events — drop native turn only. 176 span._name = "__parlot_drop_turn__" 177 return 178 179 exported = remap_pipecat_span_name(name, attrs) 180 if exported is None: 181 span._name = f"__parlot_drop_{name}__" 182 return 183 184 apply_pipecat_span_rename(span) 185 self._stamp_session_linkage(span) 186 self._stamp_agent_role(span) 187 self._map_pipecat_metrics(span) 188 self._map_transcript_text(span) 189 self._record_usage_metrics(span)
Called when a opentelemetry.trace.Span is ended.
This method is called synchronously on the thread that ends the span, therefore it should not block or throw an exception.
Arguments:
- span: The
opentelemetry.trace.Spanthat just ended.
110class ParlotRecordingProcessor(AudioBufferProcessor): 111 """Mixed dual-mono stereo → ~30s WAV (or Opus) segments → presigned PUT → ``/complete``. 112 113 Place after ``transport.output()`` so user and bot are buffered. Pipecat mixes 114 both tracks (``num_channels=1``); we expand to stereo with the same mix on L and R 115 so playback matches LiveKit Room Composite rather than hard-panned L/R. 116 117 Fail-open: never raises into the call path; stamps ``session.recording.status=failed`` 118 with a reason when capture/upload cannot complete. 119 """ 120 121 def __init__( 122 self, 123 *, 124 sample_rate: int | None = 16_000, 125 segment_seconds: float = DEFAULT_SEGMENT_SECONDS, 126 format: str = "pcm_wav", 127 context: ParlotContext | None = None, 128 **kwargs: Any, 129 ) -> None: 130 mono_bytes = int(max(1.0, segment_seconds) * _DEFAULT_MONO_BYTES_PER_SEC) 131 if sample_rate and sample_rate != 16_000: 132 mono_bytes = int(max(1.0, segment_seconds) * sample_rate * 2) 133 # Mono merge in Pipecat (not user-L / bot-R); we dual-mono to stereo on upload. 134 super().__init__( 135 sample_rate=sample_rate, 136 num_channels=1, 137 buffer_size=mono_bytes, 138 auto_start_recording=True, 139 **kwargs, 140 ) 141 self._segment_seconds = float(segment_seconds) 142 self._format = "opus_ogg" if format == "opus_ogg" else "pcm_wav" 143 self._context = context 144 self._segment_index = 0 145 self._uploaded_segments: list[dict[str, int]] = [] 146 self._sample_offset = 0 147 self._sample_count = 0 148 self._anchor_wall_ms: int | None = None 149 self._audio_uri: str | None = None 150 self._finished = False 151 # Re-entry guard for finish(); uploads stay allowed until drain closes the gate. 152 self._finishing = False 153 self._upload_lock = asyncio.Lock() 154 self._upload_tasks: set[asyncio.Task[None]] = set() 155 self._all_silent = True 156 self._received_audio = False 157 # Last specific upload failure (grant/put); avoid overwriting with a generic stamp. 158 self._last_upload_error: str | None = None 159 # Cached so /complete still works after CancelFrame tears down the session. 160 self._cached_session_id: str = "" 161 self._cached_conversation_id: str = "" 162 self._cached_runtime: Any = None 163 self._cached_session_span: Any = None 164 165 try: 166 from ._auto import register_recording_processor 167 168 register_recording_processor(self) 169 except Exception: 170 pass 171 172 @self.event_handler("on_audio_data") 173 async def _on_audio(processor, audio, sample_rate, num_channels): 174 # Child task so finish() can gather uploads even if this handler is 175 # concurrent with CancelFrame; still await so Pipecat cleanup waits. 176 task = asyncio.create_task( 177 self._upload_segment(audio, sample_rate, num_channels), 178 name="parlot-recording-upload", 179 ) 180 self._upload_tasks.add(task) 181 task.add_done_callback(self._upload_tasks.discard) 182 try: 183 await task 184 except Exception: 185 logger.warning("parlot: segment upload failed", exc_info=True) 186 if not self._last_upload_error: 187 stamp_recording_error( 188 self._session_span(), "segment_upload_error" 189 ) 190 191 @self.event_handler("on_recording_started") 192 async def _on_started(processor): 193 try: 194 self._maybe_stamp_started() 195 except Exception: 196 logger.debug("parlot: recording started stamp failed", exc_info=True) 197 198 async def process_frame(self, frame, direction: FrameDirection): # type: ignore[override] 199 # Complete *before* End/Cancel propagate: pushing CancelFrame ends the 200 # Pipecat conversation span, which calls close_session and clears the 201 # active session — finish() would then skip /complete (no session id). 202 if isinstance(frame, (EndFrame, CancelFrame)): 203 try: 204 await self.finish() 205 except Exception: 206 logger.warning("parlot: recording finish on end failed", exc_info=True) 207 await super().process_frame(frame, direction) 208 return 209 await super().process_frame(frame, direction) 210 211 def _runtime(self): 212 if self._cached_runtime is not None: 213 return self._cached_runtime 214 ctx = self._context 215 if ctx is None: 216 from ._auto import configured_context 217 218 ctx = configured_context() 219 if ctx is None: 220 return None 221 return getattr(ctx, "runtime", None) 222 223 def _session_span(self): 224 span = get_active_session_span() 225 if span is not None: 226 self._cached_session_span = span 227 return span 228 return self._cached_session_span 229 230 def _session_state(self): 231 state = get_active_session() 232 if state is not None: 233 return state 234 return any_open_session() 235 236 def _session_id(self) -> str: 237 state = self._session_state() 238 sid = str(getattr(state, "session_id", "") or "") if state else "" 239 if sid: 240 self._cached_session_id = sid 241 return sid 242 return self._cached_session_id 243 244 def _cache_binding(self) -> None: 245 runtime = self._runtime() 246 if runtime is not None: 247 self._cached_runtime = runtime 248 sid = self._session_id() 249 if sid: 250 self._cached_session_id = sid 251 state = self._session_state() 252 cid = str(getattr(state, "conversation_id", "") or "") if state else "" 253 if cid: 254 self._cached_conversation_id = cid 255 span = get_active_session_span() 256 if span is not None: 257 self._cached_session_span = span 258 259 def _maybe_stamp_started(self) -> None: 260 if self._anchor_wall_ms is not None: 261 return 262 self._anchor_wall_ms = int(time.time() * 1000) 263 self._cache_binding() 264 state = self._session_state() 265 if state is not None: 266 set_recording_anchor_wall_ms(state, self._anchor_wall_ms) 267 stamp_recording_started( 268 self._session_span(), 269 anchor_wall_ms=self._anchor_wall_ms, 270 source="pipecat_buffer", 271 format=self._format, 272 ) 273 274 async def _await_uploads_idle(self) -> None: 275 """Gather in-flight segment upload tasks after stop_recording. 276 277 Cancel/End can race a buffer flush: finish must not treat 278 ``received_audio && segment_index==0`` as silent while PUT is still running. 279 """ 280 # One yield so stop_recording's on_audio_data can create_task + register. 281 await asyncio.sleep(0) 282 pending = [t for t in self._upload_tasks if not t.done()] 283 if not pending: 284 return 285 try: 286 await asyncio.wait_for( 287 asyncio.gather(*pending, return_exceptions=True), 288 timeout=UPLOAD_DRAIN_TIMEOUT_S, 289 ) 290 except asyncio.TimeoutError: 291 still = sum(1 for t in pending if not t.done()) 292 logger.warning( 293 "parlot: recording upload drain timed out " 294 "(pending=%s); proceeding with committed segments", 295 still, 296 ) 297 298 async def _upload_segment( 299 self, audio: bytes, sample_rate: int, num_channels: int 300 ) -> None: 301 # Allow uploads during finish() until the post-drain gate closes. 302 if self._finished or not audio: 303 return 304 async with self._upload_lock: 305 if self._finished: 306 return 307 await self._upload_segment_locked(audio, sample_rate, num_channels) 308 309 def _stamp_upload_error(self, reason: str) -> None: 310 self._last_upload_error = reason 311 stamp_recording_error(self._session_span(), reason) 312 313 async def _upload_segment_locked( 314 self, audio: bytes, sample_rate: int, num_channels: int 315 ) -> None: 316 self._received_audio = True 317 self._maybe_stamp_started() 318 self._cache_binding() 319 if not _pcm_is_silent(audio): 320 self._all_silent = False 321 322 runtime = self._cached_runtime or self._runtime() 323 session_id = self._cached_session_id or self._session_id() 324 if runtime is None or not session_id: 325 logger.warning( 326 "parlot: recording segment skipped — no runtime/session yet" 327 ) 328 return 329 330 # Timeline frames from the buffer (mono mix); encode as dual-mono stereo. 331 frames = len(audio) // (2 * max(1, num_channels)) 332 pcm = ( 333 _mono_pcm_to_dual_stereo(audio) 334 if num_channels == 1 335 else audio 336 ) 337 out_channels = 2 if num_channels == 1 else num_channels 338 339 content_type = "audio/ogg" if self._format == "opus_ogg" else "audio/wav" 340 if self._format == "opus_ogg": 341 encoded = _encode_opus_ogg( 342 pcm, sample_rate=sample_rate, num_channels=out_channels 343 ) 344 if encoded is None: 345 self._format = "pcm_wav" 346 content_type = "audio/wav" 347 body = _wav_bytes( 348 pcm, sample_rate=sample_rate, num_channels=out_channels 349 ) 350 else: 351 body = encoded 352 else: 353 body = _wav_bytes( 354 pcm, sample_rate=sample_rate, num_channels=out_channels 355 ) 356 357 outcome = await fetch_upload_grant( 358 runtime, 359 session_id=session_id, 360 segment_index=self._segment_index, 361 sample_offset=self._sample_offset, 362 content_type=content_type, 363 ) 364 if not outcome.ok or outcome.grant is None: 365 error = outcome.error or "upload_grant_failed" 366 self._stamp_upload_error(error) 367 logger.error( 368 "parlot: recording segment skipped — upload grant denied error=%s", 369 error, 370 ) 371 return 372 grant = outcome.grant 373 put_url = grant_put_url(grant) 374 if not put_url: 375 self._stamp_upload_error("upload_grant_failed") 376 return 377 ok = await put_bytes_to_presigned_url( 378 put_url, body, content_type=content_type 379 ) 380 if not ok: 381 self._stamp_upload_error("segment_put_failed") 382 return 383 384 uri = grant_audio_uri(grant) 385 if uri: 386 self._audio_uri = uri 387 self._uploaded_segments.append( 388 { 389 "segment_index": self._segment_index, 390 "sample_offset": self._sample_offset, 391 } 392 ) 393 self._sample_offset += frames 394 self._sample_count += frames 395 self._segment_index += 1 396 397 async def finish(self) -> None: 398 """Flush last partial segment and POST ``/complete``. Fail-open.""" 399 if self._finishing or self._finished: 400 return 401 self._finishing = True 402 try: 403 from ._auto import unregister_recording_processor 404 405 unregister_recording_processor(self) 406 except Exception: 407 pass 408 409 # Single task so CancelledError waits for the same work (no double /complete). 410 task = asyncio.create_task( 411 self._finish_inner(), name="parlot-recording-finish" 412 ) 413 try: 414 await asyncio.wait_for(asyncio.shield(task), timeout=CLOSE_TIMEOUT_S) 415 except asyncio.TimeoutError: 416 stamp_recording_error(self._session_span(), "complete_timeout") 417 task.cancel() 418 try: 419 await task 420 except (asyncio.CancelledError, Exception): 421 pass 422 except asyncio.CancelledError: 423 # Outer cancel: wait for the shielded task; do not start a second finish. 424 try: 425 await asyncio.shield(task) 426 except Exception as exc: 427 stamp_recording_error( 428 self._session_span(), f"complete_failed:{type(exc).__name__}" 429 ) 430 raise 431 except Exception as exc: 432 stamp_recording_error( 433 self._session_span(), f"complete_failed:{type(exc).__name__}" 434 ) 435 logger.warning("parlot: recording finish failed — %s", exc, exc_info=True) 436 finally: 437 # Safety net if drain path never set the gate. 438 self._finished = True 439 440 async def _finish_inner(self) -> None: 441 try: 442 await self.stop_recording() 443 except Exception: 444 logger.debug("parlot: stop_recording during finish failed", exc_info=True) 445 446 # stop_recording may still be uploading the final buffer segment. 447 await self._await_uploads_idle() 448 449 # Close the upload window before /complete so late flushes cannot orphan raw/. 450 # Set the gate before snapshotting; do not hold _upload_lock across this so a 451 # hung PUT (drain timed out) cannot deadlock finish. 452 self._finished = True 453 segment_count = self._segment_index 454 segments = list(self._uploaded_segments) 455 sample_count = self._sample_count 456 received_audio = self._received_audio 457 all_silent = self._all_silent 458 last_upload_error = self._last_upload_error 459 audio_uri_hint = self._audio_uri 460 fmt = self._format 461 anchor = self._anchor_wall_ms 462 463 if segment_count == 0 and sample_count == 0: 464 if not received_audio: 465 stamp_recording_error(self._session_span(), "no_audio") 466 elif all_silent: 467 stamp_recording_error(self._session_span(), "silent") 468 elif last_upload_error: 469 # Specific grant/put failure already stamped; keep it. 470 pass 471 else: 472 stamp_recording_error(self._session_span(), "segment_upload_error") 473 return 474 475 if all_silent: 476 stamp_recording_error(self._session_span(), "silent") 477 return 478 479 runtime = self._cached_runtime or self._runtime() 480 session_id = self._cached_session_id or self._session_id() 481 if runtime is None or not session_id: 482 stamp_recording_error(self._session_span(), "complete_no_session") 483 logger.warning( 484 "parlot: recording complete skipped — no session " 485 "(cached_id=%r)", 486 self._cached_session_id, 487 ) 488 return 489 490 wall_end_ms = int(time.time() * 1000) 491 logger.info( 492 "parlot: recording complete session_id=%s segments=%s samples=%s", 493 session_id, 494 segment_count, 495 sample_count, 496 ) 497 conversation_id = self._cached_conversation_id 498 if not conversation_id: 499 state = self._session_state() 500 conversation_id = ( 501 str(getattr(state, "conversation_id", "") or "") if state else "" 502 ) 503 result = await complete_recording( 504 runtime, 505 session_id=session_id, 506 format=fmt, 507 conversation_id=conversation_id or None, 508 segment_count=segment_count, 509 segments=segments, 510 sample_rate=self.sample_rate or 16_000, 511 anchor_wall_ms=anchor, 512 sample_count=sample_count, 513 wall_end_ms=wall_end_ms, 514 ) 515 if result is None: 516 stamp_recording_error(self._session_span(), "complete_failed") 517 return 518 519 audio_uri = str(result.get("audio_recording_uri") or audio_uri_hint or "") 520 partial = bool(result.get("partial")) 521 if audio_uri: 522 stamp_recording_uploaded( 523 self._session_span(), 524 audio_uri=audio_uri, 525 partial=partial, 526 sample_count=sample_count, 527 wall_end_ms=wall_end_ms, 528 format=fmt, 529 ) 530 531 async def fail(self, reason: str) -> None: 532 stamp_recording_error(self._session_span(), reason) 533 self._finishing = True 534 self._finished = True
Mixed dual-mono stereo → ~30s WAV (or Opus) segments → presigned PUT → /complete.
Place after transport.output() so user and bot are buffered. Pipecat mixes
both tracks (num_channels=1); we expand to stereo with the same mix on L and R
so playback matches LiveKit Room Composite rather than hard-panned L/R.
Fail-open: never raises into the call path; stamps session.recording.status=failed
with a reason when capture/upload cannot complete.
121 def __init__( 122 self, 123 *, 124 sample_rate: int | None = 16_000, 125 segment_seconds: float = DEFAULT_SEGMENT_SECONDS, 126 format: str = "pcm_wav", 127 context: ParlotContext | None = None, 128 **kwargs: Any, 129 ) -> None: 130 mono_bytes = int(max(1.0, segment_seconds) * _DEFAULT_MONO_BYTES_PER_SEC) 131 if sample_rate and sample_rate != 16_000: 132 mono_bytes = int(max(1.0, segment_seconds) * sample_rate * 2) 133 # Mono merge in Pipecat (not user-L / bot-R); we dual-mono to stereo on upload. 134 super().__init__( 135 sample_rate=sample_rate, 136 num_channels=1, 137 buffer_size=mono_bytes, 138 auto_start_recording=True, 139 **kwargs, 140 ) 141 self._segment_seconds = float(segment_seconds) 142 self._format = "opus_ogg" if format == "opus_ogg" else "pcm_wav" 143 self._context = context 144 self._segment_index = 0 145 self._uploaded_segments: list[dict[str, int]] = [] 146 self._sample_offset = 0 147 self._sample_count = 0 148 self._anchor_wall_ms: int | None = None 149 self._audio_uri: str | None = None 150 self._finished = False 151 # Re-entry guard for finish(); uploads stay allowed until drain closes the gate. 152 self._finishing = False 153 self._upload_lock = asyncio.Lock() 154 self._upload_tasks: set[asyncio.Task[None]] = set() 155 self._all_silent = True 156 self._received_audio = False 157 # Last specific upload failure (grant/put); avoid overwriting with a generic stamp. 158 self._last_upload_error: str | None = None 159 # Cached so /complete still works after CancelFrame tears down the session. 160 self._cached_session_id: str = "" 161 self._cached_conversation_id: str = "" 162 self._cached_runtime: Any = None 163 self._cached_session_span: Any = None 164 165 try: 166 from ._auto import register_recording_processor 167 168 register_recording_processor(self) 169 except Exception: 170 pass 171 172 @self.event_handler("on_audio_data") 173 async def _on_audio(processor, audio, sample_rate, num_channels): 174 # Child task so finish() can gather uploads even if this handler is 175 # concurrent with CancelFrame; still await so Pipecat cleanup waits. 176 task = asyncio.create_task( 177 self._upload_segment(audio, sample_rate, num_channels), 178 name="parlot-recording-upload", 179 ) 180 self._upload_tasks.add(task) 181 task.add_done_callback(self._upload_tasks.discard) 182 try: 183 await task 184 except Exception: 185 logger.warning("parlot: segment upload failed", exc_info=True) 186 if not self._last_upload_error: 187 stamp_recording_error( 188 self._session_span(), "segment_upload_error" 189 ) 190 191 @self.event_handler("on_recording_started") 192 async def _on_started(processor): 193 try: 194 self._maybe_stamp_started() 195 except Exception: 196 logger.debug("parlot: recording started stamp failed", exc_info=True)
Initialize the audio buffer processor.
Arguments:
- sample_rate: Desired output sample rate. If None, uses source rate.
- num_channels: Number of channels (1 for mono, 2 for stereo). Defaults to 1.
- buffer_size: Size of buffer before triggering events. 0 for no buffering.
- enable_turn_audio: Whether turn audio event handlers should be triggered.
- auto_start_recording: Whether to start recording automatically when
the pipeline starts, without requiring a call to
start_recording()or anAudioBufferStartRecordingFrame. - **kwargs: Additional arguments passed to parent class.
198 async def process_frame(self, frame, direction: FrameDirection): # type: ignore[override] 199 # Complete *before* End/Cancel propagate: pushing CancelFrame ends the 200 # Pipecat conversation span, which calls close_session and clears the 201 # active session — finish() would then skip /complete (no session id). 202 if isinstance(frame, (EndFrame, CancelFrame)): 203 try: 204 await self.finish() 205 except Exception: 206 logger.warning("parlot: recording finish on end failed", exc_info=True) 207 await super().process_frame(frame, direction) 208 return 209 await super().process_frame(frame, direction)
Process incoming audio frames and manage audio buffers.
Arguments:
- frame: The frame to process.
- direction: The direction of frame flow in the pipeline.
397 async def finish(self) -> None: 398 """Flush last partial segment and POST ``/complete``. Fail-open.""" 399 if self._finishing or self._finished: 400 return 401 self._finishing = True 402 try: 403 from ._auto import unregister_recording_processor 404 405 unregister_recording_processor(self) 406 except Exception: 407 pass 408 409 # Single task so CancelledError waits for the same work (no double /complete). 410 task = asyncio.create_task( 411 self._finish_inner(), name="parlot-recording-finish" 412 ) 413 try: 414 await asyncio.wait_for(asyncio.shield(task), timeout=CLOSE_TIMEOUT_S) 415 except asyncio.TimeoutError: 416 stamp_recording_error(self._session_span(), "complete_timeout") 417 task.cancel() 418 try: 419 await task 420 except (asyncio.CancelledError, Exception): 421 pass 422 except asyncio.CancelledError: 423 # Outer cancel: wait for the shielded task; do not start a second finish. 424 try: 425 await asyncio.shield(task) 426 except Exception as exc: 427 stamp_recording_error( 428 self._session_span(), f"complete_failed:{type(exc).__name__}" 429 ) 430 raise 431 except Exception as exc: 432 stamp_recording_error( 433 self._session_span(), f"complete_failed:{type(exc).__name__}" 434 ) 435 logger.warning("parlot: recording finish failed — %s", exc, exc_info=True) 436 finally: 437 # Safety net if drain path never set the gate. 438 self._finished = True
Flush last partial segment and POST /complete. Fail-open.
30def stamp_external_recording( 31 *, 32 audio_uri: str, 33 anchor_wall_ms: int, 34 mode: str = "link", 35 format: str = "opus_ogg", 36 sample_count: Optional[int] = None, 37 wall_end_ms: Optional[int] = None, 38 pii_redaction_required: bool = False, 39 span: Any = None, 40) -> bool: 41 """BYO recording stamp. 42 43 * ``mode="link"`` — external URI only. Rejected when *pii_redaction_required*. 44 * ``mode="ingest"`` — caller already uploaded via grant; stamp as uploaded. 45 46 Returns False when rejected or no session span. 47 """ 48 target = span if span is not None else get_active_session_span() 49 if target is None: 50 logger.warning("parlot: stamp_external_recording skipped — no session span") 51 return False 52 53 if mode == "link" and pii_redaction_required: 54 stamp_recording_error( 55 target, 56 "byo_link_rejected:tenant_pii_redaction_enabled", 57 ) 58 return False 59 60 source = "byo_link" if mode == "link" else "byo_ingest" 61 stamp_recording_started( 62 target, 63 anchor_wall_ms=anchor_wall_ms, 64 source=source, 65 format=format, 66 ) 67 stamp_recording_uploaded( 68 target, 69 audio_uri=audio_uri, 70 partial=False, 71 sample_count=sample_count, 72 wall_end_ms=wall_end_ms, 73 format=format, 74 ) 75 return True
BYO recording stamp.
mode="link"— external URI only. Rejected when pii_redaction_required.mode="ingest"— caller already uploaded via grant; stamp as uploaded.
Returns False when rejected or no session span.
89def add_platform_ref( 90 kind: str, 91 value: str, 92 *, 93 framework: str = "custom", 94) -> None: 95 """ 96 Attach a searchable external ID to the active Parlot session. 97 98 Stamps ``platform.ref.{kind}`` (and the primary triple when this is the 99 first ref) on the live session span so the session can be found by that 100 value in Parlot search / resolve. 101 102 Args: 103 kind: Identifier type (e.g. ``"crm_ticket"``, ``"order_number"``, 104 ``"call_sid"``). 105 value: Unique identifier value (e.g. ``"TKT-9921"``). 106 framework: Originating framework name. Defaults to ``"custom"``. 107 108 Example:: 109 110 from parlot.instrumentation.livekit import add_platform_ref 111 112 add_platform_ref("crm_ticket", "TKT-9") 113 """ 114 kind = str(kind or "").strip() 115 value = str(value or "").strip() 116 framework = str(framework or "custom").strip() or "custom" 117 if not kind or not value: 118 return 119 span = get_active_session_span() 120 if span is None: 121 return 122 stamp_platform_refs(span, [(framework, kind, value)])
Attach a searchable external ID to the active Parlot session.
Stamps platform.ref.{kind} (and the primary triple when this is the
first ref) on the live session span so the session can be found by that
value in Parlot search / resolve.
Arguments:
- kind: Identifier type (e.g.
"crm_ticket","order_number","call_sid"). - value: Unique identifier value (e.g.
"TKT-9921"). - framework: Originating framework name. Defaults to
"custom".
Example::
from parlot.instrumentation.livekit import add_platform_ref
add_platform_ref("crm_ticket", "TKT-9")
50@contextmanager 51def human_escalation(label: str | None = None) -> Iterator[None]: 52 """Mark the next participant who joins the active session as a human rep. 53 54 Args: 55 label: Optional role or team label for the incoming human representative. 56 """ 57 token = _pending_escalation_label.set(label) 58 try: 59 yield 60 finally: 61 _pending_escalation_label.reset(token)
Mark the next participant who joins the active session as a human rep.
Arguments:
- label: Optional role or team label for the incoming human representative.
19def record_human_rep(participant_id: str, *, label: str | None = None) -> None: 20 """ 21 Mark a participant as a human representative. 22 23 Stamps ``session.topology.agents`` on the active session span and registers 24 the participant for ``turn.participant_role=human_rep`` on future turns. 25 26 Args: 27 participant_id: Participant identifier within the room/session. 28 label: Optional human-readable name (e.g. ``"Tier 2 Escalation Desk"``). 29 """ 30 participant_id = str(participant_id or "").strip() 31 if not participant_id: 32 return 33 34 state = get_active_session() 35 if state is not None: 36 state.human_rep_participant_ids.add(participant_id) 37 entry: dict[str, str] = {"id": participant_id, "role": "human_rep"} 38 if label: 39 entry["label"] = label 40 if not any(a.get("id") == participant_id for a in state.topology_agents): 41 state.topology_agents.append(entry) 42 43 span = get_active_session_span() 44 if span is not None and state is not None and state.topology_agents: 45 span.set_attribute( 46 ATTR_SESSION_TOPOLOGY_AGENTS, json.dumps(state.topology_agents) 47 )
Mark a participant as a human representative.
Stamps session.topology.agents on the active session span and registers
the participant for turn.participant_role=human_rep on future turns.
Arguments:
- participant_id: Participant identifier within the room/session.
- label: Optional human-readable name (e.g.
"Tier 2 Escalation Desk").
20def set_session_attribute(key: str, value: str | int | float | bool) -> None: 21 """ 22 Stamp one custom attribute on the active session under ``session.metadata.*``. 23 24 Keys are normalized to ``session.metadata.<key>``. Values are stored as 25 strings on the live session span and remembered on session state so they 26 are also present on ``parlot.session.close``. 27 28 Args: 29 key: Attribute name. If not prefixed with ``session.metadata.``, the 30 prefix is added automatically. 31 value: Value to record (``str``, ``int``, ``float``, or ``bool``). 32 """ 33 full_key = session_metadata_key(key) 34 if not full_key or full_key == ATTR_SESSION_METADATA_PREFIX: 35 return 36 str_value = value if isinstance(value, str) else str(value) 37 38 state = get_active_session() 39 if state is not None: 40 state.custom_metadata[full_key] = str_value 41 42 span = get_active_session_span() 43 if span is not None and hasattr(span, "set_attribute"): 44 span.set_attribute(full_key, str_value)
Stamp one custom attribute on the active session under session.metadata.*.
Keys are normalized to session.metadata.<key>. Values are stored as
strings on the live session span and remembered on session state so they
are also present on parlot.session.close.
Arguments:
- key: Attribute name. If not prefixed with
session.metadata., the prefix is added automatically. - value: Value to record (
str,int,float, orbool).
47def set_session_metadata(**pairs: str | int | float | bool) -> None: 48 """ 49 Attach custom key/value metadata to the active Parlot session. 50 51 Each keyword becomes ``session.metadata.<name>`` on the session span and 52 appears in session detail in the Parlot UI. 53 54 Args: 55 **pairs: Keyword metadata pairs (values ``str``, ``int``, ``float``, 56 or ``bool``). 57 58 Example:: 59 60 from parlot.instrumentation.livekit import set_session_metadata 61 62 set_session_metadata(order_id="12345", crm_ticket="TKT-9") 63 """ 64 for key, value in pairs.items(): 65 set_session_attribute(key, value)
Attach custom key/value metadata to the active Parlot session.
Each keyword becomes session.metadata.<name> on the session span and
appears in session detail in the Parlot UI.
Arguments:
- **pairs: Keyword metadata pairs (values
str,int,float, orbool).
Example::
from parlot.instrumentation.livekit import set_session_metadata
set_session_metadata(order_id="12345", crm_ticket="TKT-9")
46def stamp_platform_refs( 47 span: Any, 48 refs: list[tuple[str, str, str]], 49) -> None: 50 """Stamp ``platform.ref.*`` triples onto a span. 51 52 ``refs`` is a list of ``(framework, kind, value)`` tuples, e.g. 53 ``("livekit", "room_sid", "RM_abc")``. The first tuple is also written 54 to the canonical triple attributes (``platform.ref.framework/kind/value``) 55 so backends can pivot on a single primary ref. 56 57 Every tuple is also written as a flat ``platform.ref.{kind} = value`` key 58 for ingestion fallbacks. 59 60 Args: 61 span: A live OTel span (``set_attribute``) or a ``ReadableSpan`` with a 62 mutable ``_attributes`` dict. 63 refs: Non-empty list of reference triples. 64 """ 65 if not refs: 66 return 67 68 def _write(key: str, value: str) -> None: 69 if hasattr(span, "set_attribute") and callable(span.set_attribute): 70 try: 71 span.set_attribute(key, value) 72 return 73 except Exception: 74 pass 75 try: 76 ParlotBaseProcessor._set(span, key, value) 77 except Exception: 78 return 79 80 fw, kind, val = refs[0] 81 _write(ATTR_PLATFORM_FRAMEWORK, fw) 82 _write(ATTR_PLATFORM_KIND, kind) 83 _write(ATTR_PLATFORM_VALUE, val) 84 85 for _fw_i, kind_i, val_i in refs: 86 _write(platform_ref_flat_key(kind_i), val_i)
Stamp platform.ref.* triples onto a span.
refs is a list of (framework, kind, value) tuples, e.g.
("livekit", "room_sid", "RM_abc"). The first tuple is also written
to the canonical triple attributes (platform.ref.framework/kind/value)
so backends can pivot on a single primary ref.
Every tuple is also written as a flat platform.ref.{kind} = value key
for ingestion fallbacks.
Arguments:
- span: A live OTel span (
set_attribute) or aReadableSpanwith a mutable_attributesdict. - refs: Non-empty list of reference triples.