### Start LocalAPIServer Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/local-api.md Example of how to start the shared instance of the LocalAPIServer. ```swift LocalAPIServer.shared.start() ``` -------------------------------- ### Swift Integration Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/GENERATION_SUMMARY.txt Demonstrates starting and stopping the ASR service using Swift. Assumes shared instance access. ```swift let asrService = AppServices.shared.asr try await asrService.start() let text = await asrService.stop() ``` -------------------------------- ### Local API Usage Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/local-api.md Demonstrates how to start the Local API server and make a health check request from a client application. ```swift // Start server LocalAPIServer.shared.start() // Client code (from any local app) let url = URL(string: "http://127.0.0.1:47733/v1/health")! let (data, response) = try await URLSession.shared.data(from: url) let healthCheck = try JSONDecoder().decode(HealthResponse.self, from: data) print("Status: \(healthCheck.status)") ``` -------------------------------- ### Enable and Start Local API Server Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/errors.md Configure user defaults to enable the local API and then start the LocalAPIServer. If the local API is disabled, the start() method will return silently. ```swift // Configure to enable UserDefaults.standard.set(true, forKey: "LocalAPIEnabled") LocalAPIServer.shared.start() // If disabled, start() returns silently ``` -------------------------------- ### Client Libraries and Examples Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/GENERATION_SUMMARY.txt The documentation covers examples for various client libraries including Python, JavaScript/Node.js, cURL, and Swift, along with categories like initialization, configuration, speech recognition, LLM requests, AI enhancement, local API usage, and error handling. ```APIDOC ## Supported Client Libraries and Example Categories ### Client Libraries - Python (requests library) - JavaScript/Node.js (fetch) - cURL - Swift ### Example Categories - Initialization and setup - Configuration - Speech recognition - LLM requests - AI enhancement - Local API usage - Error handling - Swift/Objective-C patterns ``` -------------------------------- ### start() Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/asr-service.md Initiates audio capture and prepares the ASR service for transcription. This method should be called before starting any transcription process. ```APIDOC ## Method: start() ### Description Begin audio capture and prepare for transcription. ### Signature ```swift func start() async throws ``` ### Throws Errors from microphone access or transcription provider preparation. ### Example ```swift let asrService = ASRService() do { try await asrService.start() } catch { print("Failed to start ASR: \(error)") } ``` ``` -------------------------------- ### Setup Pre-commit Hook Source: https://github.com/altic-dev/fluidvoice/blob/main/README.md Installs a pre-commit hook to prevent accidental commits of team IDs. Ensure you have execute permissions for the script. ```bash cp scripts/check-team-id.sh .git/hooks/pre-commit chmod +x .git/hooks/pre-commit ``` -------------------------------- ### HotkeyShortcut displayString Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/hotkey-shortcut.md Demonstrates how to get a human-readable string representation of a HotkeyShortcut, including modifiers and the key name. Useful for displaying shortcuts to users. ```swift let hotkey = HotkeyShortcut(keyCode: 49, modifierFlags: [.command]) print(hotkey.displayString) // "⌘ + Space" ``` -------------------------------- ### Initialize and Start ASR Service Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/asr-service.md Initializes the ASRService and begins audio capture. Ensure microphone access is granted before starting. ```swift let asrService = ASRService() do { try await asrService.start() } catch { print("Failed to start ASR: \(error)") } ``` -------------------------------- ### Start LocalAPIServer Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/local-api.md Starts the Local API server. It reads configuration, ensures it's enabled, and only accepts loopback connections. ```swift func start() { // Implementation details omitted for brevity } ``` -------------------------------- ### LLM Request Example with Streaming Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/llm-client.md Demonstrates how to configure and send an LLM request using the LLMClient. This example includes setting up messages, model, API key, and enabling streaming with a content chunk handler. It also shows how to catch and print LLM errors. ```swift let config = LLMClient.Config( messages: [ ["role": "system", "content": "You are a helpful assistant"], ["role": "user", "content": "Hello!"] ], model: "gpt-4", baseURL: "https://api.openai.com/v1", apiKey: "sk-...", streaming: true, tools: [], temperature: 0.7, onContentChunk: { chunk in print("Streaming: \(chunk)") } ) do { let response = try await LLMClient.shared.request(config: config) print("Response: \(response.content)") if let thinking = response.thinking { print("Model thinking: \(thinking)") } } catch let error as LLMError { print("LLM error: \(error.errorDescription ?? \"unknown\")") } ``` -------------------------------- ### Navigation and Entry Points Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/GENERATION_SUMMARY.txt The documentation provides a clear navigation structure starting with README.md for an overview, INDEX.md for quick start and architecture, and specific service documentation within the api-reference/ directory. ```APIDOC ## Documentation Navigation Structure ### Entry Points - **README.md**: Overview and document structure. - **INDEX.md**: Architecture and common tasks. ### API Reference - Located in the `api-reference/` directory. ### Suggested Reading Order 1. README.md 2. INDEX.md 3. types.md 4. configuration.md 5. Specific service docs (e.g., `asr-service.md`) 6. endpoints.md 7. errors.md ``` -------------------------------- ### JavaScript/Node.js Client Examples Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Use the fetch API in JavaScript to communicate with the Fluidvoice API. Examples cover health checks, retrieving history, and transcribing audio. ```javascript const BASE_URL = "http://127.0.0.1:47733/v1"; // Health check fetch(`${BASE_URL}/health`) .then(r => r.json()) .then(data => console.log(data)); // Get history fetch(`${BASE_URL}/history?limit=10`) .then(r => r.json()) .then(history => { history.forEach(item => { console.log(`${item.timestamp}: ${item.text}`); }); }); // Transcribe audio const audioBase64 = btoa(audioData); fetch(`${BASE_URL}/transcribe`, { method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify({audio: audioBase64, format: "wav"}) }) .then(r => r.json()) .then(result => console.log(result.text)); ``` -------------------------------- ### Swift Customization Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/GENERATION_SUMMARY.txt Shows how to add a custom dictation prompt profile using Swift. Requires access to the shared SettingsStore. ```swift let profile = SettingsStore.DictationPromptProfile(...) SettingsStore.shared.addDictationPromptProfile(profile) ``` -------------------------------- ### HotkeyShortcut Initialization and Usage Examples Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/types.md Demonstrates how to create a HotkeyShortcut instance, display its string representation, check if an event matches the shortcut, and detect conflicts between modifier-only shortcuts. ```swift // Create Command+Space let hotkey = HotkeyShortcut( keyCode: 49, // Space modifierFlags: [.command] ) print(hotkey.displayString) // "⌘ + Space" // Check if event matches let matches = hotkey.matches(keyCode: eventKeyCode, modifiers: eventModifiers) // Detect conflicts between two modifier-only shortcuts let conflict = shortcut1.conflictsWith(shortcut2) ``` -------------------------------- ### Enable and Start Local API Server Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/INDEX.md Enable the local API via UserDefaults and start the LocalAPIServer. Access the API at http://127.0.0.1:47733/v1/health. ```swift UserDefaults.standard.set(true, forKey: "LocalAPIEnabled") LocalAPIServer.shared.start() // Then access at http://127.0.0.1:47733/v1/health ``` -------------------------------- ### POST /v1/postprocess cURL Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Example of how to call the post-processing endpoint using cURL, specifying the text and mode. ```bash curl -X POST http://127.0.0.1:47733/v1/postprocess \ -H "Content-Type: application/json" \ -d '{ "text": "hello world", "mode": "dictate" }' ``` -------------------------------- ### Install FluidVoice with Homebrew Source: https://github.com/altic-dev/fluidvoice/blob/main/README.md Use this command to install FluidVoice on your macOS system using Homebrew. ```bash brew install --cask fluidvoice ``` -------------------------------- ### Python Client Examples Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Interact with the Fluidvoice API using Python's requests library. Examples include health checks, fetching history, and adding dictionary replacements. ```python import requests import json BASE_URL = "http://127.0.0.1:47733/v1" # Health check response = requests.get(f"{BASE_URL}/health") print(response.json()) # Get history response = requests.get(f"{BASE_URL}/history?limit=10") history = response.json() for item in history: print(f"{item['timestamp']}: {item['text']}") # Add replacement response = requests.post( f"{BASE_URL}/dictionary/replacements", json={"from": "ur", "to": "your"} ) print(f"Status: {response.status_code}") ``` -------------------------------- ### GET /v1/dictionary/replacements Response Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md The response is an array of objects, where each object specifies a word replacement from 'from' to 'to'. ```json [ { "from": "ur", "to": "your" }, { "from": "teh", "to": "the" } ] ``` -------------------------------- ### cURL Examples Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Perform API operations using cURL commands. Includes examples for health checks, fetching history with a limit, and adding custom words to the dictionary. ```bash # Health check curl http://127.0.0.1:47733/v1/health # Get history curl "http://127.0.0.1:47733/v1/history?limit=5" # Add word to dictionary curl -X POST http://127.0.0.1:47733/v1/dictionary/custom-words \ -H "Content-Type: application/json" \ -d '{"word":"MacBook","definition":"Apple laptop"}' ``` -------------------------------- ### Example Usage of OpenAICompatibleProvider Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/ai-provider.md Demonstrates how to use the OpenAICompatibleProvider to process text with an AI model. Ensure you have the provider initialized and provide valid API credentials and endpoint details. ```swift let provider = OpenAICompatibleProvider() let result = await provider.process( systemPrompt: "You are a helpful assistant", userText: "Fix the grammar: Im happy today", model: "gpt-4", apiKey: "sk-.", baseURL: "https://api.openai.com/v1", stream: false ) print(result) // "I'm happy today" ``` -------------------------------- ### WhisperProvider Usage Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/transcription-provider.md Demonstrates the typical workflow for using the WhisperProvider, including preparation, checking availability, capturing audio, transcribing, and clearing the cache. Ensure the provider is prepared before use. ```swift // Create provider let provider = WhisperProvider() // Ensure ready try await provider.prepare { updateUI(progress: progress) } // Check availability guard provider.isAvailable && provider.isReady else { print("Provider not ready") return } // Transcribe samples let samples = await captureAudio() let result = try await provider.transcribe(samples) print("You said: \(result.text)") // Cleanup try await provider.clearCache() ``` -------------------------------- ### App Initialization with AppServices Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/app-services.md Sets up the main application struct, injecting the AppServices singleton as an environment object. This pattern is used for top-level application setup. ```swift @main struct FluidApp: App { @StateObject private var appServices: AppServices init() { _appServices = StateObject(wrappedValue: AppServices.shared) } var body: some Scene { WindowGroup { ContentView() .environmentObject(appServices) } } } ``` -------------------------------- ### POST /v1/dictionary/replacements Response Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md A successful addition or update returns a 204 No Content status. ```http HTTP/1.1 204 No Content ``` -------------------------------- ### GET /v1/dictionary/replacements Request Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Retrieve word replacement rules from the dictionary. The 'limit' parameter controls the number of results returned, with a maximum of 1000. ```http GET /v1/dictionary/replacements?limit=100 HTTP/1.1 Host: 127.0.0.1:47733 ``` -------------------------------- ### Stop LocalAPIServer Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/local-api.md Example of how to stop the shared instance of the LocalAPIServer. ```swift LocalAPIServer.shared.stop() ``` -------------------------------- ### Ensure Transcription Provider is Ready with Progress Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/asr-service.md Downloads and prepares the necessary speech recognition model. Provides a progress handler to monitor download status. This method should be called before starting transcription. ```swift do { try await asrService.ensureTranscriptionProviderReady { progress in print("Download: \(Int(progress * 100))%") } } catch { print("Model preparation failed: \(error)") } ``` -------------------------------- ### POST /v1/postprocess Response Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md The response contains the enhanced text and a boolean indicating if any modifications were made. ```json { "text": "Hello world.", "changed": true } ``` -------------------------------- ### getAppPromptBinding Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/settings-store.md Get the prompt binding configuration for a specific application identified by its bundle ID. Returns the binding details or nil if none is configured. ```APIDOC ## getAppPromptBinding(forBundleID:) ### Description Get the prompt binding for a specific app. ### Method func getAppPromptBinding(forBundleID bundleID: String) -> AppPromptBinding? ### Parameters #### Path Parameters - **bundleID** (String) - Required - Bundle ID of the app to retrieve binding for ### Returns Binding or nil if not configured ``` -------------------------------- ### Integrate ASRService with Dictation Post-Processing Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/dictation-post-processing.md Shows how to start and stop the ASRService, which automatically utilizes the DictationPostProcessingService for enhanced transcriptions if enabled. ```swift let asrService = ASRService() try await asrService.start() // ... speak ... let transcribed = await asrService.stop() // If enhancement is enabled, finalText is already enhanced // Otherwise it's raw transcription ``` -------------------------------- ### POST /v1/dictionary/replacements Request Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Add or update a word replacement rule in the dictionary. Both 'from' and 'to' fields are required. ```json { "from": "ur", "to": "your" } ``` -------------------------------- ### Generic Error Response Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Example JSON format for all error responses, such as route not found. ```json { "error": "Route not found." } ``` -------------------------------- ### API Documentation Structure Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/GENERATION_SUMMARY.txt Each API document includes the exact signature from the source, parameter tables with types and defaults, return types and descriptions, error conditions, and minimal examples. Cross-references and hierarchical navigation are also provided. ```APIDOC ## API Document Contents ### Signature Exact signature from source code. ### Parameters - **paramName** (type) - Required/Optional - Description with default values if applicable. ### Returns - **type** - Description of the return value. ### Errors - **ErrorType** - Description of when this error is thrown or rejected. ### Examples Minimal but complete code examples demonstrating usage. ### Source Reference - **File**: path/to/source/file.ext - **Line**: line_number ``` -------------------------------- ### POST /v1/postprocess Request Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Send transcribed text to the post-processing endpoint for AI-enhanced output. The 'mode' parameter can be set to 'dictate' or 'edit', and 'context' provides surrounding text for better results. ```json { "text": "hello world", "mode": "dictate", "context": "Selected text before dictation" } ``` -------------------------------- ### Retrieve All Dictation Prompt Profiles Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/settings-store.md Gets a list of all custom dictation prompt profiles currently configured. Returns an empty array if none are set. ```swift func allDictationPromptProfiles() -> [DictationPromptProfile] ``` -------------------------------- ### GET /v1/history Request Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Example of a GET request to retrieve transcription history with pagination parameters. ```http GET /v1/history?limit=50&offset=0 HTTP/1.1 Host: 127.0.0.1:47733 ``` -------------------------------- ### HotkeyShortcut isModifierOnlyShortcut Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/hotkey-shortcut.md Shows how to determine if a HotkeyShortcut is triggered by a modifier key alone. This is useful for differentiating between shortcuts that require a modifier and another key, versus those that are just the modifier itself. ```swift // Command+V (regular key) let regular = HotkeyShortcut(keyCode: 9, modifierFlags: [.command]) print(regular.isModifierOnlyShortcut) // false // Right Command (modifier only) let modifier = HotkeyShortcut(keyCode: 54, modifierFlags: []) print(modifier.isModifierOnlyShortcut) // true ``` -------------------------------- ### GET /v1/history Response (200 OK) Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Example JSON response for a successful retrieval of transcription history. ```json [ { "id": "abc123", "text": "hello world", "timestamp": "2025-12-21T10:30:00Z", "model": "parakeet-tdt-v3", "duration_ms": 2500 } ] ``` -------------------------------- ### Basic Dictation with ASR Service Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/README.md Starts the ASR service, captures audio input, and stops the service to retrieve transcribed text. The output will be enhanced text if AI is enabled, otherwise raw transcription. ```swift let asrService = AppServices.shared.asr try await asrService.start() // ... speak ... let text = await asrService.stop() print(text) // Enhanced text if AI enabled, raw otherwise ``` -------------------------------- ### Startup Flow Visualization Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/README.md Illustrates the sequence of events during application startup, highlighting lazy service initialization after the UI is ready to prevent crashes. ```text 1. AppServices singleton created (services not yet initialized) ↓ 2. UI renders and completes (1.5s delay for AttributeGraph) ↓ 3. signalUIReady() called ↓ 4. initializeServicesIfNeeded() called ↓ 5. Services lazily initialized on first access ``` -------------------------------- ### GET /v1/dictionary/custom-words Response Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md The response is an array of custom word objects, each containing the 'word' and an optional 'definition'. ```json [ { "word": "Kubernetes", "definition": "container orchestration platform" } ] ``` -------------------------------- ### GET /v1/dictionary/custom-words Request Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Retrieve custom words from the dictionary. The 'limit' parameter restricts the number of words returned, up to a maximum of 1000. ```http GET /v1/dictionary/custom-words?limit=100 HTTP/1.1 Host: 127.0.0.1:47733 ``` -------------------------------- ### prepare(progressHandler:) Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/transcription-provider.md Downloads and/or loads transcription models. It can optionally report download progress. ```APIDOC ## prepare(progressHandler:) ### Description Download and/or load models for transcription. This method can optionally provide progress updates during the download process. ### Method `async throws` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **progressHandler** ((Double) -> Void)? - No - Callback for download progress (0.0 to 1.0) ### Throws Error if download or model loading fails ### Example ```swift let provider = ParakeetRealtimeProvider() do { try await provider.prepare { progress in print("Download: \(Int(progress * 100))%") } } catch { print("Failed to prepare: \(error)") } ``` ``` -------------------------------- ### Prepare Transcription Models Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/transcription-provider.md Downloads and loads transcription models. Use the progress handler to monitor download progress. This method can throw an error if preparation fails. ```swift let provider = ParakeetRealtimeProvider() do { try await provider.prepare { progress in print("Download: \(Int(progress * 100))%") } } catch { print("Failed to prepare: \(error)") } ``` -------------------------------- ### Creating and Using Custom Prompt Profiles Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/dictation-post-processing.md Illustrates how to define a custom `DictationPromptProfile` for specific formatting (e.g., code comments) and add it to the `SettingsStore`. The custom profile can then be used for text enhancement. ```swift let codePrompt = SettingsStore.DictationPromptProfile( name: "Code Comments", prompt: "Format as a concise code comment preserving technical terms", mode: .edit, includeContext: false ) SettingsStore.shared.addDictationPromptProfile(codePrompt) // Later, use it let dictated = "creates a new user with email and password" let enhanced = await service.process( text: dictated, mode: .edit, context: nil ) // "Creates a new user with email and password." ``` -------------------------------- ### Health Check Endpoint Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/local-api.md Example of how to perform a health check on the Local API. ```APIDOC ## Usage Example ```swift // Start server LocalAPIServer.shared.start() // Client code (from any local app) let url = URL(string: "http://127.0.0.1:47733/v1/health")! let (data, response) = try await URLSession.shared.data(from: url) let healthCheck = try JSONDecoder().decode(HealthResponse.self, from: data) print("Status: \(healthCheck.status)") ``` ### GET /v1/health #### Description Checks the health status of the Local API. #### Endpoint `/v1/health` #### Response ##### Success Response (200) - **status** (string) - The health status of the API (e.g., "ok"). ``` -------------------------------- ### Enable Local API Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/local-api.md Configuration instructions for enabling the Local API via UserDefaults or the Settings UI. ```APIDOC ## Configuration Enable Local API in UserDefaults: ```swift let defaults = UserDefaults.standard defaults.set(true, forKey: "LocalAPIEnabled") defaults.set(47733, forKey: "LocalAPIPort") ``` Or via Settings UI: `Settings → Advanced → Local API → Enable` ``` -------------------------------- ### Get History Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Retrieves a list of historical transcription data, with an optional limit. ```APIDOC ## GET /history ### Description Retrieves a list of historical transcription data. ### Method GET ### Endpoint /v1/history ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of history items to retrieve. ``` -------------------------------- ### Configure Hotkey and Local API Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/README.md Defines a command + space hotkey for dictation and enables the local API server. ```swift // Hotkey let hotkey = HotkeyShortcut(keyCode: 49, modifierFlags: [.command]) SettingsStore.shared.dictationHotkey = hotkey // Local API UserDefaults.standard.set(true, forKey: "LocalAPIEnabled") LocalAPIServer.shared.start() ``` -------------------------------- ### Start and Stop Dictation Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/INDEX.md Initiate speech-to-text dictation and retrieve the transcribed text upon stopping. ```swift let asrService = AppServices.shared.asr try await asrService.start() // ... speak ... let text = await asrService.stop() ``` -------------------------------- ### Process Text with O1 Reasoning Model Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/ai-provider.md Engage a specific reasoning model like 'o1' using the OpenAICompatibleProvider. This model typically does not use temperature settings. ```swift let provider = OpenAICompatibleProvider() let result = await provider.process( systemPrompt: "You are a problem solver.", userText: "Find all integer solutions to x^2 + y^2 = 25", model: "o1", // Reasoning model (no temperature) apiKey: "sk-...", baseURL: "https://api.openai.com/v1", stream: false ) print(result) ``` -------------------------------- ### GET /v1/dictionary/custom-words Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Retrieves custom words from the dictionary. Supports limiting the number of words returned. ```APIDOC ## GET /v1/dictionary/custom-words ### Description Get custom dictionary. This endpoint retrieves a list of custom words added to the dictionary, optionally including their definitions. ### Method GET ### Endpoint /v1/dictionary/custom-words ### Parameters #### Query Parameters - **limit** (integer) - No - Default: 100, Maximum: 1000 - Number of words to return ### Response #### Success Response (200 OK) - **Array of word objects** - **word** (string) - Word - **definition** (string) - Definition (optional) #### Response Example ```json [ { "word": "Kubernetes", "definition": "container orchestration platform" } ] ``` ``` -------------------------------- ### Convert Key Code to String with Keyboard Layout Support Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/hotkey-shortcut.md Illustrates converting a key code to its string representation, automatically handling different keyboard layouts. Falls back to QWERTY if the current layout is not supported. ```swift // On French AZERTY: '2' might be displayed differently let qwerty = HotkeyShortcut.keyCodeToString(19) // "2" (QWERTY) // On AZERTY: might be "é" or different character ``` -------------------------------- ### Get Transcription History Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Retrieves a paginated list of past transcriptions. Supports filtering by limit and offset. ```APIDOC ## GET /v1/history ### Description Retrieve transcription history. ### Method GET ### Endpoint /v1/history ### Query Parameters - **limit** (integer) - Optional - Number of items to return. Default: 100, Maximum: 1000 - **offset** (integer) - Optional - Pagination offset. Default: 0 ### Request Example ```http GET /v1/history?limit=50&offset=0 HTTP/1.1 Host: 127.0.0.1:47733 ``` ### Response #### Success Response (200 OK) - **id** (string) - Unique identifier - **text** (string) - Transcribed text - **timestamp** (string) - When transcribed (ISO8601 format) - **model** (string) - ASR model used - **duration_ms** (integer) - Recording duration in milliseconds #### Response Example ```json [ { "id": "abc123", "text": "hello world", "timestamp": "2025-12-21T10:30:00Z", "model": "parakeet-tdt-v3", "duration_ms": 2500 } ] ``` ### Errors - `500` — History lookup failed ``` -------------------------------- ### createAppPromptBinding Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/settings-store.md Create a binding between an application and a prompt profile. This allows specific apps to use custom prompts. ```APIDOC ## createAppPromptBinding(mode:appBundleID:appName:promptID:) ### Description Create a binding between an app and a prompt profile. ### Method func createAppPromptBinding( mode: PromptMode, appBundleID: String, appName: String, promptID: String? ) ### Parameters #### Path Parameters - **mode** (PromptMode) - Required - Dictate or edit mode - **appBundleID** (String) - Required - Bundle identifier of target app - **appName** (String) - Required - Human-readable app name - **promptID** (String?) - Optional - Profile ID or nil for default ``` -------------------------------- ### GET /v1/dictionary/replacements Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Retrieves a list of word replacement rules. Supports limiting the number of results returned. ```APIDOC ## GET /v1/dictionary/replacements ### Description Get word replacements. This endpoint retrieves a list of predefined word replacements that can be used to automatically correct or standardize text. ### Method GET ### Endpoint /v1/dictionary/replacements ### Parameters #### Query Parameters - **limit** (integer) - No - Default: 100, Maximum: 1000 - Number of replacements to return ### Response #### Success Response (200 OK) - **Array of replacement objects** - **from** (string) - Text to replace - **to** (string) - Replacement text #### Response Example ```json [ { "from": "ur", "to": "your" }, { "from": "teh", "to": "the" } ] ``` ``` -------------------------------- ### SettingsStore.DictationPromptProfile Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/types.md Defines a template for AI enhancement prompts used in dictation settings. ```APIDOC ## SettingsStore.DictationPromptProfile ### Description Template for AI enhancement prompts. ### Properties - **id** (String) - Unique identifier (UUID) - **name** (String) - Display name - **prompt** (String) - Prompt template text - **mode** (PromptMode) - Dictate or edit mode - **includeContext** (Bool) - Include selected text as context - **createdAt** (Date) - Creation timestamp - **updatedAt** (Date) - Last modification timestamp ``` -------------------------------- ### POST /v1/dictionary/custom-words Request Example Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Add a word to the custom dictionary. The 'word' is mandatory, and a 'definition' can be optionally provided. ```json { "word": "Kubernetes", "definition": "container orchestration platform" } ``` -------------------------------- ### allDictationPromptProfiles Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/settings-store.md Get all custom prompt profiles currently stored. This method returns an array containing all available profiles. ```APIDOC ## allDictationPromptProfiles() ### Description Get all custom prompt profiles. ### Method func allDictationPromptProfiles() -> [DictationPromptProfile] ### Returns Array of all profiles ``` -------------------------------- ### init(keyCode:modifierFlags:modifierKeyCodes:) Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/hotkey-shortcut.md Initializes a HotkeyShortcut with a primary key code and modifier information. It supports automatic validation and normalization of modifiers, with an option to provide explicit modifier key codes. ```APIDOC ## init(keyCode:modifierFlags:modifierKeyCodes:) ### Description Creates a hotkey with automatic validation and normalization. ### Parameters #### Path Parameters - **keyCode** (UInt16) - Required - Primary key code - **modifierFlags** (NSEvent.ModifierFlags) - Required - Modifier flags - **modifierKeyCodes** ([UInt16]) - Optional - Explicit modifier key codes (defaults to []) ### Details - Normalizes modifier key codes (deduplicates and sorts). - Validates modifier flags. - If modifierKeyCodes is provided, uses them instead of modifierFlags. - Removes trigger key from combined modifiers. ### Request Example ```swift // Command+Space let hotkey = HotkeyShortcut( keyCode: 49, // Space modifierFlags: [.command] ) // Or with explicit modifier key codes let hotkey2 = HotkeyShortcut( keyCode: 49, modifierFlags: [], modifierKeyCodes: [55, 49] // Command + Space ) ``` ``` -------------------------------- ### App-Specific Enhancement Configuration Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/dictation-post-processing.md Details how to create an app-specific prompt profile and bind it to a particular application using its bundle ID. This allows for tailored dictation enhancement based on the active application. ```swift // Configure different enhancement per app let scriptPrompt = SettingsStore.DictationPromptProfile( name: "AppleScript", prompt: "Format as AppleScript code, preserve technical syntax", mode: .edit, includeContext: false ) SettingsStore.shared.addDictationPromptProfile(scriptPrompt) SettingsStore.shared.createAppPromptBinding( mode: .edit, appBundleID: "com.apple.ScriptEditor2", appName: "Script Editor", promptID: scriptPrompt.id ) // When dictating in Script Editor, uses ScriptPrompt let enhanced = await service.process( text: "delay for one second", mode: .edit, context: nil ) // "delay for 1 second" (preserves AppleScript style) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/altic-dev/fluidvoice/blob/main/docs/MACOS_UI_AUTOMATION_BRANCH_PLAN.md Command to execute unit tests for the Fluid project. Ensure the correct scheme and destination are specified. ```bash xcodebuild test -project Fluid.xcodeproj -scheme Fluid -destination 'platform=macOS,arch=arm64' -only-testing:FluidTests ``` -------------------------------- ### Clone FluidVoice Repository and Open Project Source: https://github.com/altic-dev/fluidvoice/blob/main/README.md Clone the FluidVoice repository from GitHub and open the Xcode project. Dependencies are managed via Swift Package Manager. ```bash git clone https://github.com/altic-dev/FluidVoice.git cd FluidVoice open Fluid.xcodeproj ``` -------------------------------- ### Enable Local API in UserDefaults Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/local-api.md Configure the Local API by setting 'LocalAPIEnabled' to true and specifying the port in UserDefaults. ```swift let defaults = UserDefaults.standard defaults.set(true, forKey: "LocalAPIEnabled") defaults.set(47733, forKey: "LocalAPIPort") ``` -------------------------------- ### Local API Health Check Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/README.md Performs a health check on the local FluidVoice API. This is a simple GET request to the health endpoint. ```bash # Health check curl http://127.0.0.1:47733/v1/health ``` -------------------------------- ### GET /v1/health Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/endpoints.md Checks the health of the FluidVoice server and retrieves its current version. This endpoint is useful for verifying that the Local API is running and accessible. ```APIDOC ## GET /v1/health ### Description Server health check and version info. ### Method GET ### Endpoint /v1/health ### Response #### Success Response (200 OK) - **status** (string) - Server status ("ok") - **version** (string) - App version #### Response Example ```json { "status": "ok", "version": "1.6.0" } ``` ``` -------------------------------- ### Check and Load ASR Model Readiness Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/errors.md Before transcribing, verify if the Automatic Speech Recognition (ASR) service is ready. If models exist on disk, load them; otherwise, initiate a download. ```swift // Check before transcribing if !asrService.isAsrReady { if asrService.modelsExistOnDisk { // Load model try await asrService.ensureTranscriptionProviderReady() } else { // Download model try await asrService.ensureTranscriptionProviderReady { progress in print("Download: \(Int(progress * 100))%") } } } ``` -------------------------------- ### SettingsStore Class Signature Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/settings-store.md Defines the SettingsStore class, its singleton instance, and constants for transcription preview character limits. ```swift final class SettingsStore: ObservableObject { static let shared = SettingsStore() static let transcriptionPreviewCharLimitRange: ClosedRange = 50...800 static let transcriptionPreviewCharLimitStep = 50 static let defaultTranscriptionPreviewCharLimit = 150 } ``` -------------------------------- ### Get Modifier Flag for Key Code Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/hotkey-shortcut.md Retrieves the NSEvent.ModifierFlags corresponding to a given modifier key code. Provides a mapping for common modifier keys. ```swift static func modifierFlag(forKeyCode keyCode: UInt16) -> NSEvent.ModifierFlags? ``` ```swift let flag = HotkeyShortcut.modifierFlag(forKeyCode: 55) print(flag) // Optional(.command) ``` -------------------------------- ### Get AI Enhancement Mode Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/dictation-post-processing.md Retrieve the current AI enhancement mode for dictation. Modes range from off to default, private AI, or a custom profile. ```swift SettingsStore.shared.dictationAIMode ``` -------------------------------- ### Access Audio Hardware Observer Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/app-services.md Access the audio hardware observer. It is lazily created upon first access, not during AppServices initialization. ```swift let observer = appServices.audioObserver print("Microphone: \(observer.defaultMicrophoneDevice)") ``` -------------------------------- ### OpenAICompatibleProvider.process Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/ai-provider.md Sends text to an OpenAI-compatible API and returns the response. It handles various configurations like streaming, local endpoints, and specific model requirements. ```APIDOC ## func process(systemPrompt:userText:model:apiKey:baseURL:stream:) ### Description Sends text to an OpenAI-compatible API and returns the response. It handles various configurations like streaming, local endpoints, and specific model requirements. ### Method `async func` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **systemPrompt** (String) - Required - System instruction - **userText** (String) - Required - User message - **model** (String) - Required - Model identifier - **apiKey** (String) - Required - API authentication key - **baseURL** (String) - Required - API base URL - **stream** (Bool) - Optional - Default: `false` - Enable streaming ### Returns Content from first response choice, or error message ### Error Handling: - Invalid URL → "Error: Invalid Base URL" - HTTP errors → "Error: HTTP {code}: {body}" - JSON encoding failure → "Error: Failed to encode request" - Network/connection errors → "Error: {error description}" - Decoding errors → "Error: {error description}" ### Special Behavior: 1. **URL Handling:** If baseURL doesn't contain /chat/completions, /api/chat, or /api/generate, automatically appends /chat/completions 2. **Local Endpoints:** For loopback addresses (127.0.0.1, localhost, 10.x.x.x, etc.), omits Authorization header 3. **Temperature Handling:** For reasoning models (o1, o3, gpt-5), omits temperature parameter 4. **Reasoning Effort:** For gpt-oss models (Groq), adds `reasoning_effort: "low"` 5. **Default Temperature:** Sets temperature to 0.2 for non-reasoning models ``` -------------------------------- ### audioObserver Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/app-services.md Provides access to the audio hardware observer. This property is lazily initialized, meaning the observer is only created when it is first accessed. ```APIDOC ## audioObserver ### Description Get or lazily create the audio hardware observer. ### Method var ### Parameters None ### Returns AudioHardwareObserver instance (created on first access) ### Details - The observer is only created when first accessed, not at AppServices initialization. ### Example ```swift let observer = appServices.audioObserver print("Microphone: \(observer.defaultMicrophoneDevice)") ``` ``` -------------------------------- ### Compare HotkeyShortcut Instances Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/hotkey-shortcut.md Shows how to compare two HotkeyShortcut instances for equality. Equality is determined by matching modifier key codes or, if normalized, by matching keyCode and relevantModifierFlags. ```swift let hotkey1 = HotkeyShortcut(keyCode: 49, modifierFlags: [.command]) let hotkey2 = HotkeyShortcut(keyCode: 49, modifierFlags: [.command, .option]) hotkey1 == hotkey1 // true hotkey1 == hotkey2 // false ``` -------------------------------- ### Store and Retrieve API Key Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/settings-store.md Demonstrates how to store and retrieve an API key using the SettingsStore. The key is automatically encrypted and decrypted. ```swift // Store a key SettingsStore.shared.openAIKey = "sk-..." // Retrieve (automatically decrypted) if let key = SettingsStore.shared.openAIKey { // use key } ``` -------------------------------- ### Initialize HotkeyShortcut with Modifiers Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/hotkey-shortcut.md Create a hotkey using primary key code and modifier flags. Supports explicit modifier key codes as an alternative. ```swift init( keyCode: UInt16, modifierFlags: NSEvent.ModifierFlags, modifierKeyCodes: [UInt16] = [] ) ``` ```swift // Command+Space let hotkey = HotkeyShortcut( keyCode: 49, // Space modifierFlags: [.command] ) // Or with explicit modifier key codes let hotkey2 = HotkeyShortcut( keyCode: 49, modifierFlags: [], modifierKeyCodes: [55, 49] // Command + Space ) ``` -------------------------------- ### Get App Prompt Binding for Bundle ID Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/settings-store.md Retrieves the prompt binding configuration for a given application bundle identifier. Returns `nil` if no binding is configured for the app. ```swift func getAppPromptBinding(forBundleID bundleID: String) -> AppPromptBinding? ``` -------------------------------- ### Process Text with Local LM Studio Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/ai-provider.md Connect to a locally running language model via LM Studio using the OpenAICompatibleProvider. The API key is not used for local endpoints. ```swift let provider = OpenAICompatibleProvider() let result = await provider.process( systemPrompt: "You are helpful.", userText: "What is 2+2?", model: "local-model", apiKey: "", // Not used for local endpoints baseURL: "http://localhost:1234/v1", stream: false ) print(result) // "2+2 equals 4" ``` -------------------------------- ### Create App Prompt Binding Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/settings-store.md Establishes a link between an application and a prompt profile. You can specify a particular prompt profile or use the default. ```swift func createAppPromptBinding( mode: PromptMode, appBundleID: String, appName: String, promptID: String? ) ``` -------------------------------- ### Local API Response Constructor Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/types.md Initializes a Local API response. Defaults are provided for headers and body. ```swift init(status: Int, headers: [String: String] = [:], body: Data = Data()) ``` -------------------------------- ### Local API Get Transcription History Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/README.md Retrieves a limited number of transcription history records from the local FluidVoice API. The 'limit' query parameter controls the number of results returned. ```bash # Get history curl http://127.0.0.1:47733/v1/history?limit=10 ``` -------------------------------- ### initializeServicesIfNeeded() Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/app-services.md Safely initializes all services after the UI is ready. This method is idempotent and can be called multiple times, but services will only be initialized once. ```APIDOC ## initializeServicesIfNeeded() ### Description Safely initialize all services after the UI is ready. ### Method func ### Parameters None ### Details - Call this from ContentView.onAppear after signalUIReady() - Safe to call multiple times—only initializes once - Logs initialization progress ### Example ```swift .onAppear { Task { try? await Task.sleep(nanoseconds: 1_500_000_000) appServices.signalUIReady() appServices.initializeServicesIfNeeded() } } ``` ``` -------------------------------- ### Get Selected AI Provider Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/dictation-post-processing.md Retrieve the currently selected AI provider for dictation processing. Options include OpenAI, Groq, Anthropic, Cohere, custom endpoints, and local models. ```swift SettingsStore.shared.selectedAIProvider ``` -------------------------------- ### Documentation Verification and Quality Checks Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/GENERATION_SUMMARY.txt The documentation undergoes rigorous quality checks to ensure completeness, accuracy, and adherence to technical precision, including verifying all public elements, tested examples, and consistent formatting. ```APIDOC ## Documentation Quality Assurance ### Completeness Checks - All public classes and structs documented - All public methods documented - All public properties documented - All configuration options documented - All HTTP endpoints documented - Error handling documented - Thread safety notes included ### Quality Checks - No placeholder content - All examples tested against source code - All signatures match source code - All links are internal and valid - Consistent formatting throughout - No marketing copy or introductions - Focus on technical precision ``` -------------------------------- ### Configure SettingsStore in Swift Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/configuration.md Use SettingsStore.shared to access and modify application settings. This includes setting speech models, enabling AI enhancements with API keys, defining hotkeys, creating custom prompt profiles, and binding profiles to specific applications. It also covers enabling and configuring local audio history. ```swift let settings = SettingsStore.shared // Configure speech model settings.selectedSpeechModel = .parakeetTDT // Enable AI enhancement with OpenAI settings.selectedAIProvider = .openai settings.openAIKey = "sk-..." settings.aiEnhancementEnabled = true // Set dictation hotkey (Command+Space) let hotkey = HotkeyShortcut( keyCode: 49, modifierFlags: [.command] ) settings.dictationHotkey = hotkey // Create a custom prompt profile let profile = SettingsStore.DictationPromptProfile( name: "Email", prompt: "Format as professional email", mode: .edit, includeContext: true ) settings.addDictationPromptProfile(profile) // Bind profile to Mail app settings.createAppPromptBinding( mode: .edit, appBundleID: "com.apple.mail", appName: "Mail", promptID: profile.id ) // Enable local audio history settings.recordAudioHistory = true settings.audioHistoryBudgetMB = 1000 ``` -------------------------------- ### Get Selected Prompt Profile Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/dictation-post-processing.md Retrieves the active prompt profile for a given app bundle ID and processing mode. Falls back to the default profile if no app-specific binding is found. Returns nil if the mode is set to .off. ```swift let prompt = service.getSelectedPrompt( for: "com.apple.mail", mode: .edit ) if let prompt = prompt { print("Using profile: \(prompt.name)") print("Prompt: \(prompt.prompt)") } ``` -------------------------------- ### Create a Custom Dictation Prompt Profile Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/INDEX.md Define a custom prompt profile for dictation, specifying its name, prompt text, mode, and context inclusion. ```swift let profile = SettingsStore.DictationPromptProfile( name: "Email", prompt: "Format as professional email", mode: .edit, includeContext: true ) SettingsStore.shared.addDictationPromptProfile(profile) ``` -------------------------------- ### Create Custom Prompt Profile Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/api-reference/dictation-post-processing.md Define and add a custom prompt profile for dictation. This allows for specific formatting and enhancement instructions, including context inclusion. ```swift let profile = SettingsStore.DictationPromptProfile( name: "Email", prompt: "Format as a professional email with proper grammar", mode: .edit, includeContext: true ) SettingsStore.shared.addDictationPromptProfile(profile) ``` -------------------------------- ### Configure Speech and AI Settings Source: https://github.com/altic-dev/fluidvoice/blob/main/_autodocs/README.md Sets the default speech recognition model to Parakeet TDT and enables OpenAI for AI enhancement, requiring an API key. ```swift // Speech model SettingsStore.shared.selectedSpeechModel = .parakeetTDT // AI enhancement SettingsStore.shared.selectedAIProvider = .openai SettingsStore.shared.openAIKey = "sk-..." SettingsStore.shared.aiEnhancementEnabled = true ```