Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(call): speaker diarization (#2846)

Will Hutchinsone68dd3c61a63
diff --git a/agents/transcription/transcriber.py b/agents/transcription/transcriber.py
index a45d28f4fc..2b1865c1f4 100644
--- a/agents/transcription/transcriber.py
+++ b/agents/transcription/transcriber.py
@@ -2,6 +2,7 @@ import asyncio
import logging
import os
import uuid
+from collections import Counter
from datetime import datetime, timezone
import httpx
@@ -18,6 +19,7 @@ from livekit.agents import (
inference,
llm,
room_io,
+ stt as stt_pkg,
utils,
WorkerOptions,
)
@@ -56,12 +58,49 @@ class Transcriber(Agent):
"numerals": True,
"interim_results": True,
"no_delay": True,
+ # Emit per-word speaker labels so we can attribute segments to
+ # distinct voices even when one audio track carries multiple.
+ "diarize": True,
},
),
)
self.participant_identity = participant_identity
self.channel_id = channel_id
self.http_client = http_client
+ # Word counts per Deepgram speaker int, accumulated across final
+ # transcripts inside a single user turn and cleared on turn completion.
+ self._pending_speakers: Counter[int] = Counter()
+ # Deepgram's speaker ints are only unique within one streaming session.
+ # Namespace them with a nonce regenerated per Transcriber so a reconnect
+ # doesn't silently merge two different humans under the same UUID.
+ self._speaker_namespace = uuid.uuid4().hex
+ self._speaker_uuids: dict[int, str] = {}
+
+ def _resolve_diarized_speaker_id(self, dg_speaker: int) -> str:
+ cached = self._speaker_uuids.get(dg_speaker)
+ if cached is not None:
+ return cached
+ seed = (
+ f"{self.channel_id}:{self.participant_identity}:"
+ f"{self._speaker_namespace}:{dg_speaker}"
+ )
+ value = str(uuid.uuid5(uuid.NAMESPACE_URL, seed))
+ self._speaker_uuids[dg_speaker] = value
+ return value
+
+ async def stt_node(self, audio, model_settings):
+ async for event in super().stt_node(audio, model_settings):
+ if isinstance(event, stt_pkg.SpeechEvent) and (
+ event.type == stt_pkg.SpeechEventType.FINAL_TRANSCRIPT
+ ):
+ alt = event.alternatives[0] if event.alternatives else None
+ for word in getattr(alt, "words", None) or ():
+ speaker = getattr(word, "speaker", None)
+ if speaker is None:
+ speaker = getattr(word, "speaker_id", None)
+ if speaker is not None:
+ self._pending_speakers[int(speaker)] += 1
+ yield event
async def on_user_turn_completed(
self, chat_ctx: llm.ChatContext, new_message: llm.ChatMessage
@@ -86,9 +125,16 @@ class Transcriber(Agent):
)
segment_id = str(uuid.uuid5(uuid.NAMESPACE_URL, segment_seed))
+ diarized_speaker_id = None
+ if self._pending_speakers:
+ dominant_speaker, _ = self._pending_speakers.most_common(1)[0]
+ diarized_speaker_id = self._resolve_diarized_speaker_id(dominant_speaker)
+ self._pending_speakers.clear()
+
segment = {
"segmentId": segment_id,
"speakerId": self.participant_identity,
+ "diarizedSpeakerId": diarized_speaker_id,
"content": content,
"startedAt": timestamp,
"endedAt": timestamp,
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
index b63ac8069f..6622772ddb 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/schemas.ts
@@ -527,6 +527,7 @@ export const ReadCallRecordResponse = z.object({
transcript: z.array(
z.object({
content: z.string(),
+ diarizedSpeakerId: z.union([z.string(), z.null()]).optional(),
endedAt: z
.union([z.string().datetime({ offset: true }), z.null()])
.optional(),
diff --git a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
index 67fd9933b9..a8c5a51684 100644
--- a/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
+++ b/js/app/packages/service-clients/service-cognition/generated/tools/types.ts
@@ -1030,6 +1030,11 @@ export interface ReadCallRecordResponse {
* The transcribed text.
*/
content: string;
+ /**
+ * Stable per-speaker identifier produced by diarization, when available.
+ * Distinguishes multiple speakers sharing one audio track.
+ */
+ diarizedSpeakerId?: string | null;
/**
* When the speaker stopped (if known).
*/
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/callRecordTranscriptSegment.ts b/js/app/packages/service-clients/service-storage/generated/schemas/callRecordTranscriptSegment.ts
index 4da77d7a0c..c4f29ecdd8 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/callRecordTranscriptSegment.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/callRecordTranscriptSegment.ts
@@ -4,6 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { CallRecordTranscriptSegmentDiarizedSpeakerId } from './callRecordTranscriptSegmentDiarizedSpeakerId';
import type { CallRecordTranscriptSegmentEndedAt } from './callRecordTranscriptSegmentEndedAt';
import type { CallRecordTranscriptSegmentSegmentId } from './callRecordTranscriptSegmentSegmentId';
@@ -13,6 +14,10 @@ import type { CallRecordTranscriptSegmentSegmentId } from './callRecordTranscrip
export interface CallRecordTranscriptSegment {
/** The transcribed text content. */
content: string;
+ /** Stable per-speaker identifier produced by the STT provider's diarization
+pass. Unique across tracks in the call. `None` when the provider didn't
+return a speaker label. */
+ diarizedSpeakerId?: CallRecordTranscriptSegmentDiarizedSpeakerId;
/** When the speaker stopped (if known). */
endedAt?: CallRecordTranscriptSegmentEndedAt;
/** LiveKit segment ID (nullable for archived records). */
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/callRecordTranscriptSegmentDiarizedSpeakerId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/callRecordTranscriptSegmentDiarizedSpeakerId.ts
new file mode 100644
index 0000000000..8bc72eeea7
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/callRecordTranscriptSegmentDiarizedSpeakerId.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Stable per-speaker identifier produced by the STT provider's diarization
+pass. Unique across tracks in the call. `None` when the provider didn't
+return a speaker label.
+ */
+export type CallRecordTranscriptSegmentDiarizedSpeakerId = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index 637c91b9bf..5c4200db6e 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -98,6 +98,7 @@ export * from './callRecordPreviewOneOfFourAllOf';
export * from './callRecordPreviewOneOfFourAllOfType';
export * from './callRecordRecordingUrl';
export * from './callRecordTranscriptSegment';
+export * from './callRecordTranscriptSegmentDiarizedSpeakerId';
export * from './callRecordTranscriptSegmentEndedAt';
export * from './callRecordTranscriptSegmentSegmentId';
export * from './callTokenResponse';
@@ -639,6 +640,7 @@ export * from './threadDeletedAt';
export * from './threadResponse';
export * from './threadUpdatedAt';
export * from './transcriptSegmentRequest';
+export * from './transcriptSegmentRequestDiarizedSpeakerId';
export * from './transcriptSegmentRequestEndedAt';
export * from './typedSuccessResponse';
export * from './typedSuccessResponseDataOneOf';
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts
index 4eb33cdfc5..4e41362344 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequest.ts
@@ -4,6 +4,7 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { TranscriptSegmentRequestDiarizedSpeakerId } from './transcriptSegmentRequestDiarizedSpeakerId';
import type { TranscriptSegmentRequestEndedAt } from './transcriptSegmentRequestEndedAt';
/**
@@ -12,6 +13,10 @@ import type { TranscriptSegmentRequestEndedAt } from './transcriptSegmentRequest
export interface TranscriptSegmentRequest {
/** The transcribed text content. */
content: string;
+ /** Stable per-speaker identifier produced by the STT provider's diarization
+pass. Namespaced upstream by audio track so values are unique across all
+tracks in a call. `None` when the provider didn't return a speaker label. */
+ diarizedSpeakerId?: TranscriptSegmentRequestDiarizedSpeakerId;
/** When the speaker stopped talking for this segment. */
endedAt?: TranscriptSegmentRequestEndedAt;
/** Whether this is a final transcription (not interim). */
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestDiarizedSpeakerId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestDiarizedSpeakerId.ts
new file mode 100644
index 0000000000..3888ad0908
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/transcriptSegmentRequestDiarizedSpeakerId.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Stable per-speaker identifier produced by the STT provider's diarization
+pass. Namespaced upstream by audio track so values are unique across all
+tracks in a call. `None` when the provider didn't return a speaker label.
+ */
+export type TranscriptSegmentRequestDiarizedSpeakerId = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 1b9a0de8c2..d6a9897695 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -964,6 +964,12 @@ export const getCallRecordResponse = zod
zod
.object({
content: zod.string().describe('The transcribed text content.'),
+ diarizedSpeakerId: zod
+ .string()
+ .nullish()
+ .describe(
+ "Stable per-speaker identifier produced by the STT provider's diarization\npass. Unique across tracks in the call. `None` when the provider didn't\nreturn a speaker label."
+ ),
endedAt: zod
.string()
.datetime({})
@@ -1140,6 +1146,12 @@ export const ingestTranscriptParams = zod.object({
export const ingestTranscriptBody = zod
.object({
content: zod.string().describe('The transcribed text content.'),
+ diarizedSpeakerId: zod
+ .string()
+ .nullish()
+ .describe(
+ "Stable per-speaker identifier produced by the STT provider's diarization\npass. Namespaced upstream by audio track so values are unique across all\ntracks in a call. `None` when the provider didn't return a speaker label."
+ ),
endedAt: zod
.string()
.datetime({})
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 839cf3041e..44fa95b1a3 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -6391,6 +6391,10 @@
"type": "string",
"description": "The transcribed text content."
},
+ "diarizedSpeakerId": {
+ "type": ["string", "null"],
+ "description": "Stable per-speaker identifier produced by the STT provider's diarization\npass. Unique across tracks in the call. `None` when the provider didn't\nreturn a speaker label."
+ },
"endedAt": {
"type": ["string", "null"],
"format": "date-time",
@@ -11675,6 +11679,10 @@
"type": "string",
"description": "The transcribed text content."
},
+ "diarizedSpeakerId": {
+ "type": ["string", "null"],
+ "description": "Stable per-speaker identifier produced by the STT provider's diarization\npass. Namespaced upstream by audio track so values are unique across all\ntracks in a call. `None` when the provider didn't return a speaker label."
+ },
"endedAt": {
"type": ["string", "null"],
"format": "date-time",
diff --git a/rust/cloud-storage/call/.sqlx/query-12c11b297513c688c8daf5bf541aa13c5f3bfa941859a5fdb9c7bad1654a0ec7.json b/rust/cloud-storage/call/.sqlx/query-12c11b297513c688c8daf5bf541aa13c5f3bfa941859a5fdb9c7bad1654a0ec7.json
new file mode 100644
index 0000000000..ac6329e83c
--- /dev/null
+++ b/rust/cloud-storage/call/.sqlx/query-12c11b297513c688c8daf5bf541aa13c5f3bfa941859a5fdb9c7bad1654a0ec7.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO call_transcripts (call_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num)\n VALUES ($1, $2, $3, $4, $5, $6, $7, (\n SELECT COALESCE(MAX(sequence_num), 0) + 1\n FROM call_transcripts\n WHERE call_id = $1\n ))\n ON CONFLICT (call_id, segment_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "12c11b297513c688c8daf5bf541aa13c5f3bfa941859a5fdb9c7bad1654a0ec7"
+}
diff --git a/rust/cloud-storage/call/.sqlx/query-2a43904e78a134b93cef3613fa69ed67bdd5fe2f059e97d3e74a11d478647c86.json b/rust/cloud-storage/call/.sqlx/query-2a43904e78a134b93cef3613fa69ed67bdd5fe2f059e97d3e74a11d478647c86.json
deleted file mode 100644
index 301e5dce85..0000000000
--- a/rust/cloud-storage/call/.sqlx/query-2a43904e78a134b93cef3613fa69ed67bdd5fe2f059e97d3e74a11d478647c86.json
+++ /dev/null
@@ -1,19 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO call_transcripts (call_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)\n VALUES ($1, $2, $3, $4, $5, $6, (\n SELECT COALESCE(MAX(sequence_num), 0) + 1\n FROM call_transcripts\n WHERE call_id = $1\n ))\n ON CONFLICT (call_id, segment_id) DO NOTHING\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Text",
- "Text",
- "Text",
- "Timestamptz",
- "Timestamptz"
- ]
- },
- "nullable": []
- },
- "hash": "2a43904e78a134b93cef3613fa69ed67bdd5fe2f059e97d3e74a11d478647c86"
-}
diff --git a/rust/cloud-storage/call/.sqlx/query-669b1e8428a2dff7724bb47104efc739eb157f1b1dbe21cb607a0fc1f87ebe30.json b/rust/cloud-storage/call/.sqlx/query-669b1e8428a2dff7724bb47104efc739eb157f1b1dbe21cb607a0fc1f87ebe30.json
new file mode 100644
index 0000000000..7d528c9086
--- /dev/null
+++ b/rust/cloud-storage/call/.sqlx/query-669b1e8428a2dff7724bb47104efc739eb157f1b1dbe21cb607a0fc1f87ebe30.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num)\n SELECT $1, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num\n FROM call_transcripts\n WHERE call_id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "669b1e8428a2dff7724bb47104efc739eb157f1b1dbe21cb607a0fc1f87ebe30"
+}
diff --git a/rust/cloud-storage/call/.sqlx/query-a33089d525147261468bbf9c4522b251d3ddd6d499f77fb4e102787111195cee.json b/rust/cloud-storage/call/.sqlx/query-9b0034065161dec2180a9714d46745b36e32ab06043cd636bbfab029d173bf72.json
similarity index 64%
rename from rust/cloud-storage/call/.sqlx/query-a33089d525147261468bbf9c4522b251d3ddd6d499f77fb4e102787111195cee.json
rename to rust/cloud-storage/call/.sqlx/query-9b0034065161dec2180a9714d46745b36e32ab06043cd636bbfab029d173bf72.json
index 54a1434464..0288a507b7 100644
--- a/rust/cloud-storage/call/.sqlx/query-a33089d525147261468bbf9c4522b251d3ddd6d499f77fb4e102787111195cee.json
+++ b/rust/cloud-storage/call/.sqlx/query-9b0034065161dec2180a9714d46745b36e32ab06043cd636bbfab029d173bf72.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT segment_id, speaker_id, content, started_at, ended_at, sequence_num\n FROM call_record_transcripts\n WHERE call_record_id = $1\n ORDER BY sequence_num ASC\n ",
+ "query": "\n SELECT segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num\n FROM call_record_transcripts\n WHERE call_record_id = $1\n ORDER BY sequence_num ASC\n ",
"describe": {
"columns": [
{
@@ -15,21 +15,26 @@
},
{
"ordinal": 2,
- "name": "content",
+ "name": "diarized_speaker_id",
"type_info": "Text"
},
{
"ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
"name": "started_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 4,
+ "ordinal": 5,
"name": "ended_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 5,
+ "ordinal": 6,
"name": "sequence_num",
"type_info": "Int4"
}
@@ -42,11 +47,12 @@
"nullable": [
true,
false,
+ true,
false,
false,
true,
false
]
},
- "hash": "a33089d525147261468bbf9c4522b251d3ddd6d499f77fb4e102787111195cee"
+ "hash": "9b0034065161dec2180a9714d46745b36e32ab06043cd636bbfab029d173bf72"
}
diff --git a/rust/cloud-storage/call/.sqlx/query-b564cb72641ccbd1fede2f0fac3167e192665f8dda8043f7a27c22a2eec49662.json b/rust/cloud-storage/call/.sqlx/query-b564cb72641ccbd1fede2f0fac3167e192665f8dda8043f7a27c22a2eec49662.json
deleted file mode 100644
index e7ba0e104f..0000000000
--- a/rust/cloud-storage/call/.sqlx/query-b564cb72641ccbd1fede2f0fac3167e192665f8dda8043f7a27c22a2eec49662.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)\n SELECT $1, segment_id, speaker_id, content, started_at, ended_at, sequence_num\n FROM call_transcripts\n WHERE call_id = $2\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Uuid",
- "Uuid"
- ]
- },
- "nullable": []
- },
- "hash": "b564cb72641ccbd1fede2f0fac3167e192665f8dda8043f7a27c22a2eec49662"
-}
diff --git a/rust/cloud-storage/call/.sqlx/query-a6882145e34b9196f175874ed47a08b4739179533ed3369d181ce07b3d2f5d80.json b/rust/cloud-storage/call/.sqlx/query-b683cd2f7a93ff5eb1264823b9a4ce8e500abd7c2e170ce4efc4fa06123e82f6.json
similarity index 64%
rename from rust/cloud-storage/call/.sqlx/query-a6882145e34b9196f175874ed47a08b4739179533ed3369d181ce07b3d2f5d80.json
rename to rust/cloud-storage/call/.sqlx/query-b683cd2f7a93ff5eb1264823b9a4ce8e500abd7c2e170ce4efc4fa06123e82f6.json
index 776100dc7a..f9b38a1926 100644
--- a/rust/cloud-storage/call/.sqlx/query-a6882145e34b9196f175874ed47a08b4739179533ed3369d181ce07b3d2f5d80.json
+++ b/rust/cloud-storage/call/.sqlx/query-b683cd2f7a93ff5eb1264823b9a4ce8e500abd7c2e170ce4efc4fa06123e82f6.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT segment_id, speaker_id, content, started_at, ended_at, sequence_num\n FROM call_transcripts\n WHERE call_id = $1\n ORDER BY sequence_num ASC\n ",
+ "query": "\n SELECT segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num\n FROM call_transcripts\n WHERE call_id = $1\n ORDER BY sequence_num ASC\n ",
"describe": {
"columns": [
{
@@ -15,21 +15,26 @@
},
{
"ordinal": 2,
- "name": "content",
+ "name": "diarized_speaker_id",
"type_info": "Text"
},
{
"ordinal": 3,
+ "name": "content",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
"name": "started_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 4,
+ "ordinal": 5,
"name": "ended_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 5,
+ "ordinal": 6,
"name": "sequence_num",
"type_info": "Int4"
}
@@ -42,11 +47,12 @@
"nullable": [
false,
false,
+ true,
false,
false,
true,
false
]
},
- "hash": "a6882145e34b9196f175874ed47a08b4739179533ed3369d181ce07b3d2f5d80"
+ "hash": "b683cd2f7a93ff5eb1264823b9a4ce8e500abd7c2e170ce4efc4fa06123e82f6"
}
diff --git a/rust/cloud-storage/call/fixtures/call_repo.sql b/rust/cloud-storage/call/fixtures/call_repo.sql
index 6a62faefb5..75a163d5d8 100644
--- a/rust/cloud-storage/call/fixtures/call_repo.sql
+++ b/rust/cloud-storage/call/fixtures/call_repo.sql
@@ -55,10 +55,10 @@ INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_a
('00000000-0000-0000-0000-0000000ca2ed', 'macro|[email protected]', '2024-01-01 10:00:00+00', '2024-01-01 10:05:00+00'),
('00000000-0000-0000-0000-0000000ca2ed', 'macro|[email protected]', '2024-01-01 10:01:00+00', '2024-01-01 10:04:30+00');
-INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num) VALUES
- ('00000000-0000-0000-0000-0000000ca2ed', 'seg-arch-1', 'macro|[email protected]', 'archived hello',
+INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num) VALUES
+ ('00000000-0000-0000-0000-0000000ca2ed', 'seg-arch-1', 'macro|[email protected]', 'spk-arch-a0', 'archived hello',
'2024-01-01 10:00:05+00', '2024-01-01 10:00:07+00', 1),
- ('00000000-0000-0000-0000-0000000ca2ed', 'seg-arch-2', 'macro|[email protected]', 'archived reply',
+ ('00000000-0000-0000-0000-0000000ca2ed', 'seg-arch-2', 'macro|[email protected]', NULL, 'archived reply',
'2024-01-01 10:00:08+00', '2024-01-01 10:00:10+00', 2);
-- entity_access grants for the active call (owner + channel view).
diff --git a/rust/cloud-storage/call/src/domain/models.rs b/rust/cloud-storage/call/src/domain/models.rs
index f36c41b1f6..e21987d549 100644
--- a/rust/cloud-storage/call/src/domain/models.rs
+++ b/rust/cloud-storage/call/src/domain/models.rs
@@ -129,6 +129,11 @@ pub struct TranscriptSegmentRequest {
pub segment_id: String,
/// The speaker's user ID (from `lk.transcribed_track_id`).
pub speaker_id: String,
+ /// Stable per-speaker identifier produced by the STT provider's diarization
+ /// pass. Namespaced upstream by audio track so values are unique across all
+ /// tracks in a call. `None` when the provider didn't return a speaker label.
+ #[serde(default)]
+ pub diarized_speaker_id: Option<String>,
/// The transcribed text content.
pub content: String,
/// When the speaker started talking for this segment.
@@ -162,6 +167,11 @@ pub struct CallRecordTranscriptSegment {
pub segment_id: Option<String>,
/// The speaker's user ID.
pub speaker_id: String,
+ /// Stable per-speaker identifier produced by the STT provider's diarization
+ /// pass. Unique across tracks in the call. `None` when the provider didn't
+ /// return a speaker label.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub diarized_speaker_id: Option<String>,
/// The transcribed text content.
pub content: String,
/// When the speaker started this segment.
diff --git a/rust/cloud-storage/call/src/inbound/toolset/read_call_record.rs b/rust/cloud-storage/call/src/inbound/toolset/read_call_record.rs
index a8c5b3e953..70d8eaa8d8 100644
--- a/rust/cloud-storage/call/src/inbound/toolset/read_call_record.rs
+++ b/rust/cloud-storage/call/src/inbound/toolset/read_call_record.rs
@@ -20,6 +20,10 @@ use super::CallToolContext;
pub struct TranscriptSegment {
/// The speaker's user id.
pub speaker_id: String,
+ /// Stable per-speaker identifier produced by diarization, when available.
+ /// Distinguishes multiple speakers sharing one audio track.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub diarized_speaker_id: Option<String>,
/// The transcribed text.
pub content: String,
/// When the speaker started this segment.
@@ -96,6 +100,7 @@ where
.into_iter()
.map(|s| TranscriptSegment {
speaker_id: s.speaker_id,
+ diarized_speaker_id: s.diarized_speaker_id,
content: s.content,
started_at: s.started_at,
ended_at: s.ended_at,
diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
index 0e982f2b9f..6491cd1883 100644
--- a/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo.rs
@@ -647,8 +647,8 @@ impl CallRepository for PgCallRepo {
// Copy transcripts to call_record_transcripts.
sqlx::query!(
r#"
- INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)
- SELECT $1, segment_id, speaker_id, content, started_at, ended_at, sequence_num
+ INSERT INTO call_record_transcripts (call_record_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num)
+ SELECT $1, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num
FROM call_transcripts
WHERE call_id = $2
"#,
@@ -731,8 +731,8 @@ impl CallRepository for PgCallRepo {
) -> Result<(), Self::Err> {
sqlx::query!(
r#"
- INSERT INTO call_transcripts (call_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)
- VALUES ($1, $2, $3, $4, $5, $6, (
+ INSERT INTO call_transcripts (call_id, segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, (
SELECT COALESCE(MAX(sequence_num), 0) + 1
FROM call_transcripts
WHERE call_id = $1
@@ -742,6 +742,7 @@ impl CallRepository for PgCallRepo {
call_id,
segment.segment_id,
segment.speaker_id,
+ segment.diarized_speaker_id,
segment.content,
segment.started_at,
segment.ended_at,
@@ -800,7 +801,7 @@ impl CallRepository for PgCallRepo {
let transcript = sqlx::query!(
r#"
- SELECT segment_id, speaker_id, content, started_at, ended_at, sequence_num
+ SELECT segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num
FROM call_transcripts
WHERE call_id = $1
ORDER BY sequence_num ASC
@@ -813,6 +814,7 @@ impl CallRepository for PgCallRepo {
.map(|row| CallRecordTranscriptSegment {
segment_id: Some(row.segment_id),
speaker_id: row.speaker_id,
+ diarized_speaker_id: row.diarized_speaker_id,
content: row.content,
started_at: row.started_at,
ended_at: row.ended_at,
@@ -876,7 +878,7 @@ impl CallRepository for PgCallRepo {
let transcript = sqlx::query!(
r#"
- SELECT segment_id, speaker_id, content, started_at, ended_at, sequence_num
+ SELECT segment_id, speaker_id, diarized_speaker_id, content, started_at, ended_at, sequence_num
FROM call_record_transcripts
WHERE call_record_id = $1
ORDER BY sequence_num ASC
@@ -889,6 +891,7 @@ impl CallRepository for PgCallRepo {
.map(|row| CallRecordTranscriptSegment {
segment_id: row.segment_id,
speaker_id: row.speaker_id,
+ diarized_speaker_id: row.diarized_speaker_id,
content: row.content,
started_at: row.started_at,
ended_at: row.ended_at,
diff --git a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs
index cf0c298001..cb3685d3cc 100644
--- a/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs
+++ b/rust/cloud-storage/call/src/outbound/pg_call_repo/test.rs
@@ -688,6 +688,7 @@ async fn create_transcript_segment_stores_and_increments_sequence(
let seg1 = TranscriptSegmentRequest {
segment_id: "seg-001".to_string(),
speaker_id: USER_A.to_string(),
+ diarized_speaker_id: Some("spk-a0".to_string()),
content: "hello world".to_string(),
started_at: now,
ended_at: Some(now),
@@ -696,6 +697,7 @@ async fn create_transcript_segment_stores_and_increments_sequence(
let seg2 = TranscriptSegmentRequest {
segment_id: "seg-002".to_string(),
speaker_id: USER_B.to_string(),
+ diarized_speaker_id: None,
content: "hi there".to_string(),
started_at: now,
ended_at: Some(now),
@@ -710,7 +712,7 @@ async fn create_transcript_segment_stores_and_increments_sequence(
let rows = sqlx::query!(
r#"
- SELECT speaker_id, content, sequence_num
+ SELECT speaker_id, diarized_speaker_id, content, sequence_num
FROM call_transcripts
WHERE call_id = $1
ORDER BY sequence_num ASC
@@ -723,8 +725,10 @@ async fn create_transcript_segment_stores_and_increments_sequence(
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].content, "hello world");
assert_eq!(rows[0].sequence_num, 1);
+ assert_eq!(rows[0].diarized_speaker_id.as_deref(), Some("spk-a0"));
assert_eq!(rows[1].content, "hi there");
assert_eq!(rows[1].sequence_num, 2);
+ assert_eq!(rows[1].diarized_speaker_id, None);
Ok(())
}
@@ -742,6 +746,7 @@ async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Result
let seg = TranscriptSegmentRequest {
segment_id: "seg-archive-001".to_string(),
speaker_id: USER_A.to_string(),
+ diarized_speaker_id: Some("spk-archive-a0".to_string()),
content: "test transcript".to_string(),
started_at: now,
ended_at: Some(now),
@@ -755,7 +760,7 @@ async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Result
// Transcripts should be in call_record_transcripts.
let transcripts = sqlx::query!(
r#"
- SELECT speaker_id, content, sequence_num
+ SELECT speaker_id, diarized_speaker_id, content, sequence_num
FROM call_record_transcripts
WHERE call_record_id = $1
"#,
@@ -767,6 +772,10 @@ async fn archive_call_copies_transcripts(pool: Pool<Postgres>) -> anyhow::Result
assert_eq!(transcripts.len(), 1);
assert_eq!(transcripts[0].content, "test transcript");
assert_eq!(transcripts[0].speaker_id, USER_A.as_ref());
+ assert_eq!(
+ transcripts[0].diarized_speaker_id.as_deref(),
+ Some("spk-archive-a0")
+ );
assert_eq!(transcripts[0].sequence_num, 1);
// Ephemeral transcripts should be gone (cascaded).
@@ -797,6 +806,7 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Re
&TranscriptSegmentRequest {
segment_id: "seg-live-1".to_string(),
speaker_id: USER_A.to_string(),
+ diarized_speaker_id: Some("spk-live-a0".to_string()),
content: "hello there".to_string(),
started_at: now,
ended_at: Some(now),
@@ -809,6 +819,7 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Re
&TranscriptSegmentRequest {
segment_id: "seg-live-2".to_string(),
speaker_id: USER_B.to_string(),
+ diarized_speaker_id: None,
content: "general kenobi".to_string(),
started_at: now,
ended_at: Some(now),
@@ -844,8 +855,13 @@ async fn get_call_record_returns_active_call(pool: Pool<Postgres>) -> anyhow::Re
record.transcript[0].segment_id.as_deref(),
Some("seg-live-1")
);
+ assert_eq!(
+ record.transcript[0].diarized_speaker_id.as_deref(),
+ Some("spk-live-a0")
+ );
assert_eq!(record.transcript[1].sequence_num, 2);
assert_eq!(record.transcript[1].content, "general kenobi");
+ assert_eq!(record.transcript[1].diarized_speaker_id, None);
Ok(())
}
@@ -874,7 +890,12 @@ async fn get_call_record_returns_archived_call(pool: Pool<Postgres>) -> anyhow::
// Transcripts ordered by sequence_num.
assert_eq!(record.transcript.len(), 2);
assert_eq!(record.transcript[0].content, "archived hello");
+ assert_eq!(
+ record.transcript[0].diarized_speaker_id.as_deref(),
+ Some("spk-arch-a0")
+ );
assert_eq!(record.transcript[1].content, "archived reply");
+ assert_eq!(record.transcript[1].diarized_speaker_id, None);
Ok(())
}
diff --git a/rust/cloud-storage/macro_db_client/migrations/20260424130000_call_transcripts_diarized_speaker_id.sql b/rust/cloud-storage/macro_db_client/migrations/20260424130000_call_transcripts_diarized_speaker_id.sql
new file mode 100644
index 0000000000..edd1c7aaf9
--- /dev/null
+++ b/rust/cloud-storage/macro_db_client/migrations/20260424130000_call_transcripts_diarized_speaker_id.sql
@@ -0,0 +1,10 @@
+-- Per-speaker identifier emitted by the STT provider's diarization pass.
+-- Unique within a single audio track session; namespaced by track/participant
+-- upstream so values are globally unique across a call. Nullable because older
+-- segments and non-diarized providers won't populate it.
+
+ALTER TABLE call_transcripts
+ ADD COLUMN IF NOT EXISTS diarized_speaker_id TEXT;
+
+ALTER TABLE call_record_transcripts
+ ADD COLUMN IF NOT EXISTS diarized_speaker_id TEXT;