### Reset Project to Clean Slate Source: https://docs.speechmatics.com/voice-agents/flow/guides/react-native Run this command to remove example code and start with a clean project structure. It moves existing examples to an 'app-example' directory. ```bash npm run reset-project ``` -------------------------------- ### Basic Voice Agent Configuration Example Source: https://docs.speechmatics.com/voice-agents/voice-sdk This example demonstrates a comprehensive `VoiceAgentConfig` setup, including language, model, vocabulary, audio, and diarization settings. It utilizes `VoiceAgentConfigPreset.ADAPTIVE` with custom overrides. ```python from speechmatics.voice import ( AdditionalVocabEntry, AudioEncoding, OperatingPoint, VoiceAgentConfig, VoiceAgentConfigPreset, ) overrides = VoiceAgentConfig( # Language and locale language="en", # e.g. "en", "es", "fr" output_locale=None, # e.g. "en-GB", "en-US" # Model selection operating_point=OperatingPoint.ENHANCED, # STANDARD or ENHANCED domain=None, # e.g. "finance", "medical" # Vocabulary additional_vocab=[ AdditionalVocabEntry( content="Speechmatics", sounds_like=["speech matters", "speech matics"], ), AdditionalVocabEntry(content="API"), ], punctuation_overrides=None, # Audio sample_rate=16000, audio_encoding=AudioEncoding.PCM_S16LE, # Diarization enable_diarization=True, ) config = VoiceAgentConfigPreset.ADAPTIVE(overrides) ``` -------------------------------- ### Realtime Speaker Enrollment Example in Python Source: https://docs.speechmatics.com/speech-to-text/realtime/speaker-identification Use this example to enroll speakers in real-time. It configures the transcription for speaker diarization and sends a GetSpeakers request after recognition starts. ```python import asyncio import speechmatics import speechmatics.models import speechmatics.client from speechmatics.client import ( ServerMessageType, ClientMessageType ) API_KEY = "YOUR_API_KEY" PATH_TO_FILE = "example.wav" LANGUAGE = "en" CONNECTION_URL = "wss://eu.rt.speechmatics.com/v2" async def enroll_speakers(): handler_tasks: list[asyncio.Task] = [] transcription_config = speechmatics.models.TranscriptionConfig(**{ "language": LANGUAGE, "diarization": "speaker", } ) # Create a transcription client client = speechmatics.client.WebsocketClient( speechmatics.models.ConnectionSettings( url=CONNECTION_URL, auth_token=API_KEY, ) ) # Register the event handler for RecognitionStarted # to send the GetSpeakers(final=True) request client.add_event_handler( ServerMessageType.RecognitionStarted, lambda _: handler_tasks.append( asyncio.create_task(client.send_message(ClientMessageType.GetSpeakers, {"final": True})) ), ) # Register the event handler for SpeakersResult # to print the speaker identifiers obtained from the server client.add_event_handler( ServerMessageType.SpeakersResult, lambda message: print(f"[speaker identifiers] {message['speakers']}"), ) with open(PATH_TO_FILE, "rb") as fh: await asyncio.create_task(client.run(fh, transcription_config)) for task in handler_tasks: await task if __name__ == "__main__": asyncio.run(enroll_speakers()) ``` -------------------------------- ### Install Python Requests Library Source: https://docs.speechmatics.com/text-to-speech/quickstart Install the 'requests' library for making HTTP requests in Python. This is a prerequisite for using the Python (requests) example. ```bash pip install requests ``` -------------------------------- ### Install Dependencies with uv Source: https://docs.speechmatics.com/integrations-and-sdks/pipecat Set up a virtual environment and install project dependencies using the uv package manager. ```bash uv venv source .venv/bin/activate uv pip install -r requirements.txt ``` -------------------------------- ### Environment Configuration Example Source: https://docs.speechmatics.com/integrations-and-sdks/livekit Example of a .env.local file showing LiveKit, Speechmatics, and OpenAI API key configurations. ```dotenv LIVEKIT_URL=wss://your-project.livekit.cloud LIVEKIT_API_KEY=... LIVEKIT_API_SECRET=... SPEECHMATICS_API_KEY=your_speechmatics_key OPENAI_API_KEY=your_openai_key ``` -------------------------------- ### Install LiveKit CLI (Linux) Source: https://docs.speechmatics.com/integrations-and-sdks/livekit Installs the LiveKit Command Line Interface on Linux by downloading and executing a script. ```bash curl -sSL https://get.livekit.io/cli | bash ``` -------------------------------- ### Python Real-time Transcription Setup Source: https://docs.speechmatics.com/speech-to-text/realtime/quickstart Configure audio format and transcription settings for real-time transcription. Ensure PyAudio is installed for microphone access. ```python audio_format = AudioFormat( encoding=AudioEncoding.PCM_S16LE, sample_rate=16000, chunk_size=4096, ) config = TranscriptionConfig( language="en", max_delay=0.7, ) ``` -------------------------------- ### Install FFMPEG on Linux Source: https://docs.speechmatics.com/speech-to-text/realtime/guides/python-using-ffmpeg Install FFMPEG and ALSA utilities on Debian-based Linux systems using apt. Verify the installation with `ffmpeg -version`. ```bash sudo apt update ``` ```bash sudo apt install ffmpeg libasound2 alsa-utils ``` ```bash ffmpeg -version ``` -------------------------------- ### Example Bad Config for Unsupported Language Source: https://docs.speechmatics.com/speech-to-text/batch/language-identification This JSON configuration demonstrates an invalid setup where an unsupported language code ('zz') is provided in 'expected_languages'. This will result in a HTTP 400 error. ```json { "type": "transcription", "transcription_config": { "language": "en" }, "language_identification_config": { "expected_languages": ["zz"] } } ``` -------------------------------- ### Get Appliance Summary Information Source: https://docs.speechmatics.com/deployments/virtual-appliance/administration/services Retrieve summary information about the appliance, including its version, variant, and installed languages. Requires authentication. ```bash curl -sSL -u admin:admin -X 'GET' \ "http://${APPLIANCE_HOST}/v2/management/host/about" ``` ```json { "appliance_version": "6.3.0", "appliance_variant": "sm-realtime-appliance-6.3.0-xxxxxxx", "languages": [ "en" ] } ``` -------------------------------- ### Python Realtime Transcription Example Source: https://docs.speechmatics.com/speech-to-text/realtime/quickstart Example Python script to connect to the Realtime API, configure transcription, and process audio from the microphone. Ensure you have your API key and the necessary libraries installed. ```python import asyncio from speechmatics.rt import ( AudioEncoding, AudioFormat, AuthenticationError, Microphone, ServerMessageType, TranscriptResult, TranscriptionConfig, AsyncClient, ) API_KEY = YOUR_API_KEY ``` -------------------------------- ### Install LiveKit CLI (Windows) Source: https://docs.speechmatics.com/integrations-and-sdks/livekit Installs the LiveKit Command Line Interface on Windows using the Windows Package Manager. ```bash winget install LiveKit.LiveKitCLI ``` -------------------------------- ### Realtime Readiness Response Example Source: https://docs.speechmatics.com/deployments/virtual-appliance/administration/scaling Example JSON response from the realtime readiness endpoint, indicating service capacity. ```json { "ready": true, } ``` -------------------------------- ### Install Speechmatics Python Library Source: https://docs.speechmatics.com/speech-to-text/realtime/guides/python-using-microphone Install the Speechmatics Python library and CLI using pip. ```bash pip3 install speechmatics-python ``` -------------------------------- ### Install Speechmatics Realtime Python Library Source: https://docs.speechmatics.com/speech-to-text/realtime/quickstart Install the Speechmatics Realtime client and PyAudio for microphone input using pip. ```bash pip install speechmatics-rt pyaudio ``` -------------------------------- ### Install Voice SDK Source: https://docs.speechmatics.com/voice-agents/voice-sdk Install the Speechmatics Voice SDK using pip. Use the `smart` extra for ML-based turn detection. ```bash # Standard installation pip install speechmatics-voice # With SMART_TURN (ML-based turn detection) pip install speechmatics-voice[smart] ``` -------------------------------- ### GET /v2/management/host/about Source: https://docs.speechmatics.com/deployments/virtual-appliance/administration/services Retrieves summary information about the appliance, including its version, variant, and installed languages. ```APIDOC ## GET /v2/management/host/about ### Description Retrieves summary information about the appliance, including its version, variant, and installed languages. ### Method GET ### Endpoint `/v2/management/host/about` ### Response #### Success Response (200) - **appliance_version** (string) - The version of the appliance. - **appliance_variant** (string) - The specific build and mode of the appliance. - **languages** (array of strings) - The list of languages installed in the appliance. ### Response Example ```json { "appliance_version": "6.3.0", "appliance_variant": "sm-realtime-appliance-6.3.0-xxxxxxx", "languages": [ "en" ] } ``` ``` -------------------------------- ### Install Pipecat Dependencies Source: https://docs.speechmatics.com/integrations-and-sdks/pipecat Define the necessary Pipecat AI packages and their extensions in a requirements.txt file for installation. ```text pipecat-ai[local-smart-turn-v3,silero,speechmatics,webrtc,openai,runner] pipecat-ai-small-webrtc-prebuilt python-dotenv loguru ``` -------------------------------- ### GPU Inference Container Server Output Source: https://docs.speechmatics.com/deployments/container/gpu-speech-to-text Example output when the GPU inference server starts successfully, indicating readiness of various models and the GRPC/HTTP services. ```text I1215 11:43:57.300390 1 server.cc:633] +----------------------+---------+--------+ | Model | Version | Status | +----------------------+---------+--------+ | am_en_enhanced | 1 | READY | | am_en_standard | 1 | READY | | body_enhanced | 1 | READY | | body_standard | 1 | READY | | diar_enhanced | 1 | READY | | diar_standard | 1 | READY | | ensemble_en_enhanced | 1 | READY | | ensemble_en_standard | 1 | READY | | lm_en_enhanced | 1 | READY | +----------------------+---------+--------+ ... I1215 11:43:57.375233 1 grpc_server.cc:4819] Started GRPCInferenceService at 0.0.0.0:8001 I1215 11:43:57.375473 1 http_server.cc:3477] Started HTTPService at 0.0.0.0:8000 I1215 11:43:57.417749 1 http_server.cc:184] Started Metrics Service at 0.0.0.0:8002 ``` -------------------------------- ### Install Speechmatics Realtime JavaScript Library Source: https://docs.speechmatics.com/speech-to-text/realtime/quickstart Install the Speechmatics Realtime client and authentication libraries for JavaScript using npm. ```bash npm install @speechmatics/real-time-client @speechmatics/auth ``` -------------------------------- ### Install PyAudio Source: https://docs.speechmatics.com/speech-to-text/realtime/guides/python-using-microphone Install the PyAudio library, which is required for microphone input. For Mac M1/M2, specific instructions involving Homebrew are provided. ```bash pip3 install pyaudio ``` ```bash brew install portaudio brew link portaudio BREW_PREFIX=$(brew --prefix) CFLAGS="-I$BREW_PREFIX/include -L$BREW_PREFIX/lib" python3 -m pip install pyaudio ``` -------------------------------- ### Install Speechmatics Packages Source: https://docs.speechmatics.com/voice-agents/flow/guides/nextjs-guide Install the necessary Speechmatics packages for Flow API client, authentication, and audio handling. ```bash # Official Flow API client for React npm install @speechmatics/flow-client-react # Used for requesting JWTs for API authentication npm install @speechmatics/auth # These let us capture and play raw audio in the browser easily npm install @speechmatics/browser-audio-input npm install @speechmatics/browser-audio-input-react npm install @speechmatics/web-pcm-player-react # Utility package for rendering the transcript of the conversation npm install @speechmatics/use-flow-transcript ``` -------------------------------- ### Install LiveKit CLI (macOS) Source: https://docs.speechmatics.com/integrations-and-sdks/livekit Installs the LiveKit Command Line Interface on macOS using Homebrew. ```bash brew install livekit-cli ``` -------------------------------- ### Map Log Directory in Docker Container Source: https://docs.speechmatics.com/deployments/container/troubleshooting Example command to map a temporary directory into the container for log file creation, useful when logging setup fails due to volume mapping issues. ```bash $ docker run --rm -e SM_LOG_DIR=/xxx -e SM_JOB_ID=1 -v $PWD/tmp:/xxx batch-asr-transcriber-en:{smVariables.latestContainerVersion} ``` -------------------------------- ### Install Speechmatics Realtime Helm Chart Source: https://docs.speechmatics.com/deployments/kubernetes/realtime Use this command to install or upgrade the sm-realtime Helm chart. Ensure prerequisites are met and specify the desired URL. ```bash helm upgrade --install speechmatics-realtime \ oci://speechmaticspublic.azurecr.io/sm-charts/sm-realtime \ --version 1.2.0 \ --set proxy.ingress.url="speechmatics.example.com" ``` -------------------------------- ### Batch Mode GPU Configuration Example Response Source: https://docs.speechmatics.com/deployments/virtual-appliance/administration/using-a-gpu An example JSON response showing the current GPU configuration for batch mode, including operating point and max jobs. ```json { "primary_operating_point": "enhanced", "max_jobs": 12 } ``` -------------------------------- ### Install Speechmatics Batch JavaScript Client Source: https://docs.speechmatics.com/speech-to-text/batch/quickstart Install the JavaScript SDK using NPM. This is required to interact with the Speechmatics Batch API in Node.js. ```bash npm install @speechmatics\/batch-client ``` -------------------------------- ### Install Speechmatics Batch Python Client Source: https://docs.speechmatics.com/speech-to-text/batch/quickstart Install the Python SDK using pip. This is required to interact with the Speechmatics Batch API in Python. ```bash pip install speechmatics-batch ``` -------------------------------- ### Install Nginx Ingress Controller with Helm Source: https://docs.speechmatics.com/deployments/kubernetes/prerequisites Install the Nginx ingress controller using Helm, specifying the chart version and providing the custom `nginx.values.yaml` file for configuration. ```bash helm repo add nginx https://kubernetes.github.io/ingress-nginx helm install nginx nginx/ingress-nginx --version 4.11.4 -f nginx.values.yaml ``` -------------------------------- ### Example .dbl File Format Source: https://docs.speechmatics.com/speech-to-text/accuracy-benchmarking An example of a '.dbl' file format, which contains a list of file paths to individual transcript files. ```text /audio_transcripts/audio1_reference.txt /audio_transcripts/audio2_reference.txt /audio_transcripts/audio3_reference.txt ``` -------------------------------- ### Example JSON Response with Topics Source: https://docs.speechmatics.com/speech-to-text/batch/speech-intelligence/topic-detection This is an example of the JSON output when topic detection is enabled. It includes detected topics for each segment and an overall summary of topic counts. ```json { "job": { ... }, "metadata": { "created_at": "2023-05-26T15:01:48.412714Z", "type": "transcription", "transcription_config": { "language": "en" }, "topic_detection_config": {} ... }, "results": [...], "topics": { "segments": [ { "text": "The National Park Service on Twitter says it expects the closures to remain in effect ...", "start_time": 0.80, "end_time": 1.72, "topics": [{"topic": "Events & Attractions"}], }, { "text": "Lawmakers in Canada have voted to regulate online streaming content ...", "start_time": 2.06, "end_time": 3.40, "topics": [{"topic": "News & Politics"}, {"topic": "Technology & Computing"}], } ], "summary": { "overall": { "Business & Finance": 1, "Education": 0, "Entertainment": 0, "Events & Attractions": 0, "Food & Drink": 0, "News & Politics": 1, "Science": 0, "Sports": 0, "Technology & Computing": 1, "Travel": 0 } } } } ``` -------------------------------- ### Install Project Dependencies Source: https://docs.speechmatics.com/integrations-and-sdks/livekit Installs necessary Python packages including LiveKit agents with Speechmatics and OpenAI support, and dotenv for environment variable management. ```bash uv init uv add "livekit-agents[speechmatics,openai,silero]==1.4.2" python-dotenv ``` -------------------------------- ### AddTranscript Message Example Source: https://docs.speechmatics.com/deployments/container/cpu-speech-to-text An example of the AddTranscript message format returned by the Realtime container, detailing word-level transcriptions with start and end times and confidence scores. ```json { "message": "AddTranscript", "format": "2.9", "metadata": { "transcript": "full tell radar", "start_time": 0.11, "end_time": 1.07 }, "results": [ { "type": "word", "start_time": 0.11, "end_time": 0.4, "alternatives": [{ "content": "full", "confidence": 0.7 }] }, { "type": "word", "start_time": 0.41, "end_time": 0.62, "alternatives": [{ "content": "tell", "confidence": 0.6 }] }, { "type": "word", "start_time": 0.65, "end_time": 1.07, "alternatives": [{ "content": "radar", "confidence": 1.0 }] } ] } ``` -------------------------------- ### Upload SSL Certificate and Key Source: https://docs.speechmatics.com/deployments/virtual-appliance/administration/ssl-configuration Use this command to upload your custom SSL certificate and private key to the Appliance. Ensure `APPLIANCE_HOST` is set correctly. Do not use HTTP for uploads. ```bash curl --insecure -L -u admin:$PWD -X 'POST' "https://${APPLIANCE_HOST}/v2/security/sslcertificate" \ -F "keyfile=@appliance.key" -F "certfile=@appliance.crt" ``` -------------------------------- ### Quickstart: Stream Microphone Audio to Voice Agent Source: https://docs.speechmatics.com/voice-agents/voice-sdk Stream microphone audio to the Voice Agent and transcribe finalized speech segments with speaker IDs using the 'scribe' preset. Requires the `speechmatics-rt` package for microphone handling. ```python import asyncio import os from speechmatics.rt import Microphone from speechmatics.voice import VoiceAgentClient, AgentServerMessageType async def main(): """Stream microphone audio to Speechmatics Voice Agent using 'scribe' preset""" # Audio configuration SAMPLE_RATE = 16000 # Hz CHUNK_SIZE = 160 # Samples per read PRESET = "scribe" # Configuration preset # Create client with preset client = VoiceAgentClient( api_key=os.getenv("SPEECHMATICS_API_KEY"), preset=PRESET ) # Print finalised segments of speech with speaker ID @client.on(AgentServerMessageType.ADD_SEGMENT) def on_segment(message): for segment in message["segments"]: speaker = segment["speaker_id"] text = segment["text"] print(f"{speaker}: {text}") # Setup microphone mic = Microphone(SAMPLE_RATE, CHUNK_SIZE) if not mic.start(): print("Error: Microphone not available") return # Connect to the Voice Agent await client.connect() # Stream microphone audio (interruptible using keyboard) try: while True: audio_chunk = await mic.read(CHUNK_SIZE) if not audio_chunk: break # Microphone stopped producing data await client.send_audio(audio_chunk) except KeyboardInterrupt: pass finally: await client.disconnect() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install FFMPEG on Windows Source: https://docs.speechmatics.com/speech-to-text/realtime/guides/python-using-ffmpeg Install FFMPEG on Windows by downloading the binary, extracting it, and adding the \"bin\" folder to your system's PATH environment variable. Verify with `ffmpeg -version`. ```bash ffmpeg -version ``` -------------------------------- ### Query Health Service Started Probe Source: https://docs.speechmatics.com/deployments/container/cpu-speech-to-text Query the /started endpoint of the Health Service using an HTTP GET request to check if all services in the container have successfully started. A 200 response indicates success. ```bash $ curl -i address.of.container:8001/started HTTP/1.0 200 OK Server: BaseHTTP/0.6 Python/3.8.5 Date: Mon, 08 Feb 2021 12:46:21 GMT Content-Type: application/json { "started": true } ``` -------------------------------- ### ASR Usage Container Export Success Log Example Source: https://docs.speechmatics.com/deployments/usage-reporting/offline Example log message from the ASR Usage Container indicating a successful GET request to the /v1/export endpoint, likely from a customer data export operation. ```log [2021-09-03T14:54:00Z INFO actix_web::middleware::logger] 172.19.0.1:55820 "GET /v1/export HTTP/1.1" 200 12912 "-" "curl/7.64.1" 0.006313 ``` -------------------------------- ### Realtime Streaming with Microphone (Python) Source: https://docs.speechmatics.com/speech-to-text/realtime/turn-detection Example of setting up real-time audio streaming from a microphone for voice AI applications. Requires API key, language, and connection URL. ```python import speechmatics import pyaudio import threading import time import asyncio API_KEY = "YOUR_API_KEY" LANGUAGE = "en" CONNECTION_URL = f"wss://eu.rt.speechmatics.com/v2" ``` -------------------------------- ### Successful WebSocket Handshake Request Source: https://docs.speechmatics.com/api-ref/realtime-transcription-websocket An example of a client's GET request to initiate a WebSocket connection for Realtime transcription. ```http GET /v2/ HTTP/1.1 Host: eu.rt.speechmatics.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: ujRTbIaQsXO/0uCbjjkSZQ== Sec-WebSocket-Version: 13 Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits Authorization: Bearer wmz9fkLJM6U5NdyaG3HLHybGZj65PXp User-Agent: Python/3.8 websockets/8.1 ``` -------------------------------- ### Run Development Server Source: https://docs.speechmatics.com/voice-agents/flow/guides/nextjs-guide Command to start the Next.js development server. Access the application at http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### Configure Raw Audio Input Source: https://docs.speechmatics.com/speech-to-text/realtime/input Example configuration for sending raw audio. Ensure the 'encoding' and 'sample_rate' match your audio stream. ```json {"type":"raw","encoding":"pcm_s16le","sample_rate":44100} ``` -------------------------------- ### Authenticated Request Example Source: https://docs.speechmatics.com/deployments/virtual-appliance/administration/ssl-configuration Shows how to make an authenticated GET request to a management API endpoint using curl with the `--user` flag to provide the admin username and password. ```bash curl -L --user "admin:$PWD" -X GET "http://${APPLIANCE_HOST}/v2/management/host/about" ``` -------------------------------- ### Get Transcription Output as Non-Root User Source: https://docs.speechmatics.com/deployments/container/additional-security Run the container with a non-root user and map volumes for input and configuration. This example assumes the image name is stored in the ${IMAGE_NAME} variable. ```bash docker run -u 1020:4000 \ -v /Users/$USER/work/pipeline/mydev/config.json:/config.json \ -v /Users/$USER/work/pipeline/mydev/input.audio:/input.audio \ ${IMAGE_NAME} ``` -------------------------------- ### Appliance VM CPU Information Example Source: https://docs.speechmatics.com/deployments/virtual-appliance/installation/system-requirements This JSON output shows an example of the CPU information returned by the Management API. It details the CPU architecture, model, core count, and a comprehensive list of supported CPU flags, such as AVX and AVX2. ```json { "usage_percentage": 2.5, "architecture": "X86_64", "model_name": "Intel(R) Xeon(R) Silver 4116 CPU @ 2.10GHz", "cpus": "2", "vendor": "GenuineIntel", "hyperthreading": false, "flags": "3dnowprefetch abm adx aes apic arat arch_capabilities arch_perfmon avx avx2 avx512_vnni bmi1 bmi2 clflush cmov constant_tsc cpuid cpuid_fault cx16 cx8 de f16c flush_l1d fma fpu fsgsbase fxsr hypervisor ibpb ibrs invpcid invpcid_single lahf_lm lm mca mce md_clear mmx movbe msr mtrr nonstop_tsc nopl nx pae pat pcid pclmulqdq pdpe1gb pge pni popcnt pse pse36 pti rdrand rdseed rdtscp sep smap smep ss ssbd sse sse2 sse4_1 sse4_2 ssse3 stibp syscall tsc tsc_adjust tsc_deadline_timer tsc_reliable vme x2apic xsave xsaveopt xtopology" } ``` -------------------------------- ### Download Appliance Logs as ZIP Source: https://docs.speechmatics.com/deployments/virtual-appliance/administration/services Download appliance logs as a ZIP file. The 'limit' parameter specifies the maximum age of logs to include. Output is redirected to a file. ```bash curl -sSL -u admin:admin -X 'GET' \ "http://${APPLIANCE_HOST}/v2/management/logs/zip?limit=1h" \ -o ./speechmatics.zip ``` -------------------------------- ### Install FFMPEG on macOS Source: https://docs.speechmatics.com/speech-to-text/realtime/guides/python-using-ffmpeg Install FFMPEG on macOS using Homebrew. Ensure Homebrew is installed and up-to-date before proceeding. ```bash brew update ``` ```bash brew upgrade ``` ```bash brew install ffmpeg ``` -------------------------------- ### Initialize FlowProvider and Connect/Disconnect Logic Source: https://docs.speechmatics.com/voice-agents/flow/guides/react-native This snippet shows the main component setup for the Speechmatics Flow client. It includes the `FlowProvider` for context and a `Flow` component that uses the `useFlow` hook to manage conversation state and actions. The `obtainJwt` function demonstrates how to get a JWT, with a warning about exposing API keys in client-side code. The `handleToggleConnect` function manages the connection and disconnection process. ```typescript // The polyfill should be the first import in the app import "event-target-polyfill"; import { createSpeechmaticsJWT } from "@speechmatics/auth"; import { FlowProvider, useFlow } from "@speechmatics/flow-client-react"; import { Button, StyleSheet, Text, View } from "react-native"; export default function Index() { return ( ); } function Flow() { const { startConversation, endConversation, sendAudio, socketState } = useFlow(); const obtainJwt = async () => { const apiKey = process.env.EXPO_PUBLIC_SPEECHMATICS_API_KEY; if (!apiKey) { throw new Error("API key not found"); } // WARNING: This is just an example app. // In a real app you should obtain the JWT from your server. // For example, `createSpeechmaticsJWT` could be used on a server running JS. // Otherwise, you will expose your API key to the client. return await createSpeechmaticsJWT({ type: "flow", apiKey, ttl: 60, }); }; const handleToggleConnect = async () => { if (socketState === "open") { endConversation(); } else { try { const jwt = await obtainJwt(); await startConversation(jwt, { config: { template_id: "flow-service-assistant-humphrey", template_variables: { timezone: "Europe/London", }, }, }); } catch (e) { console.log("Error connecting to Flow: ", e); } } }; return ( Talk to Flow!