### Initialize and Start Project Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Commands to clone submodules, install dependencies, and launch the development 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 the Ruby Flux Application Source: https://github.com/deepgram-starters/ruby-flux/blob/main/README.md Use these commands to initialize the project, configure environment variables, and start the local development server. ```bash make init cp sample.env .env # Add your DEEPGRAM_API_KEY make start ``` -------------------------------- ### Connect with Custom Configuration Example Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt Example of connecting to the Flux API with custom configuration parameters for encoding, sample rate, EOT threshold, and keyterms. ```bash # ws://localhost:8081/api/flux?encoding=opus&sample_rate=48000&eot_threshold=0.8&keyterm=Deepgram&keyterm=Aura ``` -------------------------------- ### Manage Server Lifecycle Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Commands for starting, stopping, and cleaning the project environment. ```bash make start ``` ```bash # Terminal 1 — Backend bundle exec ruby app.rb # 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 vendor frontend/node_modules frontend/.vite make init ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Examples of valid commit messages following the conventional commits format. ```git feat(ruby-flux): add diarization support ``` ```git fix(ruby-flux): resolve WebSocket close handling ``` ```git refactor(ruby-flux): simplify session endpoint ``` ```git chore(deps): update frontend submodule ``` -------------------------------- ### Configure Keyterms Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Example of passing multiple keyterm parameters as query strings to the API. ```text ?keyterm=Deepgram&keyterm=Nova&keyterm=Aura ``` -------------------------------- ### Makefile Commands for Project Management Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt Common Makefile commands for checking prerequisites, initializing the project, setting up the environment, starting servers, running tests, updating submodules, cleaning artifacts, checking status, and ejecting the frontend. ```bash # Check prerequisites (git, ruby, bundler) make check-prereqs ``` ```bash # Initialize project: clone submodules and install all dependencies make init ``` ```bash # Set up environment cp sample.env .env # Edit .env to add your DEEPGRAM_API_KEY ``` ```bash # Start both backend (8081) and frontend (8080) servers make start ``` ```bash # Start servers separately make start-backend # Backend only on port 8081 make start-frontend # Frontend only on port 8080 ``` ```bash # Run conformance tests (requires running servers) make test ``` ```bash # Update git submodules to latest make update ``` ```bash # Clean build artifacts make clean ``` ```bash # Show git and submodule status make status ``` ```bash # Eject frontend from submodule for standalone development make eject-frontend ``` -------------------------------- ### GET /api/metadata Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Returns application metadata including use case, framework, and language. ```APIDOC ## GET /api/metadata ### Description Returns application metadata, including the use case, framework, and programming language. ### Method GET ### Endpoint `/api/metadata` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **useCase** (string) - The primary use case of the application. - **framework** (string) - The backend framework used (e.g., Sinatra). - **language** (string) - The programming language used (e.g., Ruby). #### Response Example ```json { "useCase": "Deepgram Flux Demo", "framework": "Sinatra", "language": "Ruby" } ``` ``` -------------------------------- ### GET /api/session Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Issues a JWT session token for authentication. ```APIDOC ## GET /api/session ### Description Issues a JWT session token. This token is used for authenticating WebSocket connections. ### Method GET ### Endpoint `/api/session` ### Parameters None ### Request Example None ### Response #### Success Response (200) - **token** (string) - The issued JWT session token. #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` ``` -------------------------------- ### Get Application Metadata with cURL Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt Retrieve application metadata, including use case, framework, and tags, by making a cURL request to the metadata endpoint. This is used for starter app standardization. ```bash # Get application metadata curl -s http://localhost:8081/api/metadata | python3 -m json.tool ``` -------------------------------- ### Connect to Deepgram Flux WebSocket with JavaScript Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt JavaScript example demonstrating how to connect to the Deepgram Flux WebSocket endpoint. It includes obtaining a session token, configuring Flux parameters, and handling transcription events. ```javascript // JavaScript client example connecting to Flux WebSocket async function connectToFlux() { // First, get a session token const sessionResponse = await fetch('http://localhost:8081/api/session'); const { token } = sessionResponse.json(); // Build WebSocket URL with Flux parameters const params = new URLSearchParams({ encoding: 'linear16', sample_rate: '16000', eot_threshold: '0.7', // End-of-turn confidence (0.0-1.0) eager_eot_threshold: '0.5', // Tentative end-of-turn threshold eot_timeout_ms: '5000', // Silence timeout in milliseconds keyterm: 'Deepgram', // Custom vocabulary hint keyterm: 'Nova' // Multiple keyterms supported }); // Connect with JWT in subprotocol header const ws = new WebSocket( `ws://localhost:8081/api/flux?${params}`, [`access_token.${token}`] ); ws.onopen = () => { console.log('Connected to Flux'); // Start streaming audio data as binary frames }; ws.onmessage = (event) => { const data = JSON.parse(event.data); // Handle Flux turn events switch (data.type) { case 'StartOfTurn': console.log('User started speaking'); break; case 'Update': console.log('Interim:', data.channel.alternatives[0].transcript); break; case 'EagerEndOfTurn': console.log('Tentative end detected'); break; case 'TurnResumed': console.log('User continued speaking'); break; case 'EndOfTurn': console.log('Final:', data.channel.alternatives[0].transcript); break; } }; ws.onerror = (error) => console.error('WebSocket error:', error); ws.onclose = (event) => console.log(`Disconnected: ${event.code} ${event.reason}`); return ws; } ``` -------------------------------- ### GET /api/metadata - Metadata Endpoint Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt Returns application metadata from deepgram.toml including use case, framework, language, and tags. This endpoint is used for starter app standardization and discovery. ```APIDOC ## GET /api/metadata ### Description Returns application metadata including use case, framework, language, and tags. This endpoint is used for starter app standardization and discovery. ### Method GET ### Endpoint /api/metadata ### Parameters None ### Response #### Success Response (200) - **title** (string) - The title of the application. - **description** (string) - A brief description of the application. - **author** (string) - Information about the author. - **repository** (string) - URL to the source code repository. - **useCase** (string) - The primary use case of the application. - **language** (string) - The programming language used. - **framework** (string) - The web framework used. - **tags** (array of strings) - Tags associated with the application. ### Response Example ```json { "title": "Ruby Flux", "description": "Get started using Deepgram's Flux real-time transcription with this Ruby demo app", "author": "Deepgram DX Team (https://developers.deepgram.com)", "repository": "https://github.com/deepgram-starters/ruby-flux", "useCase": "flux", "language": "ruby", "framework": "sinatra", "tags": ["flux", "streaming", "speech-to-text", "real-time", "turn-detection", "sinatra", "ruby"] } ``` ``` -------------------------------- ### GET /health - Health Check Endpoint Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt A simple health check endpoint for monitoring and load balancer probes. ```APIDOC ## GET /health ### Description Provides a simple health check for monitoring and load balancer probes. ### Method GET ### Endpoint /health ### Parameters None ### Response #### Success Response (200) - **status** (string) - Indicates the health status of the server, typically "ok". ### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### Run Conformance Tests Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Command to execute conformance tests. Requires the application to be running. ```bash make test ``` -------------------------------- ### Commit Frontend Changes Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Steps to commit and push changes made to the frontend submodule. ```bash cd frontend && git add . && git commit -m "feat: description" ``` ```bash cd frontend && git push origin main ``` ```bash cd .. && git add frontend && git commit -m "chore(deps): update frontend submodule" ``` -------------------------------- ### Environment Configuration (.env file) Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt Configuration options for the application's environment variables, including the required Deepgram API key and optional settings for the backend server port, host, and JWT signing secret. ```bash # .env file configuration # Required: Your Deepgram API key DEEPGRAM_API_KEY=your_api_key_here # Optional: Backend server port (default: 8081) PORT=8081 # Optional: Server bind address (default: 0.0.0.0) HOST=0.0.0.0 # Optional: JWT signing secret for production # If not set, a random secret is generated on startup SESSION_SECRET=your_production_secret_here ``` -------------------------------- ### Rack Configuration (config.ru) Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt Rack configuration file that sets up the application with WebSocket middleware for handling upgrade requests before Sinatra routes. ```ruby # config.ru - Rack configuration require_relative 'app' # WebSocket middleware intercepts /api/flux upgrade requests # before Sinatra handles standard HTTP routes use WebSocketMiddleware run App # Start the server with: bundle exec rackup -p 8081 -o 0.0.0.0 ``` -------------------------------- ### Ruby Dependencies (Gemfile) Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt The Gemfile lists the Ruby dependencies for the project, including Sinatra for the web framework, and other gems for CORS, web server, JWT handling, TOML parsing, environment variables, Rack server, and WebSockets. ```ruby # Gemfile source 'https://rubygems.org' gem 'sinatra', '4.1.1' # Web framework gem 'sinatra-cross_origin', '0.4.0' # CORS support gem 'puma', '6.5.0' # Async-capable web server gem 'jwt', '2.9.3' # JWT token handling gem 'toml-rb', '3.0.1' # TOML config parsing gem 'dotenv', '3.1.4' # Environment variable loading gem 'rackup', '2.2.1' # Rack server interface gem 'faye-websocket', '0.11.3' # WebSocket client/server # Install dependencies: bundle install ``` -------------------------------- ### WS /api/flux Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Establishes a WebSocket connection for advanced real-time transcription with turn-based detection. ```APIDOC ## WS /api/flux ### Description Establishes a WebSocket connection for advanced real-time transcription using Deepgram Flux. This endpoint supports turn-based detection and various customization parameters. ### Method WS (WebSocket) ### Endpoint `/api/flux` ### Parameters #### Query Parameters - **model** (string) - Optional - Flux STT model. Default: `flux-general-en`. - **encoding** (string) - Optional - Audio encoding. Options: `linear16`, `opus`. Default: `linear16`. - **sample_rate** (integer) - Optional - Audio sample rate. Range: `8000`-`48000`. Default: `16000`. - **eot_threshold** (number) - Optional - Confidence threshold for end-of-turn detection. Range: `0.0`-`1.0`. Default: `0.7`. - **eager_eot_threshold** (number) - Optional - Threshold for tentative (eager) end-of-turn detection. 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 be specified multiple times. ### Auth JWT session token passed via WebSocket subprotocol: `access_token.` ### Request Example ``` new WebSocket('wss://your-domain.com/api/flux', { protocols: ['access_token.YOUR_JWT_TOKEN'] }); ``` ### Response #### WebSocket Events - **StartOfTurn**: Indicates the beginning of a new speech turn. - **Update**: Provides interim transcription updates within the current turn. - **EagerEndOfTurn**: A tentative end of turn has been detected. - **TurnResumed**: The user resumed speaking after an `EagerEndOfTurn` event. - **EndOfTurn**: A confirmed end of turn with the final transcript for that turn. ``` -------------------------------- ### Manual Endpoint Checks Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Commands to manually check API endpoints for metadata and session information using curl and json_tool. ```bash curl -sf http://localhost:8081/api/metadata | python3 -m json.tool ``` ```bash curl -sf http://localhost:8081/api/session | python3 -m json.tool ``` -------------------------------- ### API Endpoints Source: https://github.com/deepgram-starters/ruby-flux/blob/main/AGENTS.md Overview of the available API endpoints for the Ruby 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. | ``` -------------------------------- ### WS /api/flux - WebSocket Flux Endpoint Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt The core WebSocket endpoint that proxies real-time audio to Deepgram's Flux API. Supports configurable EOT detection parameters, sample rate, encoding, and custom keyterms. Requires JWT authentication via the `access_token.*` subprotocol. ```APIDOC ## WS /api/flux ### Description Proxies real-time audio to Deepgram's Flux API. Supports configurable End-of-Turn (EOT) detection parameters, sample rate, encoding, and custom keyterms. Requires JWT authentication via the `access_token.*` subprotocol. ### Method WEBSOCKET ### Endpoint /api/flux ### Parameters #### Query Parameters - **encoding** (string) - Required. The audio encoding format (e.g., `linear16`). - **sample_rate** (integer) - Required. The audio sample rate (e.g., `16000`). - **eot_threshold** (float) - Optional. End-of-turn confidence threshold (0.0-1.0). - **eager_eot_threshold** (float) - Optional. Tentative end-of-turn threshold. - **eot_timeout_ms** (integer) - Optional. Silence timeout in milliseconds for EOT detection. - **keyterm** (string) - Optional. Custom vocabulary hint. Multiple `keyterm` parameters can be provided. ### Request Headers - **Sec-WebSocket-Protocol** (string) - Required. Must be in the format `access_token.`. ### Request Example (JavaScript Client) ```javascript async function connectToFlux() { const sessionResponse = await fetch('http://localhost:8081/api/session'); const { token } = await sessionResponse.json(); const params = new URLSearchParams({ encoding: 'linear16', sample_rate: '16000', eot_threshold: '0.7', eager_eot_threshold: '0.5', eot_timeout_ms: '5000', keyterm: 'Deepgram', keyterm: 'Nova' }); const ws = new WebSocket( `ws://localhost:8081/api/flux?${params}`, [`access_token.${token}`] ); ws.onopen = () => console.log('Connected to Flux'); ws.onmessage = (event) => { const data = JSON.parse(event.data); // Handle Flux turn events switch (data.type) { case 'StartOfTurn': console.log('User started speaking'); break; case 'Update': console.log('Interim:', data.channel.alternatives[0].transcript); break; case 'EagerEndOfTurn': console.log('Tentative end detected'); break; case 'TurnResumed': console.log('User continued speaking'); break; case 'EndOfTurn': console.log('Final:', data.channel.alternatives[0].transcript); break; } }; ws.onerror = (error) => console.error('WebSocket error:', error); ws.onclose = (event) => console.log(`Disconnected: ${event.code} ${event.reason}`); return ws; } ``` ### Response #### WebSocket Messages - **StartOfTurn**: Indicates the start of a speaker's turn. - **Update**: Provides interim transcription results. - **EagerEndOfTurn**: Indicates a tentative end of a turn. - **TurnResumed**: Indicates that a speaker has resumed speaking after a pause. - **EndOfTurn**: Provides the final transcription for a completed turn. Each message is a JSON object. For transcription messages (Update, EndOfTurn), the structure includes: - **type** (string) - The type of message. - **channel** (object) - **alternatives** (array of objects) - **transcript** (string) - The transcribed text. ### Response Example (EndOfTurn message) ```json { "type": "EndOfTurn", "channel": { "alternatives": [ { "transcript": "This is the final transcription." } ] } } ``` ``` -------------------------------- ### Request Session Token with cURL Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt Use cURL to request a JWT session token from the backend API for WebSocket authentication. The token is signed with HS256 and expires after 1 hour. ```bash # Request a session token curl -s http://localhost:8081/api/session | python3 -m json.tool ``` -------------------------------- ### Check Server Health with cURL Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt Perform a simple health check on the server by sending a cURL request to the health endpoint. This is useful for monitoring and load balancer probes. ```bash # Check server health curl -s http://localhost:8081/health | python3 -m json.tool ``` -------------------------------- ### POST /api/session - Session Authentication Source: https://context7.com/deepgram-starters/ruby-flux/llms.txt This endpoint issues JWT tokens for WebSocket authentication. Clients must obtain a token before connecting to the Flux WebSocket endpoint. Tokens are signed with HS256 and expire after 1 hour. ```APIDOC ## POST /api/session ### Description Issues JWT tokens for WebSocket authentication. Clients must obtain a token before connecting to the Flux WebSocket endpoint. Tokens are signed with HS256 and expire after 1 hour. ### Method POST ### Endpoint /api/session ### Request Body None ### Response #### Success Response (200) - **token** (string) - JWT token for WebSocket authentication. ### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MDk4..." } ``` ### Usage Use the token in WebSocket connection via subprotocol header: `Sec-WebSocket-Protocol: access_token.` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.