Crestapps core realtime voice

From CrestApps/CrestApps.AgentSkills · View interactive version

Crestapps core realtime voice is an AI agent skill from the GitHub repository CrestApps/CrestApps.AgentSkills. Skill for realtime speech-to-speech voice in CrestApps.Core 2.0. Covers the realtime deployment capability, Conversation chat mode and ResolveConversationModeAsync, cascaded realtime deployments with CascadedRealtimeMetadata chaining speech-to-text (including Cartesia), chat and text-to-speech legs,

How to use this skill

Skill file

CrestApps.Core Realtime Voice

A realtime session is a live, spoken conversation: audio in, audio out, with barge-in. It runs through the same orchestration as text chat, so the profile's or interaction's system message, persona, tools, data sources and turn persistence all apply. Audio travels over WebRTC (server relay) when available and falls back to WebSocket (PCM over SignalR) automatically.

Guidelines

Choosing the Model That Carries the Conversation

How a conversation is carried is resolved, never stored:

  1. the conversation deployment named on the profile (ChatModeProfileSettings.ConversationDeploymentName) or the interaction (ChatInteraction.ConversationDeploymentName);
  2. otherwise the site default, DefaultAIDeploymentSettings.DefaultRealtimeDeploymentName;
  3. otherwise the first deployment that declares realtime.

If none resolves, Conversation mode falls back to the client-driven speech-to-text plus text-to-speech cascade (needs both slot defaults), then to dictation, then to typing. Because step 3 accepts any realtime-capable deployment, a site that has one uses it for every Conversation profile; to keep the client cascade, have no deployment declare realtime or carry CascadedRealtimeMetadata. A named conversation deployment that is not realtime-capable is reported (ConversationModeResolution.IsMisconfigured) instead of being silently replaced.

The views and hubs share one resolver, IAIDeploymentManager.ResolveConversationModeAsync(configuredChatMode, conversationDeploymentName, chatDeploymentName, hasSpeechToText, hasTextToSpeech, chatModeIsSiteWide) (namespace CrestApps.Core.AI.Deployments). Use it to decide whether to render the voice toggle. IAIDeploymentCapabilityService.IsRealtimeDeploymentAsync(name) is the single "is this deployment realtime" check.

{
  "CrestApps": {
    "AI": {
      "Deployments": [
        {
          "ClientName": "OpenAI",
          "ConnectionName": "openai",
          "Name": "gpt-realtime",
          "Features": [ "realtime" ]
        },
        {
          "ClientName": "OpenAI",
          "ConnectionName": "openai",
          "Name": "gpt-4o-transcribe",
          "Features": [ "speechToText" ]
        }
      ]
    }
  }
}

Cascaded Realtime Deployments

A cascade chains three existing deployments into one IRealtimeClient, possibly from different vendors:

mic -> realtime speech-to-text -> chat (tools, data sources) -> text-to-speech -> speaker
using CrestApps.Core.AI.Deployments;
using CrestApps.Core.AI.Models;
using CrestApps.Core.AI.Realtime;

// The source is a registered deployment provider name. A cascade needs no connection of its own.
var deployment = await deploymentManager.NewAsync("cascaded-voice", "OpenAI");

deployment.ModelName = "cascaded-voice";

deployment.Alter<CascadedRealtimeMetadata>(cascade =>
{
    cascade.SpeechToTextDeploymentName = "gpt-4o-transcribe";
    cascade.ChatDeploymentName = "gpt-4.1";
    cascade.TextToSpeechDeploymentName = "azure-tts";
    cascade.SpeechSpeed = 1.2;
    cascade.SpeakingStyle = "Speak at a brisk, natural phone pace.";
});

deployment.Alter<AIDeploymentMetadata>(metadata =>
{
    metadata.Features = [AIDeploymentFeatureNames.Realtime];
});

var validation = await deploymentManager.ValidateAsync(deployment);

if (!validation.Succeeded)
{
    throw new InvalidOperationException("The cascaded deployment is not valid.");
}

await deploymentManager.CreateAsync(deployment);

A configured deployment can carry the same metadata under Properties, keyed by type name: "Features": [ "realtime" ] plus "Properties": { "CascadedRealtimeMetadata": { "SpeechToTextDeploymentName": "...", "ChatDeploymentName": "...", "TextToSpeechDeploymentName": "..." } }.

Profile Speech Settings in a Cascade

When the session's resource is an AIProfile with AIProfileSpeechSettings, DefaultRealtimeOrchestrator hands the cascade a CascadedRealtimeProfileOptions built with CascadedRealtimeProfileOptions.From(settings, fallbackClient):

| Setting | Effect in the cascade |

|---|---|

| SpeakingRate | Clamped to 0.25 to 4; multiplies CascadedRealtimeMetadata.SpeechSpeed |

| SpeakingEmotion | Sent as TextToSpeechOptionsProperties.Emotion; Cartesia uses it, other providers ignore it |

| PronunciationEntries | Applied to the text before synthesis, whole words, longest phrase first |

| FallbackTextToSpeechDeploymentName | Speaks when the text-to-speech leg throws before producing audio |

| BoostedKeywords | Added to the transcription request and prompt (Vocabulary: a, b.) |

| RecognitionLanguages | The first is the speech language when RealtimeOrchestrationRequest.SpeechLanguage is not set |

| InterruptionSensitivity | Words of caller speech that cut the assistant off (0 never; unset one word); on a native session it sets the VAD threshold |

| EnableBackchanneling / BackchannelPhrases | A short spoken "mm-hm" while the caller talks; cascade only, never stored |

An explicit VadThreshold or AllowInterruption = false on the request wins over the profile.

Messages That Do Not Come from the Microphone

IRealtimeConversation.AddMessageAsync(role, text) adds a user message (keys pressed on a phone keypad) or a system message (a supervisor's note) to the live conversation without asking for a reply. To have it answered now, follow it with RequestUnpromptedResponseAsync() with no instructions, once no response is in flight:

await conversation.AddMessageAsync(ChatRole.User, "[Pressed on the keypad: 1234]", cancellationToken);
await conversation.RequestUnpromptedResponseAsync(cancellationToken: cancellationToken);

Do not pass such a message as a response's instructions: those replace the session's instructions for that response, so the assistant loses its persona and language, and the message is gone by the next turn. Speech-to-speech providers receive a conversation.item.create; a cascade adds it to the chat leg's history. The default interface implementation throws NotSupportedException; DefaultRealtimeConversation and cascaded deployments support it.

Switching Profile During a Call

// Inside the same AIInvocationScope the call was started in.
await orchestrator.SwitchResourceAsync(
    conversation,
    new RealtimeOrchestrationRequest { Resource = otherProfile },
    cancellationToken);

IRealtimeOrchestrator.SwitchResourceAsync builds the new profile's system message and tools as StartAsync does and applies them with IRealtimeConversation.UpdateSessionAsync(new RealtimeSessionUpdate { Instructions = ..., Tools = ... }). A host that has its own instructions and tools can call UpdateSessionAsync directly; null leaves that part unchanged and an empty tool list removes every tool.

Voice Selection

The voice reaches the provider in the same set-up message as the instructions and tools, and a provider refuses that message whole over one value it does not accept. DefaultRealtimeOrchestrator therefore checks the requested voice against IRealtimeVoiceResolver.GetVoicesAsync(deployment): a voice the deployment does not list is dropped with a warning and the session opens with the provider's default voice. A cascaded deployment's voice, and any voice when the list is empty or cannot be read, is passed on unchecked. Keep the profile's voice one of the realtime deployment's voices, or none.

Transport Registration

builder.Services.AddWebRtcRealtimeTransport();

AddWebRtcRealtimeTransport() (package CrestApps.Core.AI.WebRTC, namespace Microsoft.Extensions.DependencyInjection) registers the SIPSorcery peer factory (IWebRtcRealtimePeerFactory, Opus through Concentus) and binds RealtimeTransportOptions to CrestApps:AI:RealtimeTransport. It is idempotent. Without it voice still works, over WebSocket only, and RealtimeTransportOptions keeps its defaults unless the host binds the section itself:

builder.Services.AddOptions<RealtimeTransportOptions>().BindConfiguration("CrestApps:AI:RealtimeTransport");

Both chat hubs (AIChatHubCore<TClient> and ChatInteractionHubBase) support WebRTC. RealtimeTransportSettings.IsWebRtcEnabled(services) is what a view uses to advertise it (data-coreai-chat-realtime-webrtc-enabled). The hubs must run with ConfigureCrestAppsChatHubOptions<THub>(); with one parallel invocation per client the WebRTC handshake deadlocks.

The browser peers with the hub, not the provider; the hub keeps talking to the provider over WebSocket, so WebRTC works with any realtime provider. Audio crosses the boundary as PCM16 at 24 kHz mono. Transcripts, errors and lifecycle events stay on SignalR.

Configuration

{
  "CrestApps": {
    "AI": {
      "RealtimeTransport": {
        "EnableWebRtc": true,
        "IdleTimeoutSeconds": 30,
        "MaxSessionDurationSeconds": 300,
        "TurnDetectionType": "semantic_vad",
        "TurnDetectionEagerness": "auto",
        "EnableKnowledgeGrounding": true,
        "GroundingAcknowledgementDelayMs": 700,
        "GroundingResponseWatchdogSeconds": 15,
        "StunUrls": [ "stun:turn.example.com:3478" ],
        "TurnUrls": [ "turn:turn.example.com:3478", "turns:turn.example.com:5349" ],
        "TurnSecret": "the-same-secret-configured-in-coturn",
        "TurnCredentialTtlSeconds": 3600,
        "IceTransportPolicy": "All"
      }
    }
  }
}

| Option | Default | Meaning |

|---|---|---|

| EnableWebRtc | true | Turn off on hosts with no inbound UDP and no reachable TURN, so sessions do not wait out the connect timeout |

| IdleTimeoutSeconds | 30 | Ends a session after this long with neither side speaking (session_ended: idle); queued playback and an uncommitted utterance (up to 2 minutes) hold it off. 0 disables |

| MaxSessionDurationSeconds | 300 | Hard cap per session (session_ended: max_duration). 0 disables |

| TurnDetectionType / TurnDetectionEagerness | semantic_vad / auto | server_vad is a silence timer; a deployment that rejects semantic detection is switched to server VAD |

| EnableKnowledgeGrounding | true | Per-turn retrieval for voice; also requires preemptive RAG to be enabled |

| GroundingAcknowledgementDelayMs | 700 | After this, the assistant says a short out-of-band "let me look that up" line. 0 never speaks one |

| GroundingResponseWatchdogSeconds | 15 | Requests a reply anyway when a committed turn goes unanswered. 0 disables |

| StunUrls | public Google STUN when empty | STUN servers |

| TurnUrls + TurnSecret + TurnCredentialTtlSeconds | | coturn use-auth-secret ephemeral credentials (username is a UNIX expiry, credential is Base64 HMAC-SHA1) |

| TurnUsername / TurnCredential | | Static TURN credentials, used only without TurnSecret; unsuitable for hosted TURN whose credentials expire |

| IceTransportPolicy | All | Relay forces TURN-only candidates |

TurnUrls without a secret or static credentials produce no TURN entry.

Cloudflare Realtime TURN

using CrestApps.Core.AI.Chat;

builder.Services.AddCloudflareRealtimeTurn();
{
  "CrestApps": {
    "AI": {
      "RealtimeTransport": {
        "Cloudflare": {
          "TokenId": "<TURN Token ID>",
          "ApiToken": "<API token>",
          "TtlSeconds": 86400
        }
      }
    }
  }
}

Credentials are minted on demand and reused until half their lifetime. While TokenId/ApiToken are unset, the configured STUN/TURN servers apply; while Cloudflare is configured they are ignored. If Cloudflare is unreachable, already issued credentials keep being served.

Any other TURN service

Both the browser's list and the server peer resolve ICE servers through IRealtimeIceServerProvider. See realtime-voice-examples.md for a complete provider, a direct IRealtimeOrchestrator session, and the client wiring.

Transcribing the User

The user's side of the transcript (history, grounding, post-call analysis) comes from a separate model. The orchestrator picks, in order: RealtimeOrchestrationRequest.InputTranscriptionModel (empty string disables it); a cascade's own speech-to-text leg; the speechToText slot deployment when it is on the realtime deployment's provider; the first speech-to-text deployment on that provider. With none, a warning is logged and grounding falls back to the search tool. For OpenAI, gpt-4o-transcribe is the accurate choice; whisper-1 invents phrases from short sounds.

Client Contract

The hubs own the session. Interaction hub methods take itemId; AIChatHubCore takes profileId and sessionId:

| Hub method | Purpose |

|---|---|

| GetRealtimeIceServers() | Called right before the browser creates its RTCPeerConnection, so TURN credentials are fresh |

| StartRealtimeWebRtc(itemId, offerSdp, voice, language, silenceDurationMs, vadThreshold, allowInterruption) | WebRTC session; the answer arrives on ReceiveRealtimeAnswer(sdp) |

| AddRealtimeIceCandidate(candidate, sdpMid, sdpMLineIndex) | Trickled ICE; server candidates arrive on ReceiveRealtimeIceCandidate |

| StartRealtimeConversation(itemId, audioChunks, voice, language, silenceDurationMs, vadThreshold, allowInterruption) | WebSocket session; audioChunks is a stream of base64 PCM16 24 kHz frames, assistant audio returns as ReceiveAudioChunk(id, base64, "audio/pcm") |

| UpdateRealtimeSettings(allowInterruption, silenceDurationMs, vadThreshold) | Applies barge-in and turn detection to the running session (browser gate, server pump and provider) |

| UpdateRealtimeSpeechSpeed(speed) | Speaking speed from the next reply (next sentence on a cascade) |

| StopConversation() | Ends the session |

ReceiveRealtimeEvent(identifier, type, payload) carries RealtimeClientEventTypes: speech_speed, session_ready, speech_started, playback_flush, user_turn_pending, user_turn_dropped, and session_ended with a RealtimeSessionEndReasons value (completed, cancelled, error, idle, max_duration). Transcripts use ReceiveTranscript, ReceiveConversationUserMessage, ReceiveConversationAssistantToken and ReceiveConversationAssistantComplete.

The shared browser client is realtime-audio.js (@crestapps/ai-chat-ui, global CoreAIRealtime). CoreAIRealtime.attach({ connection, sendStart, sendStartWebRtc, webRtcEnabled, voiceName, selectors, onSessionStateChanged, ... }) returns a controller with start, stop, toggle, isActive, getState, getGateLevel and getTransportStats. It handles transport selection and fallback, the AudioWorklet microphone gate with learned echo level, playback, and the short settings popover (microphone, speaker, volume, speaking speed, language, interruptions, push-to-talk). A host that keeps typing available between sessions passes only realtimeButton and micButton in selectors and drives its own controls from onSessionStateChanged(active).

Troubleshooting

Upgrading Within 2.0 Previews

Upgrading from 1.x

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.