### Initialize and Start the Application Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Commands to clone submodules, install dependencies, and launch the backend and frontend servers. ```bash # Initialize (clone submodules + install deps) make init # Set up environment test -f .env || cp sample.env .env # then set DEEPGRAM_API_KEY # Start both servers make start # Backend: http://localhost:8081 # Frontend: http://localhost:8080 ``` -------------------------------- ### Initialize and Start Local Development Source: https://github.com/deepgram-starters/go-flux/blob/main/README.md Use these make commands to initialize the project, set up your API key, and start the local development server. ```bash make init cp sample.env .env # Add your DEEPGRAM_API_KEY make start ``` -------------------------------- ### Install Dependencies Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Commands to install backend Go modules and frontend Node.js dependencies. ```bash go mod download cd frontend && corepack pnpm install ``` -------------------------------- ### Makefile Development Commands Source: https://context7.com/deepgram-starters/go-flux/llms.txt Common commands for project initialization, dependency management, and starting the development servers. ```bash # Check prerequisites (git, go) make check-prereqs # Initialize project: clone submodules and install dependencies make init # Install Go dependencies only make install # Install frontend dependencies only make install-frontend # Start both backend (port 8081) and frontend (port 8080) servers make start ``` -------------------------------- ### Configure Keyterms Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Example of passing multiple keyterm parameters as query strings to the WebSocket connection. ```text ?keyterm=Deepgram&keyterm=Nova&keyterm=Aura ``` -------------------------------- ### Start and Stop Commands Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Commands for managing the lifecycle of the backend and frontend processes. ```bash make start ``` ```bash # Terminal 1 — Backend go run . # Terminal 2 — Frontend cd frontend && corepack pnpm run dev -- --port 8080 --no-open ``` ```bash lsof -ti:8080,8081 | xargs kill -9 2>/dev/null ``` ```bash rm -rf frontend/node_modules frontend/.vite make init ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Examples of commit messages following the conventional commits format for the Go Flux project. ```git feat(go-flux): add diarization support ``` ```git fix(go-flux): resolve WebSocket close handling ``` ```git refactor(go-flux): simplify session endpoint ``` ```git chore(deps): update frontend submodule ``` -------------------------------- ### Makefile Development Commands Source: https://context7.com/deepgram-starters/go-flux/llms.txt Use these commands to manage the local development environment, including starting servers, running tests, and cleaning build artifacts. ```makefile make start-backend make start-frontend make update make test make clean make status make eject-frontend ``` -------------------------------- ### Manual Endpoint Checks with Curl Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Examples of using curl to manually check the /api/metadata and /api/session endpoints, with JSON output formatted using python3. ```bash curl -sf http://localhost:8081/api/metadata | python3 -m json.tool ``` ```bash curl -sf http://localhost:8081/api/session | python3 -m json.tool ``` -------------------------------- ### Environment Configuration Variables Source: https://context7.com/deepgram-starters/go-flux/llms.txt Required and optional environment variables for server configuration. Copy sample.env to .env to apply these settings. ```bash # Required - Get your API key from https://console.deepgram.com DEEPGRAM_API_KEY=your_api_key_here # Optional - Backend API server port (default: 8081) PORT=8081 # Optional - Server bind address (default: 0.0.0.0) HOST=0.0.0.0 # Optional - Secret for signing JWT tokens (auto-generated if not set) # Set this in production for consistent token validation across restarts SESSION_SECRET=your_secret_key_here ``` -------------------------------- ### Run Go Flux Conformance Tests Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Command to execute the project's conformance tests. Ensure the application is running before executing. ```bash make test ``` -------------------------------- ### Docker Deployment Commands Source: https://context7.com/deepgram-starters/go-flux/llms.txt Build and run the application using a multi-stage Docker image with required environment variables. ```bash # Build Docker image docker build -f deploy/Dockerfile -t go-flux . # Run container with environment variables docker run -d \ -p 8080:8080 \ -e DEEPGRAM_API_KEY=your_api_key_here \ -e SESSION_SECRET=your_production_secret \ go-flux ``` -------------------------------- ### Fly.io Deployment Commands Source: https://context7.com/deepgram-starters/go-flux/llms.txt Deploy the application to Fly.io by authenticating, setting secrets, and running the deployment process. ```bash # Install Fly CLI and authenticate flyctl auth login # Set your Deepgram API key as a secret flyctl secrets set DEEPGRAM_API_KEY=your_api_key_here # Deploy the application flyctl deploy # View logs flyctl logs # Open the deployed app flyctl open ``` -------------------------------- ### Configure WebSocket Query Parameters Source: https://context7.com/deepgram-starters/go-flux/llms.txt Lists available query parameters for the /api/flux endpoint to control audio encoding, sample rate, and end-of-turn detection behavior. ```bash # Available query parameters for /api/flux WebSocket endpoint: # encoding (default: "linear16") # Audio encoding format: linear16, mulaw, alaw, opus, flac, mp3 ?encoding=linear16 # sample_rate (default: "16000") # Audio sample rate in Hz ?sample_rate=16000 # eot_threshold (optional) # Confidence threshold (0.0-1.0) for end-of-turn detection ?eot_threshold=0.5 # eager_eot_threshold (optional) # Lower threshold for faster (but less accurate) end-of-turn detection ?eager_eot_threshold=0.3 # eot_timeout_ms (optional) # Timeout in milliseconds to force end-of-turn after silence ?eot_timeout_ms=1000 # keyterm (optional, multi-value) # Boost recognition of specific terms ?keyterm=Deepgram&keyterm=Flux&keyterm=API # Full example URL: ws://localhost:8081/api/flux?encoding=linear16&sample_rate=16000&eot_threshold=0.5&keyterm=Deepgram ``` -------------------------------- ### Fetch Project Metadata with cURL Source: https://context7.com/deepgram-starters/go-flux/llms.txt Retrieve project metadata, including title, description, author, and tags, from the deepgram.toml configuration file. ```bash # Fetch project metadata curl -X GET http://localhost:8081/api/metadata ``` ```json # Response: # { # "title": "Go Flux", # "description": "Get started using Deepgram's Flux API for real-time transcription with turn detection using this Go demo app", # "author": "Deepgram DX Team (https://developers.deepgram.com)", # "repository": "https://github.com/deepgram-starters/go-flux", # "useCase": "flux", # "language": "go", # "framework": "go", # "sdk": "N/A", # "tags": ["flux", "turn-detection", "real-time-transcription", "streaming-stt", "end-of-turn", "go"] # } ``` -------------------------------- ### Update Frontend Submodule Reference Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Command to update the main project's reference to the frontend submodule after pushing frontend changes. ```bash cd .. && git add frontend && git commit -m "chore(deps): update frontend submodule" ``` -------------------------------- ### Connect to Flux WebSocket in JavaScript Source: https://context7.com/deepgram-starters/go-flux/llms.txt Establishes a bidirectional WebSocket connection to the Flux API and streams microphone audio. Requires a valid session token passed via the WebSocket subprotocol. ```javascript // JavaScript client example - Connect to Flux WebSocket async function connectToFlux() { // 1. Get session token from backend const tokenResponse = await fetch('http://localhost:8081/api/session'); const { token } = await tokenResponse.json(); // 2. Build WebSocket URL with audio parameters const wsUrl = new URL('ws://localhost:8081/api/flux'); wsUrl.searchParams.set('encoding', 'linear16'); wsUrl.searchParams.set('sample_rate', '16000'); wsUrl.searchParams.set('eot_threshold', '0.5'); // End-of-turn confidence threshold wsUrl.searchParams.set('eager_eot_threshold', '0.3'); // Eager end-of-turn threshold wsUrl.searchParams.set('eot_timeout_ms', '1000'); // End-of-turn timeout wsUrl.searchParams.append('keyterm', 'Deepgram'); // Boost specific terms wsUrl.searchParams.append('keyterm', 'Flux'); // 3. Connect with token in subprotocol const ws = new WebSocket(wsUrl.toString(), [`access_token.${token}`]); ws.onopen = () => { console.log('Connected to Flux'); startAudioCapture(ws); }; ws.onmessage = (event) => { const response = JSON.parse(event.data); // Handle transcription results if (response.type === 'Results') { const transcript = response.channel.alternatives[0].transcript; console.log('Transcript:', transcript); } // Handle end-of-turn detection if (response.type === 'EndOfTurn') { console.log('Turn ended - user finished speaking'); } }; ws.onerror = (error) => console.error('WebSocket error:', error); ws.onclose = (event) => console.log('Connection closed:', event.code, event.reason); return ws; } // Capture and stream microphone audio async function startAudioCapture(ws) { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); const audioContext = new AudioContext({ sampleRate: 16000 }); const source = audioContext.createMediaStreamSource(stream); const processor = audioContext.createScriptProcessor(4096, 1, 1); processor.onaudioprocess = (event) => { if (ws.readyState === WebSocket.OPEN) { const inputData = event.inputBuffer.getChannelData(0); // Convert Float32 to Int16 PCM const pcmData = new Int16Array(inputData.length); for (let i = 0; i < inputData.length; i++) { pcmData[i] = Math.max(-32768, Math.min(32767, inputData[i] * 32768)); } ws.send(pcmData.buffer); } }; source.connect(processor); processor.connect(audioContext.destination); } // Usage connectToFlux(); ``` -------------------------------- ### API Endpoints Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Overview of the available API endpoints for the Go Flux application. ```APIDOC ## API Endpoints | Endpoint | Method | Auth | Purpose | |----------|--------|------|---------| | `/api/session` | GET | None | Issue JWT session token | | `/api/metadata` | GET | None | Return app metadata (useCase, framework, language) | | `/api/flux` | WS | JWT | Advanced real-time transcription with turn-based detection. | ``` -------------------------------- ### Commit Frontend Changes in Submodule Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Steps to commit changes within the frontend git submodule and push them. ```bash cd frontend && git add . && git commit -m "feat: description" ``` ```bash cd frontend && git push origin main ``` -------------------------------- ### Metadata API Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Endpoint for retrieving application metadata. ```APIDOC ## GET /api/metadata ### Description Returns application metadata, including `useCase`, `framework`, and `language`. ### Method GET ### Endpoint `/api/metadata` ### Authentication None ``` -------------------------------- ### Request Session Token with cURL Source: https://context7.com/deepgram-starters/go-flux/llms.txt Use this command to request a signed JWT token for authenticating WebSocket connections. Tokens expire after 1 hour. Store the token for subsequent WebSocket connections. ```bash # Request a session token curl -X GET http://localhost:8081/api/session ``` ```json # Response: # {"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE3MDk4MjM0NTYsImV4cCI6MTcwOTgyNzA1Nn0.abc123..."} ``` ```bash # Store token for WebSocket connection TOKEN=$(curl -s http://localhost:8081/api/session | jq -r '.token') echo "Session token: $TOKEN" ``` -------------------------------- ### Connect to Flux WebSocket API Source: https://context7.com/deepgram-starters/go-flux/llms.txt Establishes a bidirectional WebSocket connection to Deepgram's Flux API. Requires JWT authentication via WebSocket subprotocol. Forwards audio data from client to Deepgram and returns transcription results including turn detection events. ```APIDOC ## POST /api/flux ### Description Establishes a bidirectional WebSocket connection to Deepgram's Flux API. Requires JWT authentication via WebSocket subprotocol. Forwards audio data from client to Deepgram and returns transcription results including turn detection events. ### Method POST ### Endpoint /api/flux ### Parameters #### Query Parameters - **encoding** (string) - Optional - Audio encoding format: linear16, mulaw, alaw, opus, flac, mp3 (default: "linear16") - **sample_rate** (integer) - Optional - Audio sample rate in Hz (default: 16000) - **eot_threshold** (number) - Optional - Confidence threshold (0.0-1.0) for end-of-turn detection - **eager_eot_threshold** (number) - Optional - Lower threshold for faster (but less accurate) end-of-turn detection - **eot_timeout_ms** (integer) - Optional - Timeout in milliseconds to force end-of-turn after silence - **keyterm** (string) - Optional, multi-value - Boost recognition of specific terms ### Request Example ```javascript // JavaScript client example - Connect to Flux WebSocket async function connectToFlux() { // 1. Get session token from backend const tokenResponse = await fetch('http://localhost:8081/api/session'); const { token } = await tokenResponse.json(); // 2. Build WebSocket URL with audio parameters const wsUrl = new URL('ws://localhost:8081/api/flux'); wsUrl.searchParams.set('encoding', 'linear16'); wsUrl.searchParams.set('sample_rate', '16000'); wsUrl.searchParams.set('eot_threshold', '0.5'); // End-of-turn confidence threshold wsUrl.searchParams.set('eager_eot_threshold', '0.3'); // Eager end-of-turn threshold wsUrl.searchParams.set('eot_timeout_ms', '1000'); // End-of-turn timeout wsUrl.searchParams.append('keyterm', 'Deepgram'); // Boost specific terms wsUrl.searchParams.append('keyterm', 'Flux'); // 3. Connect with token in subprotocol const ws = new WebSocket(wsUrl.toString(), [`access_token.${token}`]); ws.onopen = () => { console.log('Connected to Flux'); startAudioCapture(ws); }; ws.onmessage = (event) => { const response = JSON.parse(event.data); // Handle transcription results if (response.type === 'Results') { const transcript = response.channel.alternatives[0].transcript; console.log('Transcript:', transcript); } // Handle end-of-turn detection if (response.type === 'EndOfTurn') { console.log('Turn ended - user finished speaking'); } }; ws.onerror = (error) => console.error('WebSocket error:', error); ws.onclose = (event) => console.log('Connection closed:', event.code, event.reason); return ws; } // Capture and stream microphone audio async function startAudioCapture(ws) { const stream = await navigator.mediaDevices.getUserMedia({ audio: true }); const audioContext = new AudioContext({ sampleRate: 16000 }); const source = audioContext.createMediaStreamSource(stream); const processor = audioContext.createScriptProcessor(4096, 1, 1); processor.onaudioprocess = (event) => { if (ws.readyState === WebSocket.OPEN) { const inputData = event.inputBuffer.getChannelData(0); // Convert Float32 to Int16 PCM const pcmData = new Int16Array(inputData.length); for (let i = 0; i < inputData.length; i++) { pcmData[i] = Math.max(-32768, Math.min(32767, inputData[i] * 32768)); } ws.send(pcmData.buffer); } }; source.connect(processor); processor.connect(audioContext.destination); } // Usage connectToFlux(); ``` ### Response #### Success Response (101 Switching Protocols) - **type** (string) - Type of the message (e.g., "Results", "EndOfTurn") - **channel** (object) - Contains transcription results - **alternatives** (array) - Array of transcription alternatives - **transcript** (string) - The transcribed text #### Response Example ```json { "type": "Results", "channel": { "alternatives": [ { "transcript": "Hello Deepgram." } ] } } ``` ```json { "type": "EndOfTurn" } ``` ``` -------------------------------- ### Session API Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Endpoint for issuing JWT session tokens. ```APIDOC ## GET /api/session ### Description Issues a JSON Web Token (JWT) session token. This token is used for authenticating WebSocket connections. ### Method GET ### Endpoint `/api/session` ### Authentication None ``` -------------------------------- ### Flux WebSocket API Source: https://github.com/deepgram-starters/go-flux/blob/main/AGENTS.md Details on the WebSocket endpoint for advanced real-time transcription with Flux. ```APIDOC ## WS /api/flux ### Description This endpoint provides advanced real-time transcription using Deepgram Flux with turn-based detection. It establishes a WebSocket connection for streaming audio and receiving transcription results. ### Method WS ### Endpoint `/api/flux` ### Parameters #### Query Parameters - **model** (string) - Optional - Flux STT model (default: `flux-general-en`) - **encoding** (string) - Optional - Audio encoding (e.g., `linear16`, `opus`; default: `linear16`) - **sample_rate** (integer) - Optional - Audio sample rate (range: `8000`-`48000`; default: `16000`) - **eot_threshold** (float) - Optional - Confidence for end-of-turn detection (range: `0.0`-`1.0`; default: `0.7`) - **eager_eot_threshold** (float) - Optional - Threshold for tentative (eager) end-of-turn (range: `0.0`-`1.0`; default: disabled) - **eot_timeout_ms** (integer) - Optional - Silence duration (ms) before automatic EOT (range: `0`-`30000`; default: `5000`) - **keyterm** (string) - Optional - Custom vocabulary hints (can specify multiple) ### Authentication JWT session tokens are used. The WebSocket subprotocol for authentication is `access_token.`. ### Understanding Turn Events Flux provides structured turn-based events: 1. **StartOfTurn**: User started speaking. 2. **Update**: Interim transcript update within the turn. 3. **EagerEndOfTurn**: Tentative end detected. 4. **TurnResumed**: User spoke again after eager EOT. 5. **EndOfTurn**: Confirmed end of turn (final transcript). ### Example Usage To connect with specific parameters, append them to the WebSocket URL: ``` ws://localhost:8081/api/flux?model=flux-custom-en&eot_threshold=0.5&keyterm=Deepgram&keyterm=Flux ``` ``` -------------------------------- ### Health Check with cURL Source: https://context7.com/deepgram-starters/go-flux/llms.txt Perform a simple health check on the server. This endpoint is useful for monitoring and load balancer probes. ```bash # Check server health curl -X GET http://localhost:8081/health ``` ```json # Response: # {"status":"ok"} ``` ```bash # Use in monitoring scripts if curl -sf http://localhost:8081/health > /dev/null; then echo "Server is healthy" else echo "Server is down" fi ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.