# Table of Contents - [Welcome to RunAnywhere - RunAnywhere Documentation](#welcome-to-runanywhere-runanywhere-documentation) - [Best Practices - RunAnywhere Documentation](#best-practices-runanywhere-documentation) - [Configuration - RunAnywhere Documentation](#configuration-runanywhere-documentation) - [Installation - RunAnywhere Documentation](#installation-runanywhere-documentation) - [Introduction - RunAnywhere Documentation](#introduction-runanywhere-documentation) - [chat() - RunAnywhere Documentation](#chat-runanywhere-documentation) - [Streaming TTS - RunAnywhere Documentation](#streaming-tts-runanywhere-documentation) - [generate() - RunAnywhere Documentation](#generate-runanywhere-documentation) - [Streaming STT - RunAnywhere Documentation](#streaming-stt-runanywhere-documentation) - [Configuration - RunAnywhere Documentation](#configuration-runanywhere-documentation) - [generateStream() - RunAnywhere Documentation](#generatestream-runanywhere-documentation) - [Voices - RunAnywhere Documentation](#voices-runanywhere-documentation) - [Error Handling - RunAnywhere Documentation](#error-handling-runanywhere-documentation) - [Voice Activity Detection - RunAnywhere Documentation](#voice-activity-detection-runanywhere-documentation) - [STT Options - RunAnywhere Documentation](#stt-options-runanywhere-documentation) - [Installation - RunAnywhere Documentation](#installation-runanywhere-documentation) - [System Prompts - RunAnywhere Documentation](#system-prompts-runanywhere-documentation) - [synthesize() - RunAnywhere Documentation](#synthesize-runanywhere-documentation) - [Quick Start - RunAnywhere Documentation](#quick-start-runanywhere-documentation) - [Introduction - RunAnywhere Documentation](#introduction-runanywhere-documentation) - [transcribe() - RunAnywhere Documentation](#transcribe-runanywhere-documentation) - [Error Handling - RunAnywhere Documentation](#error-handling-runanywhere-documentation) - [chat() - RunAnywhere Documentation](#chat-runanywhere-documentation) - [generate() - RunAnywhere Documentation](#generate-runanywhere-documentation) - [Introduction - RunAnywhere Documentation](#introduction-runanywhere-documentation) - [Installation - RunAnywhere Documentation](#installation-runanywhere-documentation) - [Best Practices - RunAnywhere Documentation](#best-practices-runanywhere-documentation) - [Streaming TTS - RunAnywhere Documentation](#streaming-tts-runanywhere-documentation) - [SDK Overview - RunAnywhere Documentation](#sdk-overview-runanywhere-documentation) - [System Prompts - RunAnywhere Documentation](#system-prompts-runanywhere-documentation) - [Streaming STT - RunAnywhere Documentation](#streaming-stt-runanywhere-documentation) - [Voice Activity Detection - RunAnywhere Documentation](#voice-activity-detection-runanywhere-documentation) - [transcribe() - RunAnywhere Documentation](#transcribe-runanywhere-documentation) - [generateStream() - RunAnywhere Documentation](#generatestream-runanywhere-documentation) - [Voices - RunAnywhere Documentation](#voices-runanywhere-documentation) - [STT Options - RunAnywhere Documentation](#stt-options-runanywhere-documentation) - [Quick Start - RunAnywhere Documentation](#quick-start-runanywhere-documentation) - [Installation - RunAnywhere Documentation](#installation-runanywhere-documentation) - [Introduction - RunAnywhere Documentation](#introduction-runanywhere-documentation) - [synthesize() - RunAnywhere Documentation](#synthesize-runanywhere-documentation) - [Voice Agent - RunAnywhere Documentation](#voice-agent-runanywhere-documentation) - [chat() - RunAnywhere Documentation](#chat-runanywhere-documentation) - [Quick Start - RunAnywhere Documentation](#quick-start-runanywhere-documentation) - [Voice Agent - RunAnywhere Documentation](#voice-agent-runanywhere-documentation) - [Configuration - RunAnywhere Documentation](#configuration-runanywhere-documentation) - [chat() - RunAnywhere Documentation](#chat-runanywhere-documentation) - [System Prompts - RunAnywhere Documentation](#system-prompts-runanywhere-documentation) - [Quick Start - RunAnywhere Documentation](#quick-start-runanywhere-documentation) - [Best Practices - RunAnywhere Documentation](#best-practices-runanywhere-documentation) - [Error Handling - RunAnywhere Documentation](#error-handling-runanywhere-documentation) - [STT Options - RunAnywhere Documentation](#stt-options-runanywhere-documentation) - [Error Handling - RunAnywhere Documentation](#error-handling-runanywhere-documentation) - [Best Practices - RunAnywhere Documentation](#best-practices-runanywhere-documentation) - [generate() - RunAnywhere Documentation](#generate-runanywhere-documentation) - [generate() - RunAnywhere Documentation](#generate-runanywhere-documentation) - [Quick Start - RunAnywhere Documentation](#quick-start-runanywhere-documentation) - [System Prompts - RunAnywhere Documentation](#system-prompts-runanywhere-documentation) - [Voices - RunAnywhere Documentation](#voices-runanywhere-documentation) - [transcribe() - RunAnywhere Documentation](#transcribe-runanywhere-documentation) - [Voices - RunAnywhere Documentation](#voices-runanywhere-documentation) - [Voice Activity Detection - RunAnywhere Documentation](#voice-activity-detection-runanywhere-documentation) - [STT Options - RunAnywhere Documentation](#stt-options-runanywhere-documentation) - [Streaming STT - RunAnywhere Documentation](#streaming-stt-runanywhere-documentation) - [transcribe() - RunAnywhere Documentation](#transcribe-runanywhere-documentation) - [Streaming TTS - RunAnywhere Documentation](#streaming-tts-runanywhere-documentation) - [Configuration - RunAnywhere Documentation](#configuration-runanywhere-documentation) - [synthesize() - RunAnywhere Documentation](#synthesize-runanywhere-documentation) - [generateStream() - RunAnywhere Documentation](#generatestream-runanywhere-documentation) - [Streaming STT - RunAnywhere Documentation](#streaming-stt-runanywhere-documentation) - [synthesize() - RunAnywhere Documentation](#synthesize-runanywhere-documentation) - [generateStream() - RunAnywhere Documentation](#generatestream-runanywhere-documentation) - [Voice Activity Detection - RunAnywhere Documentation](#voice-activity-detection-runanywhere-documentation) - [Streaming TTS - RunAnywhere Documentation](#streaming-tts-runanywhere-documentation) - [Voice Agent - RunAnywhere Documentation](#voice-agent-runanywhere-documentation) - [Voice Agent - RunAnywhere Documentation](#voice-agent-runanywhere-documentation) --- # Welcome to RunAnywhere - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Getting Started Welcome to RunAnywhere On this page * [What is RunAnywhere?](https://docs.runanywhere.ai/#what-is-runanywhere) * [Core AI Capabilities](https://docs.runanywhere.ai/#core-ai-capabilities) * [Voice Agent Pipeline](https://docs.runanywhere.ai/#voice-agent-pipeline) * [Why RunAnywhere?](https://docs.runanywhere.ai/#why-runanywhere) * [Supported Platforms](https://docs.runanywhere.ai/#supported-platforms) * [Get Started](https://docs.runanywhere.ai/#get-started) ![RunAnywhere Documentation](https://mintcdn.com/runanywhere/PgeUY8BfGFmDDdg8/images/intro-light.jpg?w=2500&fit=max&auto=format&n=PgeUY8BfGFmDDdg8&q=85&s=3985d4e1665d9c39c1d5db2d3be9b312) ![RunAnywhere Documentation](https://mintcdn.com/runanywhere/PgeUY8BfGFmDDdg8/images/intro-dark.jpg?w=2500&fit=max&auto=format&n=PgeUY8BfGFmDDdg8&q=85&s=228e2b777a634dbf98510877eee10300) [​](https://docs.runanywhere.ai/#what-is-runanywhere) What is RunAnywhere? ----------------------------------------------------------------------------- **RunAnywhere** is a production-grade, on-device AI platform that enables developers to run AI models directly on mobile devices. Our SDKs provide a unified API for running AI inference locally — ensuring minimal latency, maximum privacy, and offline capability. All AI inference runs **100% on-device**. Once models are downloaded, no network connection is required for inference. [​](https://docs.runanywhere.ai/#core-ai-capabilities) Core AI Capabilities ------------------------------------------------------------------------------ Every RunAnywhere SDK provides access to these powerful AI features: [LLM (Large Language Model)\ --------------------------\ \ On-device text generation with streaming support, structured outputs, and system prompts](https://docs.runanywhere.ai/swift/llm/chat) [STT (Speech-to-Text)\ --------------------\ \ Real-time audio transcription with multiple backends and multi-language support](https://docs.runanywhere.ai/swift/stt/transcribe) [TTS (Text-to-Speech)\ --------------------\ \ Neural and system voice synthesis with customizable voice, pitch, rate, and volume](https://docs.runanywhere.ai/swift/tts/synthesize) [VAD (Voice Activity Detection)\ ------------------------------\ \ Real-time speech detection for hands-free interactions](https://docs.runanywhere.ai/swift/vad) ### [​](https://docs.runanywhere.ai/#voice-agent-pipeline) Voice Agent Pipeline Build complete voice-powered experiences with our integrated **Voice Agent** that orchestrates: This enables full voice conversation flows with streaming and batch processing modes. [​](https://docs.runanywhere.ai/#why-runanywhere) Why RunAnywhere? --------------------------------------------------------------------- Privacy by Design Audio and text data never leaves the device unless you explicitly configure it. Only anonymous analytics are collected by default. Your users’ data stays on their device. Low Latency On-device inference eliminates network round-trips. Get AI responses in milliseconds, not seconds. Perfect for real-time voice interactions and responsive UIs. Offline Capable Once models are downloaded, your app works completely offline. No internet required for inference. Ideal for apps used in areas with poor connectivity. Plugin Architecture Backend engines are optional modules—include only what you need. Keep your app binary size minimal by importing only the capabilities you use. [​](https://docs.runanywhere.ai/#supported-platforms) Supported Platforms ---------------------------------------------------------------------------- RunAnywhere provides native SDKs for all major mobile platforms: [![Swift](https://mintcdn.com/runanywhere/PgeUY8BfGFmDDdg8/images/code-languages/swift/swift_color.svg?w=2500&fit=max&auto=format&n=PgeUY8BfGFmDDdg8&q=85&s=71f71dff148590897979dba4207b8ca1)Swift SDK\ \ **iOS, macOS, tvOS, watchOS** Native Swift API with Metal acceleration for Apple Silicon](https://docs.runanywhere.ai/swift/introduction) [![Kotlin](https://mintcdn.com/runanywhere/PgeUY8BfGFmDDdg8/images/code-languages/kotlin/kotlin_color.svg?w=2500&fit=max&auto=format&n=PgeUY8BfGFmDDdg8&q=85&s=4121f6a5e21b7378aced8ffea82962c2)Kotlin SDK\ \ **Android** Native Kotlin API with GPU acceleration support](https://docs.runanywhere.ai/kotlin/introduction) [![React Native](https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svg)React Native\ \ **iOS + Android** TypeScript-first with full type safety for cross-platform apps](https://docs.runanywhere.ai/react-native/introduction) [![Flutter](https://mintcdn.com/runanywhere/PgeUY8BfGFmDDdg8/images/code-languages/flutter/flutter_color.svg?w=2500&fit=max&auto=format&n=PgeUY8BfGFmDDdg8&q=85&s=93c53557df38a96ececaa120569159e0)Flutter SDK\ \ **iOS + Android** Dart SDK for cross-platform Flutter applications](https://docs.runanywhere.ai/flutter/introduction) [​](https://docs.runanywhere.ai/#get-started) Get Started ------------------------------------------------------------ 1 [](https://docs.runanywhere.ai/#) Choose Your SDK Select the SDK that matches your tech stack from the options above 2 [](https://docs.runanywhere.ai/#) Install the SDK Follow the installation guide for your chosen platform 3 [](https://docs.runanywhere.ai/#) Initialize & Build Initialize the SDK and start building AI-powered features [Quick Start Guide\ -----------------\ \ Get up and running in 5 minutes](https://docs.runanywhere.ai/quickstart) [SDK Comparison\ --------------\ \ Compare features across all platforms](https://docs.runanywhere.ai/sdks) [Quick Start](https://docs.runanywhere.ai/quickstart) ⌘I --- # Best Practices - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/best-practices#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Flutter SDK Best Practices On this page * [Model Selection](https://docs.runanywhere.ai/flutter/best-practices#model-selection) * [Memory Management](https://docs.runanywhere.ai/flutter/best-practices#memory-management) * [Unload Unused Models](https://docs.runanywhere.ai/flutter/best-practices#unload-unused-models) * [Check Available Memory](https://docs.runanywhere.ai/flutter/best-practices#check-available-memory) * [Clean Up Old Models](https://docs.runanywhere.ai/flutter/best-practices#clean-up-old-models) * [Streaming for Better UX](https://docs.runanywhere.ai/flutter/best-practices#streaming-for-better-ux) * [Preload Models](https://docs.runanywhere.ai/flutter/best-practices#preload-models) * [Error Handling](https://docs.runanywhere.ai/flutter/best-practices#error-handling) * [Test on Physical Devices](https://docs.runanywhere.ai/flutter/best-practices#test-on-physical-devices) * [Download Management](https://docs.runanywhere.ai/flutter/best-practices#download-management) * [Show Progress](https://docs.runanywhere.ai/flutter/best-practices#show-progress) * [Download on WiFi](https://docs.runanywhere.ai/flutter/best-practices#download-on-wifi) * [Voice Assistant Tips](https://docs.runanywhere.ai/flutter/best-practices#voice-assistant-tips) * [Optimize Latency](https://docs.runanywhere.ai/flutter/best-practices#optimize-latency) * [Handle Background/Foreground](https://docs.runanywhere.ai/flutter/best-practices#handle-background%2Fforeground) * [Performance Monitoring](https://docs.runanywhere.ai/flutter/best-practices#performance-monitoring) * [Summary Checklist](https://docs.runanywhere.ai/flutter/best-practices#summary-checklist) * [See Also](https://docs.runanywhere.ai/flutter/best-practices#see-also) Follow these best practices to build high-quality AI-powered Flutter apps. **Reference Implementation:** The [Flutter Starter Example](https://github.com/RunanywhereAI/flutter-starter-example) demonstrates all these best practices in a production-ready app. [​](https://docs.runanywhere.ai/flutter/best-practices#model-selection) Model Selection ------------------------------------------------------------------------------------------ Choose the right model size for your use case: | Model Size | RAM Required | Use Case | Example | | --- | --- | --- | --- | | 360M–500M (Q8) | ~500MB | Fast chat, commands | SmolLM2-360M | | 1B–3B (Q4/Q6) | 1–2GB | Balanced quality/speed | Qwen2.5-1.5B | | 7B (Q4) | 4–5GB | High quality | Llama-3.2-7B | **Start small** — Use the smallest model that meets your quality needs. You can always upgrade later. [​](https://docs.runanywhere.ai/flutter/best-practices#memory-management) Memory Management ---------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/flutter/best-practices#unload-unused-models) Unload Unused Models Copy Ask AI // Unload when not in use await RunAnywhere.unloadModel(); await RunAnywhere.unloadSTTModel(); await RunAnywhere.unloadTTSVoice(); ### [​](https://docs.runanywhere.ai/flutter/best-practices#check-available-memory) Check Available Memory Copy Ask AI final storageInfo = await RunAnywhere.getStorageInfo(); final freeSpace = storageInfo.deviceStorage.freeSpace; // Ensure enough space before downloading final model = await RunAnywhere.availableModels() .then((m) => m.firstWhere((m) => m.id == 'my-model')); if (model.downloadSize != null && model.downloadSize! * 2 > freeSpace) { showError('Not enough storage. Need ${model.downloadSize! * 2} bytes.'); } ### [​](https://docs.runanywhere.ai/flutter/best-practices#clean-up-old-models) Clean Up Old Models Copy Ask AI // Delete unused models await RunAnywhere.deleteStoredModel('old-model-id'); // Get storage usage final models = await RunAnywhere.getDownloadedModelsWithInfo(); for (final model in models) { print('${model.id}: ${(model.size / 1024 / 1024).toStringAsFixed(1)} MB'); } [​](https://docs.runanywhere.ai/flutter/best-practices#streaming-for-better-ux) Streaming for Better UX ---------------------------------------------------------------------------------------------------------- Always prefer streaming for chat interfaces: Copy Ask AI // ✅ Good: Streaming shows progress final result = await RunAnywhere.generateStream(prompt); await for (final token in result.stream) { setState(() => _response += token); } // ❌ Avoid: User waits with no feedback final response = await RunAnywhere.generate(prompt); setState(() => _response = response.text); [​](https://docs.runanywhere.ai/flutter/best-practices#preload-models) Preload Models ---------------------------------------------------------------------------------------- Load models during idle time, not when user needs them: Copy Ask AI class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State { @override void initState() { super.initState(); _preloadModels(); // Load in background } Future _preloadModels() async { // Download if needed final models = await RunAnywhere.availableModels(); final llm = models.firstWhere((m) => m.id == 'smollm2-360m-q8_0'); if (!llm.isDownloaded) { await for (final p in RunAnywhere.downloadModel(llm.id)) { if (p.state.isCompleted) break; } } // Preload into memory await RunAnywhere.loadModel(llm.id); } } [​](https://docs.runanywhere.ai/flutter/best-practices#error-handling) Error Handling ---------------------------------------------------------------------------------------- Always handle errors gracefully: Copy Ask AI Future generateResponse(String prompt) async { try { final result = await RunAnywhere.generate(prompt); setState(() => _response = result.text); } on SDKError catch (e) { setState(() => _error = _getUserFriendlyMessage(e)); } catch (e) { setState(() => _error = 'Something went wrong. Please try again.'); } } String _getUserFriendlyMessage(SDKError error) { // Convert technical errors to user-friendly messages switch (error.code) { case SDKErrorCode.componentNotReady: return 'AI is loading. Please wait...'; case SDKErrorCode.generationFailed: return 'Could not generate response. Try again.'; default: return 'An error occurred.'; } } [​](https://docs.runanywhere.ai/flutter/best-practices#test-on-physical-devices) Test on Physical Devices ------------------------------------------------------------------------------------------------------------ **Always test on real devices** — Emulators are significantly slower for AI inference. Performance you see in emulators is not representative of real-world usage. * iOS Simulator: 5-10x slower than device * Android Emulator: 3-5x slower than device [​](https://docs.runanywhere.ai/flutter/best-practices#download-management) Download Management -------------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/flutter/best-practices#show-progress) Show Progress Copy Ask AI Widget _buildDownloadProgress(String modelId) { return StreamBuilder( stream: RunAnywhere.downloadModel(modelId), builder: (context, snapshot) { if (!snapshot.hasData) return CircularProgressIndicator(); final progress = snapshot.data!; return Column( children: [\ LinearProgressIndicator(value: progress.percentage),\ Text('${(progress.percentage * 100).toStringAsFixed(0)}%'),\ Text('${(progress.bytesDownloaded / 1024 / 1024).toStringAsFixed(1)} MB'),\ ], ); }, ); } ### [​](https://docs.runanywhere.ai/flutter/best-practices#download-on-wifi) Download on WiFi Copy Ask AI import 'package:connectivity_plus/connectivity_plus.dart'; Future shouldDownload() async { final connectivity = await Connectivity().checkConnectivity(); return connectivity == ConnectivityResult.wifi; } Future downloadWithCheck(String modelId) async { if (!await shouldDownload()) { final proceed = await showDialog( context: context, builder: (ctx) => AlertDialog( title: Text('Download on Cellular?'), content: Text('This model is large. Download on WiFi to save data.'), actions: [\ TextButton(onPressed: () => Navigator.pop(ctx, false), child: Text('Wait for WiFi')),\ TextButton(onPressed: () => Navigator.pop(ctx, true), child: Text('Download Now')),\ ], ), ); if (proceed != true) return; } await for (final p in RunAnywhere.downloadModel(modelId)) { if (p.state.isCompleted) break; } } [​](https://docs.runanywhere.ai/flutter/best-practices#voice-assistant-tips) Voice Assistant Tips ---------------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/flutter/best-practices#optimize-latency) Optimize Latency Copy Ask AI // Load all components during initialization await Future.wait([\ RunAnywhere.loadSTTModel('whisper-tiny-en'),\ RunAnywhere.loadModel('smollm2-360m-q8_0'),\ RunAnywhere.loadTTSVoice('piper-en-us-amy'),\ ]); ### [​](https://docs.runanywhere.ai/flutter/best-practices#handle-background/foreground) Handle Background/Foreground Copy Ask AI class VoiceApp extends StatefulWidget { @override _VoiceAppState createState() => _VoiceAppState(); } class _VoiceAppState extends State with WidgetsBindingObserver { VoiceSessionHandle? _session; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.paused) { _session?.stop(); // Stop when app goes to background } } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _session?.stop(); super.dispose(); } } [​](https://docs.runanywhere.ai/flutter/best-practices#performance-monitoring) Performance Monitoring -------------------------------------------------------------------------------------------------------- Track performance metrics: Copy Ask AI final result = await RunAnywhere.generate(prompt); // Log performance analytics.logEvent('generation', { 'tokens': result.tokensUsed, 'latency_ms': result.latencyMs, 'tokens_per_second': result.tokensPerSecond, 'model': result.modelUsed, }); [​](https://docs.runanywhere.ai/flutter/best-practices#summary-checklist) Summary Checklist ---------------------------------------------------------------------------------------------- Before Launch * [ ] Test on physical devices (iOS and Android) * [ ] Handle all error cases with user-friendly messages * [ ] Implement download progress UI * [ ] Add WiFi check for large downloads * [ ] Test with slow network conditions Performance * [ ] Use smallest adequate model size - \[ \] Preload models during idle time - \[ \] Use streaming for chat interfaces - \[ \] Unload unused models - \[ \] Monitor memory usage User Experience * [ ] Show loading states clearly * [ ] Provide cancel option for long operations * [ ] Handle background/foreground transitions * [ ] Save conversation history locally * [ ] Allow model selection for power users [​](https://docs.runanywhere.ai/flutter/best-practices#see-also) See Also ---------------------------------------------------------------------------- [Configuration\ -------------\ \ SDK configuration](https://docs.runanywhere.ai/flutter/configuration) [Error Handling\ --------------\ \ Handle errors gracefully](https://docs.runanywhere.ai/flutter/error-handling) [Error Handling](https://docs.runanywhere.ai/flutter/error-handling) [Expo Integration Guide](https://docs.runanywhere.ai/vibe-coding/expo-integration) ⌘I --- # Configuration - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/configuration#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Flutter SDK Configuration On this page * [SDK Initialization](https://docs.runanywhere.ai/flutter/configuration#sdk-initialization) * [Environment Modes](https://docs.runanywhere.ai/flutter/configuration#environment-modes) * [Development Mode (Default)](https://docs.runanywhere.ai/flutter/configuration#development-mode-default) * [Production Mode](https://docs.runanywhere.ai/flutter/configuration#production-mode) * [Check SDK State](https://docs.runanywhere.ai/flutter/configuration#check-sdk-state) * [Generation Options](https://docs.runanywhere.ai/flutter/configuration#generation-options) * [Generation Parameters](https://docs.runanywhere.ai/flutter/configuration#generation-parameters) * [Voice Session Configuration](https://docs.runanywhere.ai/flutter/configuration#voice-session-configuration) * [Model Registration](https://docs.runanywhere.ai/flutter/configuration#model-registration) * [LLM Models (GGUF)](https://docs.runanywhere.ai/flutter/configuration#llm-models-gguf) * [STT Models](https://docs.runanywhere.ai/flutter/configuration#stt-models) * [TTS Voices](https://docs.runanywhere.ai/flutter/configuration#tts-voices) * [Storage Management](https://docs.runanywhere.ai/flutter/configuration#storage-management) * [Reset SDK](https://docs.runanywhere.ai/flutter/configuration#reset-sdk) * [Environment Variables](https://docs.runanywhere.ai/flutter/configuration#environment-variables) * [See Also](https://docs.runanywhere.ai/flutter/configuration#see-also) Configure the RunAnywhere SDK for different environments and use cases. [​](https://docs.runanywhere.ai/flutter/configuration#sdk-initialization) SDK Initialization ----------------------------------------------------------------------------------------------- Copy Ask AI await RunAnywhere.initialize( apiKey: 'your-api-key', // Optional for development baseURL: 'https://api.runanywhere.ai', // Optional for development environment: SDKEnvironment.production, // development | staging | production ); [​](https://docs.runanywhere.ai/flutter/configuration#environment-modes) Environment Modes --------------------------------------------------------------------------------------------- | Environment | Description | API Key | Logging | Telemetry | | --- | --- | --- | --- | --- | | `.development` | Local development | Optional | Verbose | Disabled | | `.staging` | Testing with services | Required | Info | Enabled | | `.production` | Production deployment | Required | Minimal | Enabled | ### [​](https://docs.runanywhere.ai/flutter/configuration#development-mode-default) Development Mode (Default) Copy Ask AI // No API key needed - perfect for local development await RunAnywhere.initialize(); // Or explicitly set development mode await RunAnywhere.initialize( environment: SDKEnvironment.development, ); ### [​](https://docs.runanywhere.ai/flutter/configuration#production-mode) Production Mode Copy Ask AI await RunAnywhere.initialize( apiKey: 'your-production-api-key', baseURL: 'https://api.runanywhere.ai', environment: SDKEnvironment.production, ); [​](https://docs.runanywhere.ai/flutter/configuration#check-sdk-state) Check SDK State ----------------------------------------------------------------------------------------- Copy Ask AI // Version print('SDK Version: ${RunAnywhere.version}'); // Initialization state print('Initialized: ${RunAnywhere.isSDKInitialized}'); print('Active: ${RunAnywhere.isActive}'); print('Environment: ${RunAnywhere.environment}'); // Model states print('LLM loaded: ${RunAnywhere.isModelLoaded}'); print('Current model: ${RunAnywhere.currentModelId}'); print('STT loaded: ${RunAnywhere.isSTTModelLoaded}'); print('TTS loaded: ${RunAnywhere.isTTSVoiceLoaded}'); print('Voice Agent ready: ${RunAnywhere.isVoiceAgentReady}'); [​](https://docs.runanywhere.ai/flutter/configuration#generation-options) Generation Options ----------------------------------------------------------------------------------------------- Configure text generation behavior: Copy Ask AI final options = LLMGenerationOptions( maxTokens: 256, // Maximum tokens to generate temperature: 0.7, // Randomness (0.0–2.0) topP: 0.95, // Nucleus sampling stopSequences: ['END'], // Stop at these sequences systemPrompt: 'You are a helpful assistant.', ); final result = await RunAnywhere.generate(prompt, options: options); ### [​](https://docs.runanywhere.ai/flutter/configuration#generation-parameters) Generation Parameters | Parameter | Type | Default | Range | Description | | --- | --- | --- | --- | --- | | `maxTokens` | `int` | 100 | 1–4096 | Maximum output length | | `temperature` | `double` | 0.8 | 0.0–2.0 | Higher = more creative | | `topP` | `double` | 1.0 | 0.0–1.0 | Nucleus sampling | | `stopSequences` | `List` | `[]` | \- | Stop generation triggers | | `systemPrompt` | `String?` | `null` | \- | System context | [​](https://docs.runanywhere.ai/flutter/configuration#voice-session-configuration) Voice Session Configuration ----------------------------------------------------------------------------------------------------------------- Copy Ask AI final config = VoiceSessionConfig( silenceDuration: 1.5, // Seconds of silence before processing speechThreshold: 0.03, // Audio level for speech detection autoPlayTTS: true, // Auto-play synthesized audio continuousMode: true, // Resume listening after TTS ); final session = await RunAnywhere.startVoiceSession(config: config); [​](https://docs.runanywhere.ai/flutter/configuration#model-registration) Model Registration ----------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/flutter/configuration#llm-models-gguf) LLM Models (GGUF) Copy Ask AI LlamaCpp.addModel( id: 'my-llm-model', name: 'My LLM Model', url: 'https://huggingface.co/.../model.gguf', memoryRequirement: 500000000, // 500MB supportsThinking: false, // Chain-of-thought support ); ### [​](https://docs.runanywhere.ai/flutter/configuration#stt-models) STT Models Copy Ask AI Onnx.addModel( id: 'my-stt-model', name: 'My STT Model', url: 'https://example.com/stt-model.tar.gz', modality: ModelCategory.speechRecognition, memoryRequirement: 75000000, // 75MB ); ### [​](https://docs.runanywhere.ai/flutter/configuration#tts-voices) TTS Voices Copy Ask AI Onnx.addModel( id: 'my-tts-voice', name: 'My TTS Voice', url: 'https://example.com/tts-voice.tar.bz2', modality: ModelCategory.textToSpeech, memoryRequirement: 50000000, // 50MB ); [​](https://docs.runanywhere.ai/flutter/configuration#storage-management) Storage Management ----------------------------------------------------------------------------------------------- Copy Ask AI // Get storage information final storageInfo = await RunAnywhere.getStorageInfo(); print('Free space: ${storageInfo.deviceStorage.freeSpace} bytes'); // Get downloaded models with sizes final models = await RunAnywhere.getDownloadedModelsWithInfo(); for (final model in models) { print('${model.id}: ${model.size} bytes'); } // Delete a model await RunAnywhere.deleteStoredModel('old-model-id'); // Refresh model discovery await RunAnywhere.refreshDiscoveredModels(); [​](https://docs.runanywhere.ai/flutter/configuration#reset-sdk) Reset SDK ----------------------------------------------------------------------------- Copy Ask AI // Reset SDK state (for testing or reinitialization) RunAnywhere.reset(); [​](https://docs.runanywhere.ai/flutter/configuration#environment-variables) Environment Variables ----------------------------------------------------------------------------------------------------- For production apps, store sensitive configuration securely: Copy Ask AI import 'package:flutter_dotenv/flutter_dotenv.dart'; await dotenv.load(); await RunAnywhere.initialize( apiKey: dotenv.env['RUNANYWHERE_API_KEY'], baseURL: dotenv.env['RUNANYWHERE_BASE_URL'], environment: SDKEnvironment.production, ); [​](https://docs.runanywhere.ai/flutter/configuration#see-also) See Also --------------------------------------------------------------------------- [Error Handling\ --------------\ \ Handle SDK errors](https://docs.runanywhere.ai/flutter/error-handling) [Best Practices\ --------------\ \ Optimization tips](https://docs.runanywhere.ai/flutter/best-practices) [Voice Agent](https://docs.runanywhere.ai/flutter/voice-agent) [Error Handling](https://docs.runanywhere.ai/flutter/error-handling) ⌘I --- # Installation - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/installation#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Flutter SDK Installation On this page * [Packages on pub.dev](https://docs.runanywhere.ai/flutter/installation#packages-on-pub-dev) * [Add Dependencies](https://docs.runanywhere.ai/flutter/installation#add-dependencies) * [iOS Setup (Required)](https://docs.runanywhere.ai/flutter/installation#ios-setup-required) * [1\. Update Podfile](https://docs.runanywhere.ai/flutter/installation#1-update-podfile) * [2\. Add Microphone Permission](https://docs.runanywhere.ai/flutter/installation#2-add-microphone-permission) * [3\. Install Pods](https://docs.runanywhere.ai/flutter/installation#3-install-pods) * [Android Setup](https://docs.runanywhere.ai/flutter/installation#android-setup) * [Verify Installation](https://docs.runanywhere.ai/flutter/installation#verify-installation) * [Starter Example](https://docs.runanywhere.ai/flutter/installation#starter-example) * [Next Steps](https://docs.runanywhere.ai/flutter/installation#next-steps) [​](https://docs.runanywhere.ai/flutter/installation#packages-on-pub-dev) Packages on pub.dev ------------------------------------------------------------------------------------------------ The RunAnywhere Flutter SDK consists of three packages: | Package | Description | pub.dev | | --- | --- | --- | | [`runanywhere`](https://pub.dev/packages/runanywhere) | Core SDK with APIs and infrastructure | [![pub package](https://img.shields.io/pub/v/runanywhere.svg)](https://pub.dev/packages/runanywhere) | | [`runanywhere_llamacpp`](https://pub.dev/packages/runanywhere_llamacpp) | LLM text generation (GGUF models) | [![pub package](https://img.shields.io/pub/v/runanywhere_llamacpp.svg)](https://pub.dev/packages/runanywhere_llamacpp) | | [`runanywhere_onnx`](https://pub.dev/packages/runanywhere_onnx) | STT, TTS, VAD (ONNX models) | [![pub package](https://img.shields.io/pub/v/runanywhere_onnx.svg)](https://pub.dev/packages/runanywhere_onnx) | [​](https://docs.runanywhere.ai/flutter/installation#add-dependencies) Add Dependencies ------------------------------------------------------------------------------------------ Add the packages you need to your `pubspec.yaml`: * LLM Only * STT/TTS Only * All Features Add these dependencies to `pubspec.yaml`: Copy Ask AI dependencies: runanywhere: ^0.15.11 runanywhere_llamacpp: ^0.15.11 Add these dependencies to `pubspec.yaml`: Copy Ask AI dependencies: runanywhere: ^0.15.11 runanywhere_onnx: ^0.15.11 Add these dependencies to `pubspec.yaml`: Copy Ask AI dependencies: runanywhere: ^0.15.11 runanywhere_llamacpp: ^0.15.11 runanywhere_onnx: ^0.15.11 Then run: Copy Ask AI flutter pub get [​](https://docs.runanywhere.ai/flutter/installation#ios-setup-required) iOS Setup (Required) ------------------------------------------------------------------------------------------------ After adding the packages, update your iOS configuration: ### [​](https://docs.runanywhere.ai/flutter/installation#1-update-podfile) 1\. Update Podfile Open `ios/Podfile` and update: ios/Podfile Copy Ask AI # Set minimum iOS version to 14.0 platform :ios, '14.0' target 'Runner' do # REQUIRED: Add static linkage use_frameworks! :linkage => :static flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) target.build_configurations.each do |config| config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '14.0' # Required for microphone permission (STT/Voice features) config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [\ '$(inherited)',\ 'PERMISSION_MICROPHONE=1',\ ] end end end Without `use_frameworks! :linkage => :static`, you will encounter “symbol not found” errors at runtime. ### [​](https://docs.runanywhere.ai/flutter/installation#2-add-microphone-permission) 2\. Add Microphone Permission Add to `ios/Runner/Info.plist` (for STT/Voice features): ios/Runner/Info.plist Copy Ask AI NSMicrophoneUsageDescription This app needs microphone access for speech recognition ### [​](https://docs.runanywhere.ai/flutter/installation#3-install-pods) 3\. Install Pods Copy Ask AI cd ios && pod install && cd .. [​](https://docs.runanywhere.ai/flutter/installation#android-setup) Android Setup ------------------------------------------------------------------------------------ Add microphone permission to `android/app/src/main/AndroidManifest.xml`: android/app/src/main/AndroidManifest.xml Copy Ask AI [​](https://docs.runanywhere.ai/flutter/installation#verify-installation) Verify Installation ------------------------------------------------------------------------------------------------ Run your app to verify everything is set up correctly: Copy Ask AI flutter run [​](https://docs.runanywhere.ai/flutter/installation#starter-example) Starter Example ---------------------------------------------------------------------------------------- Want to see a complete working example? Check out our official Flutter starter app:[Flutter Starter Example\ -----------------------\ \ Clone and run a complete example app with LLM, STT, TTS, and Voice Agent](https://github.com/RunanywhereAI/flutter-starter-example) Copy Ask AI git clone https://github.com/RunanywhereAI/flutter-starter-example.git cd flutter-starter-example flutter pub get flutter run [​](https://docs.runanywhere.ai/flutter/installation#next-steps) Next Steps ------------------------------------------------------------------------------ [Quick Start\ -----------\ \ Build your first AI feature →](https://docs.runanywhere.ai/flutter/quick-start) [Introduction](https://docs.runanywhere.ai/flutter/introduction) [Quick Start](https://docs.runanywhere.ai/flutter/quick-start) ⌘I --- # Introduction - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/introduction#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Flutter SDK Introduction On this page * [Overview](https://docs.runanywhere.ai/flutter/introduction#overview) * [Key Capabilities](https://docs.runanywhere.ai/flutter/introduction#key-capabilities) * [Core Philosophy](https://docs.runanywhere.ai/flutter/introduction#core-philosophy) * [Features](https://docs.runanywhere.ai/flutter/introduction#features) * [Language Models (LLM)](https://docs.runanywhere.ai/flutter/introduction#language-models-llm) * [Speech-to-Text (STT)](https://docs.runanywhere.ai/flutter/introduction#speech-to-text-stt) * [Text-to-Speech (TTS)](https://docs.runanywhere.ai/flutter/introduction#text-to-speech-tts) * [Voice Activity Detection (VAD)](https://docs.runanywhere.ai/flutter/introduction#voice-activity-detection-vad) * [Voice Agent Pipeline](https://docs.runanywhere.ai/flutter/introduction#voice-agent-pipeline) * [System Requirements](https://docs.runanywhere.ai/flutter/introduction#system-requirements) * [Package Composition](https://docs.runanywhere.ai/flutter/introduction#package-composition) * [Architecture](https://docs.runanywhere.ai/flutter/introduction#architecture) * [Starter Example](https://docs.runanywhere.ai/flutter/introduction#starter-example) * [Next Steps](https://docs.runanywhere.ai/flutter/introduction#next-steps) [​](https://docs.runanywhere.ai/flutter/introduction#overview) Overview -------------------------------------------------------------------------- The **RunAnywhere Flutter SDK** is a production-grade, on-device AI SDK for Flutter applications. It enables developers to run AI models directly on iOS and Android devices without requiring network connectivity for inference, ensuring minimal latency and maximum privacy for your users. The SDK provides a unified interface to multiple AI capabilities: [LLM\ ---\ \ Text generation with streaming support via Dart Streams](https://docs.runanywhere.ai/flutter/llm/chat) [STT\ ---\ \ Speech-to-text transcription with Whisper models](https://docs.runanywhere.ai/flutter/stt/transcribe) [TTS\ ---\ \ Neural voice synthesis with Piper TTS](https://docs.runanywhere.ai/flutter/tts/synthesize) [VAD\ ---\ \ Real-time voice activity detection with Silero VAD](https://docs.runanywhere.ai/flutter/vad) [​](https://docs.runanywhere.ai/flutter/introduction#key-capabilities) Key Capabilities ------------------------------------------------------------------------------------------ * **Multi-backend architecture** – Choose from LlamaCPP (GGUF models) or ONNX Runtime * **Cross-platform** – Single codebase for iOS and Android * **Dart-native** – Built with async/await and Streams for reactive programming * **Production-ready** – Built-in analytics, logging, and model lifecycle management [​](https://docs.runanywhere.ai/flutter/introduction#core-philosophy) Core Philosophy ---------------------------------------------------------------------------------------- On-Device First All AI inference runs locally, ensuring low latency and data privacy. Once models are downloaded, no network connection is required for inference. Modular Backends Backend engines are separate packages—include only what you need. This keeps your app bundle size minimal. Privacy by Design Audio and text data never leaves the device unless explicitly configured. Only anonymous analytics are collected by default. Event-Driven Subscribe to SDK events for reactive UI updates and observability. [​](https://docs.runanywhere.ai/flutter/introduction#features) Features -------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/flutter/introduction#language-models-llm) Language Models (LLM) * On-device text generation with streaming support * Dart Stream-based token streaming * System prompts and customizable generation parameters * Support for thinking/reasoning models * LlamaCPP backend for GGUF models ### [​](https://docs.runanywhere.ai/flutter/introduction#speech-to-text-stt) Speech-to-Text (STT) * Real-time streaming transcription * Batch audio transcription * Multi-language support * Whisper-based models via ONNX Runtime ### [​](https://docs.runanywhere.ai/flutter/introduction#text-to-speech-tts) Text-to-Speech (TTS) * Neural voice synthesis with Piper TTS * System voices via platform TTS * Streaming audio generation for long text * Customizable voice, pitch, rate, and volume ### [​](https://docs.runanywhere.ai/flutter/introduction#voice-activity-detection-vad) Voice Activity Detection (VAD) * Energy-based speech detection with Silero VAD * Configurable sensitivity thresholds * Real-time audio stream processing ### [​](https://docs.runanywhere.ai/flutter/introduction#voice-agent-pipeline) Voice Agent Pipeline * Full VAD → STT → LLM → TTS orchestration * Complete voice conversation flow * Push-to-talk and hands-free modes [​](https://docs.runanywhere.ai/flutter/introduction#system-requirements) System Requirements ------------------------------------------------------------------------------------------------ | Platform | Minimum Version | | --- | --- | | Flutter | 3.10.0+ | | Dart | 3.0.0+ | | iOS | 14.0+ | | Android | API 24 (7.0+) | ARM64 devices are recommended for best performance. Metal GPU acceleration on iOS and NEON SIMD on Android provide significant speedups over CPU-only inference. [​](https://docs.runanywhere.ai/flutter/introduction#package-composition) Package Composition ------------------------------------------------------------------------------------------------ | Package | Size | Purpose | | --- | --- | --- | | `runanywhere` | ~5MB | Core SDK (required) | | `runanywhere_llamacpp` | ~15-25MB | LLM text generation with GGUF models | | `runanywhere_onnx` | ~50-70MB | STT/TTS/VAD via ONNX Runtime | [​](https://docs.runanywhere.ai/flutter/introduction#architecture) Architecture ---------------------------------------------------------------------------------- [​](https://docs.runanywhere.ai/flutter/introduction#starter-example) Starter Example ---------------------------------------------------------------------------------------- [Flutter Starter Example\ -----------------------\ \ Complete working example with LLM chat, STT, TTS, and Voice Agent demos](https://github.com/RunanywhereAI/flutter-starter-example) [​](https://docs.runanywhere.ai/flutter/introduction#next-steps) Next Steps ------------------------------------------------------------------------------ [Installation\ ------------\ \ Add the SDK packages via pub.dev](https://docs.runanywhere.ai/flutter/installation) [Quick Start\ -----------\ \ Build your first AI feature in minutes](https://docs.runanywhere.ai/flutter/quick-start) [Best Practices](https://docs.runanywhere.ai/react-native/best-practices) [Installation](https://docs.runanywhere.ai/flutter/installation) ⌘I --- # chat() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/llm/chat#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation LLM (Language Models) chat() On this page * [When to Use](https://docs.runanywhere.ai/flutter/llm/chat#when-to-use) * [Requirements](https://docs.runanywhere.ai/flutter/llm/chat#requirements) * [Example with Error Handling](https://docs.runanywhere.ai/flutter/llm/chat#example-with-error-handling) * [See Also](https://docs.runanywhere.ai/flutter/llm/chat#see-also) The simplest way to generate text—returns just the response string. Copy Ask AI // One-liner for quick responses final response = await RunAnywhere.chat('What is the capital of France?'); print(response); // "The capital of France is Paris." [​](https://docs.runanywhere.ai/flutter/llm/chat#when-to-use) When to Use ---------------------------------------------------------------------------- Use `chat()` when you: * Need a quick response without metrics * Don’t need streaming * Want the simplest possible API [​](https://docs.runanywhere.ai/flutter/llm/chat#requirements) Requirements ------------------------------------------------------------------------------ Before calling `chat()`, ensure: 1. SDK is initialized: `await RunAnywhere.initialize()` 2. Backend is registered: `await LlamaCpp.register()` 3. Model is loaded: `await RunAnywhere.loadModel('model-id')` [​](https://docs.runanywhere.ai/flutter/llm/chat#example-with-error-handling) Example with Error Handling ------------------------------------------------------------------------------------------------------------ Copy Ask AI Future askQuestion(String question) async { try { if (!RunAnywhere.isModelLoaded) { throw SDKError.componentNotReady('No model loaded'); } return await RunAnywhere.chat(question); } on SDKError catch (e) { return 'Error: ${e.message}'; } } [​](https://docs.runanywhere.ai/flutter/llm/chat#see-also) See Also ---------------------------------------------------------------------- [generate()\ ----------\ \ Get response with metrics](https://docs.runanywhere.ai/flutter/llm/generate) [generateStream()\ ----------------\ \ Stream tokens in real-time](https://docs.runanywhere.ai/flutter/llm/stream) [Quick Start](https://docs.runanywhere.ai/flutter/quick-start) [generate()](https://docs.runanywhere.ai/flutter/llm/generate) ⌘I --- # Streaming TTS - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/tts/stream#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation TTS (Text-to-Speech) Streaming TTS On this page * [Overview](https://docs.runanywhere.ai/flutter/tts/stream#overview) * [Basic Concept](https://docs.runanywhere.ai/flutter/tts/stream#basic-concept) * [Chunked Synthesis](https://docs.runanywhere.ai/flutter/tts/stream#chunked-synthesis) * [With Voice Agent Pipeline](https://docs.runanywhere.ai/flutter/tts/stream#with-voice-agent-pipeline) * [Latency Optimization Tips](https://docs.runanywhere.ai/flutter/tts/stream#latency-optimization-tips) * [See Also](https://docs.runanywhere.ai/flutter/tts/stream#see-also) Stream TTS audio as it’s generated for faster time-to-first-audio, especially with longer text. [​](https://docs.runanywhere.ai/flutter/tts/stream#overview) Overview ------------------------------------------------------------------------ Streaming TTS starts playing audio before the entire synthesis is complete. This is particularly useful for: * Long text passages * Voice assistants responding in real-time * Reducing perceived latency [​](https://docs.runanywhere.ai/flutter/tts/stream#basic-concept) Basic Concept ---------------------------------------------------------------------------------- Copy Ask AI // The Voice Agent pipeline handles streaming TTS automatically final session = await RunAnywhere.startVoiceSession( config: VoiceSessionConfig( autoPlayTTS: true, // Automatically plays synthesized audio ), ); session.events.listen((event) { if (event is VoiceSessionSpeaking) { print('Playing audio response...'); } }); [​](https://docs.runanywhere.ai/flutter/tts/stream#chunked-synthesis) Chunked Synthesis ------------------------------------------------------------------------------------------ For manual control, synthesize text in chunks: Copy Ask AI Future speakInChunks(String longText) async { // Split into sentences final sentences = longText.split(RegExp(r'(?<=[.!?])\s+')); for (final sentence in sentences) { final result = await RunAnywhere.synthesize(sentence); await playAudio(result); } } [​](https://docs.runanywhere.ai/flutter/tts/stream#with-voice-agent-pipeline) With Voice Agent Pipeline ---------------------------------------------------------------------------------------------------------- The Voice Agent provides the best streaming TTS experience: Copy Ask AI // Initialize all components await RunAnywhere.loadSTTModel('sherpa-onnx-whisper-tiny.en'); await RunAnywhere.loadModel('smollm2-360m-q8_0'); await RunAnywhere.loadTTSVoice('vits-piper-en_US-lessac-medium'); // Start session with auto-play final session = await RunAnywhere.startVoiceSession( config: VoiceSessionConfig( autoPlayTTS: true, continuousMode: true, ), ); // The pipeline automatically: // 1. Detects speech (VAD) // 2. Transcribes audio (STT) // 3. Generates response (LLM) // 4. Synthesizes and plays audio (TTS) session.events.listen((event) { switch (event) { case VoiceSessionTranscribed(:final text): print('User: $text'); case VoiceSessionResponded(:final text): print('AI: $text'); case VoiceSessionSpeaking(): print('Playing response...'); case VoiceSessionTurnCompleted(): print('Ready for next turn'); } }); [​](https://docs.runanywhere.ai/flutter/tts/stream#latency-optimization-tips) Latency Optimization Tips ---------------------------------------------------------------------------------------------------------- Preload Voice Model Load the TTS voice during app startup or idle time, not when the user first needs it. Copy Ask AI // In app initialization await RunAnywhere.loadTTSVoice('vits-piper-en_US-lessac-medium'); Use Faster Voices Smaller voice models synthesize faster. Choose based on your quality/speed tradeoff. Sentence-Level Streaming For very long responses, synthesize and play sentence by sentence rather than waiting for the complete response. Buffer Management Start playback as soon as you have enough audio buffered (typically 100-200ms). [​](https://docs.runanywhere.ai/flutter/tts/stream#see-also) See Also ------------------------------------------------------------------------ [synthesize()\ ------------\ \ Basic synthesis](https://docs.runanywhere.ai/flutter/tts/synthesize) [Voice Agent\ -----------\ \ Complete voice pipeline](https://docs.runanywhere.ai/flutter/voice-agent) [synthesize()](https://docs.runanywhere.ai/flutter/tts/synthesize) [Voices](https://docs.runanywhere.ai/flutter/tts/voices) ⌘I --- # generate() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/llm/generate#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation LLM (Language Models) generate() On this page * [LLMGenerationOptions](https://docs.runanywhere.ai/flutter/llm/generate#llmgenerationoptions) * [LLMGenerationResult](https://docs.runanywhere.ai/flutter/llm/generate#llmgenerationresult) * [Thinking Models](https://docs.runanywhere.ai/flutter/llm/generate#thinking-models) * [See Also](https://docs.runanywhere.ai/flutter/llm/generate#see-also) Generate text with detailed metrics including latency, token count, and generation speed. Copy Ask AI final result = await RunAnywhere.generate( 'Explain quantum computing in simple terms', options: LLMGenerationOptions( maxTokens: 200, temperature: 0.7, ), ); print('Response: ${result.text}'); print('Tokens: ${result.tokensUsed}'); print('Speed: ${result.tokensPerSecond.toStringAsFixed(1)} tok/s'); print('Latency: ${result.latencyMs.toStringAsFixed(0)}ms'); [​](https://docs.runanywhere.ai/flutter/llm/generate#llmgenerationoptions) LLMGenerationOptions -------------------------------------------------------------------------------------------------- | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `maxTokens` | `int` | 100 | Maximum tokens to generate | | `temperature` | `double` | 0.8 | Randomness (0.0–2.0) | | `topP` | `double` | 1.0 | Nucleus sampling parameter | | `stopSequences` | `List` | `[]` | Stop generation at these | | `systemPrompt` | `String?` | `null` | System prompt for context | Copy Ask AI const options = LLMGenerationOptions( maxTokens: 256, temperature: 0.7, topP: 0.95, stopSequences: ['END', '###'], systemPrompt: 'You are a helpful coding assistant.', ); [​](https://docs.runanywhere.ai/flutter/llm/generate#llmgenerationresult) LLMGenerationResult ------------------------------------------------------------------------------------------------ | Property | Type | Description | | --- | --- | --- | | `text` | `String` | Generated text | | `thinkingContent` | `String?` | Thinking content (if supported) | | `inputTokens` | `int` | Number of input tokens | | `tokensUsed` | `int` | Number of output tokens | | `modelUsed` | `String` | Model ID used | | `latencyMs` | `double` | Total latency in milliseconds | | `tokensPerSecond` | `double` | Generation speed | | `timeToFirstTokenMs` | `double?` | Time to first token | [​](https://docs.runanywhere.ai/flutter/llm/generate#thinking-models) Thinking Models ---------------------------------------------------------------------------------------- Some models support “thinking” tokens for chain-of-thought reasoning: Copy Ask AI LlamaCpp.addModel( id: 'qwen-cot', name: 'Qwen CoT', url: '...', supportsThinking: true, // Enable thinking token parsing ); final result = await RunAnywhere.generate('Solve: 2x + 5 = 15'); if (result.thinkingContent != null) { print('Reasoning: ${result.thinkingContent}'); } print('Answer: ${result.text}'); [​](https://docs.runanywhere.ai/flutter/llm/generate#see-also) See Also -------------------------------------------------------------------------- [chat()\ ------\ \ Simple one-liner](https://docs.runanywhere.ai/flutter/llm/chat) [generateStream()\ ----------------\ \ Stream tokens in real-time](https://docs.runanywhere.ai/flutter/llm/stream) [chat()](https://docs.runanywhere.ai/flutter/llm/chat) [generateStream()](https://docs.runanywhere.ai/flutter/llm/stream) ⌘I --- # Streaming STT - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/stt/stream#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation STT (Speech-to-Text) Streaming STT On this page * [Overview](https://docs.runanywhere.ai/flutter/stt/stream#overview) * [Basic Usage](https://docs.runanywhere.ai/flutter/stt/stream#basic-usage) * [With Voice Session](https://docs.runanywhere.ai/flutter/stt/stream#with-voice-session) * [Real-Time Transcription Widget](https://docs.runanywhere.ai/flutter/stt/stream#real-time-transcription-widget) * [Tips for Streaming STT](https://docs.runanywhere.ai/flutter/stt/stream#tips-for-streaming-stt) * [See Also](https://docs.runanywhere.ai/flutter/stt/stream#see-also) Stream audio for real-time transcription as the user speaks. Ideal for voice assistants and live captioning. [​](https://docs.runanywhere.ai/flutter/stt/stream#overview) Overview ------------------------------------------------------------------------ Streaming STT processes audio in chunks, providing partial transcriptions that update as more audio arrives. This creates a responsive experience where users see their words appear in real-time. [​](https://docs.runanywhere.ai/flutter/stt/stream#basic-usage) Basic Usage ------------------------------------------------------------------------------ Copy Ask AI // Ensure STT model is loaded await RunAnywhere.loadSTTModel('sherpa-onnx-whisper-tiny.en'); // Create audio stream from microphone final audioStream = microphoneManager.audioStream; // Process audio chunks await for (final audioChunk in audioStream) { // Feed audio to STT (returns partial transcription) final partial = await RunAnywhere.transcribeChunk(audioChunk); print('Partial: $partial'); } [​](https://docs.runanywhere.ai/flutter/stt/stream#with-voice-session) With Voice Session -------------------------------------------------------------------------------------------- The easiest way to use streaming STT is through the Voice Agent, which handles VAD and audio capture automatically: Copy Ask AI final session = await RunAnywhere.startVoiceSession(); session.events.listen((event) { if (event is VoiceSessionTranscribed) { print('Transcription: ${event.text}'); } }); See [Voice Agent](https://docs.runanywhere.ai/flutter/voice-agent) for the complete voice pipeline. [​](https://docs.runanywhere.ai/flutter/stt/stream#real-time-transcription-widget) Real-Time Transcription Widget -------------------------------------------------------------------------------------------------------------------- Copy Ask AI class LiveTranscriptionWidget extends StatefulWidget { @override _LiveTranscriptionWidgetState createState() => _LiveTranscriptionWidgetState(); } class _LiveTranscriptionWidgetState extends State { final _recorder = AudioRecorder(); String _partialText = ''; String _finalText = ''; bool _isListening = false; StreamSubscription? _audioSubscription; Future _startListening() async { if (!await _recorder.hasPermission()) return; setState(() { _isListening = true; _partialText = ''; }); // Start recording with streaming final stream = await _recorder.startStream( const RecordConfig( encoder: AudioEncoder.pcm16bits, sampleRate: 16000, numChannels: 1, ), ); // Process audio chunks _audioSubscription = stream.listen((chunk) async { // This would use your streaming transcription implementation // The exact API depends on how you've set up streaming }); } Future _stopListening() async { await _audioSubscription?.cancel(); await _recorder.stop(); setState(() { _isListening = false; _finalText = _partialText; _partialText = ''; }); } @override Widget build(BuildContext context) { return Column( children: [\ // Show partial transcription with typing indicator\ Container(\ padding: EdgeInsets.all(16),\ child: Text(\ _isListening ? '$_partialText|' : _finalText,\ style: TextStyle(\ fontSize: 18,\ color: _isListening ? Colors.grey : Colors.black,\ ),\ ),\ ),\ \ // Recording button\ IconButton(\ icon: Icon(_isListening ? Icons.stop : Icons.mic),\ iconSize: 48,\ color: _isListening ? Colors.red : Colors.blue,\ onPressed: _isListening ? _stopListening : _startListening,\ ),\ ], ); } @override void dispose() { _audioSubscription?.cancel(); _recorder.dispose(); super.dispose(); } } [​](https://docs.runanywhere.ai/flutter/stt/stream#tips-for-streaming-stt) Tips for Streaming STT ---------------------------------------------------------------------------------------------------- Buffer Management Accumulate audio in buffers of 100-500ms for optimal accuracy vs latency tradeoff. Silence Detection Use VAD (Voice Activity Detection) to detect end of speech and finalize transcriptions. Error Recovery Handle network interruptions and audio glitches gracefully. Consider retrying failed chunks. UI Feedback Show a visual indicator (waveform, pulsing dot) to confirm audio is being captured. [​](https://docs.runanywhere.ai/flutter/stt/stream#see-also) See Also ------------------------------------------------------------------------ [transcribe()\ ------------\ \ Batch transcription](https://docs.runanywhere.ai/flutter/stt/transcribe) [Voice Agent\ -----------\ \ Complete voice pipeline](https://docs.runanywhere.ai/flutter/voice-agent) [transcribe()](https://docs.runanywhere.ai/flutter/stt/transcribe) [STT Options](https://docs.runanywhere.ai/flutter/stt/options) ⌘I --- # Configuration - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/configuration#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Kotlin SDK Configuration On this page * [SDK Initialization](https://docs.runanywhere.ai/kotlin/configuration#sdk-initialization) * [SDKEnvironment](https://docs.runanywhere.ai/kotlin/configuration#sdkenvironment) * [LLM Generation Options](https://docs.runanywhere.ai/kotlin/configuration#llm-generation-options) * [Temperature Guide](https://docs.runanywhere.ai/kotlin/configuration#temperature-guide) * [STT Options](https://docs.runanywhere.ai/kotlin/configuration#stt-options) * [TTS Options](https://docs.runanywhere.ai/kotlin/configuration#tts-options) * [VAD Configuration](https://docs.runanywhere.ai/kotlin/configuration#vad-configuration) * [Memory Considerations](https://docs.runanywhere.ai/kotlin/configuration#memory-considerations) * [Model Registry](https://docs.runanywhere.ai/kotlin/configuration#model-registry) * [InferenceFramework](https://docs.runanywhere.ai/kotlin/configuration#inferenceframework) * [ModelCategory](https://docs.runanywhere.ai/kotlin/configuration#modelcategory) * [SDK Lifecycle](https://docs.runanywhere.ai/kotlin/configuration#sdk-lifecycle) [​](https://docs.runanywhere.ai/kotlin/configuration#sdk-initialization) SDK Initialization ---------------------------------------------------------------------------------------------- Copy Ask AI RunAnywhere.initialize( apiKey = "your-api-key", // Optional for development baseURL = "https://api.runanywhere.ai", // Custom API endpoint environment = SDKEnvironment.DEVELOPMENT ) [​](https://docs.runanywhere.ai/kotlin/configuration#sdkenvironment) SDKEnvironment -------------------------------------------------------------------------------------- | Environment | Log Level | Description | | --- | --- | --- | | `DEVELOPMENT` | Debug | Full logging, local testing | | `STAGING` | Info | Staging backend, moderate logging | | `PRODUCTION` | Warning | Production backend, minimal logging | [​](https://docs.runanywhere.ai/kotlin/configuration#llm-generation-options) LLM Generation Options ------------------------------------------------------------------------------------------------------ Copy Ask AI data class LLMGenerationOptions( val maxTokens: Int = 100, // Maximum tokens to generate val temperature: Float = 0.8f, // Creativity (0.0-2.0) val topP: Float = 1.0f, // Nucleus sampling (0.0-1.0) val stopSequences: List = emptyList(), val streamingEnabled: Boolean = false, val preferredFramework: InferenceFramework? = null, val systemPrompt: String? = null ) ### [​](https://docs.runanywhere.ai/kotlin/configuration#temperature-guide) Temperature Guide | Value | Use Case | Description | | --- | --- | --- | | 0.0-0.3 | Code, facts | Deterministic, consistent | | 0.4-0.7 | General Q&A | Balanced | | 0.8-1.0 | Creative writing | More variety | | 1.1-2.0 | Brainstorming | High creativity | [​](https://docs.runanywhere.ai/kotlin/configuration#stt-options) STT Options -------------------------------------------------------------------------------- Copy Ask AI data class STTOptions( val language: String = "en", val detectLanguage: Boolean = false, val enablePunctuation: Boolean = true, val enableDiarization: Boolean = false, val maxSpeakers: Int? = null, val enableTimestamps: Boolean = true, val vocabularyFilter: List = emptyList(), val audioFormat: AudioFormat = AudioFormat.PCM, val sampleRate: Int = 16000 ) [​](https://docs.runanywhere.ai/kotlin/configuration#tts-options) TTS Options -------------------------------------------------------------------------------- Copy Ask AI data class TTSOptions( val voice: String? = null, val language: String = "en-US", val rate: Float = 1.0f, // 0.0-2.0 val pitch: Float = 1.0f, // 0.0-2.0 val volume: Float = 1.0f, // 0.0-1.0 val audioFormat: AudioFormat = AudioFormat.PCM, val sampleRate: Int = 22050, val useSSML: Boolean = false ) [​](https://docs.runanywhere.ai/kotlin/configuration#vad-configuration) VAD Configuration -------------------------------------------------------------------------------------------- Copy Ask AI data class VADConfiguration( val threshold: Float = 0.5f, val minSpeechDurationMs: Int = 250, val minSilenceDurationMs: Int = 300, val sampleRate: Int = 16000, val frameSizeMs: Int = 30 ) [​](https://docs.runanywhere.ai/kotlin/configuration#memory-considerations) Memory Considerations ---------------------------------------------------------------------------------------------------- Model memory requirements vary by size and quantization: | Model Type | Memory | Device Requirements | | --- | --- | --- | | LLM 0.5B Q8 | ~500MB | Any Android 7.0+ | | LLM 0.5B Q4 | ~300MB | Any Android 7.0+ | | LLM 1B Q4 | ~600MB | 4GB+ RAM | | LLM 3B Q4 | ~2GB | 6GB+ RAM | | Whisper Tiny | ~75MB | Any device | | Whisper Base | ~150MB | Any device | | TTS Voice | ~50MB | Any device | Always check available memory before loading large models. Loading models that exceed available RAM will crash the app. [​](https://docs.runanywhere.ai/kotlin/configuration#model-registry) Model Registry -------------------------------------------------------------------------------------- Register custom models: Copy Ask AI val modelInfo = RunAnywhere.registerModel( id = "my-custom-model", // Optional, generated from URL if null name = "My Custom Model", url = "https://...", framework = InferenceFramework.LLAMA_CPP, modality = ModelCategory.LANGUAGE, memoryRequirement = 500_000_000L, // 500MB supportsThinking = false ) [​](https://docs.runanywhere.ai/kotlin/configuration#inferenceframework) InferenceFramework ---------------------------------------------------------------------------------------------- Copy Ask AI enum class InferenceFramework { ONNX, // ONNX Runtime (STT/TTS/VAD) LLAMA_CPP, // llama.cpp (LLM) FOUNDATION_MODELS, // Platform foundation models SYSTEM_TTS, // System text-to-speech BUILT_IN, // Simple built-in services NONE, // No model needed UNKNOWN } [​](https://docs.runanywhere.ai/kotlin/configuration#modelcategory) ModelCategory ------------------------------------------------------------------------------------ Copy Ask AI enum class ModelCategory { LANGUAGE, // LLMs (text-to-text) SPEECH_RECOGNITION, // STT (voice-to-text) SPEECH_SYNTHESIS, // TTS (text-to-voice) VISION, // Image understanding IMAGE_GENERATION, // Text-to-image MULTIMODAL, // Multiple modalities AUDIO // Audio processing } [​](https://docs.runanywhere.ai/kotlin/configuration#sdk-lifecycle) SDK Lifecycle ------------------------------------------------------------------------------------ Copy Ask AI // Check initialization state val isInit = RunAnywhere.isInitialized val servicesReady = RunAnywhere.areServicesReady // Get SDK version val version = RunAnywhere.version // Get current environment val env = RunAnywhere.environment // Reset SDK (clear all state) RunAnywhere.reset() // Cleanup resources without full reset RunAnywhere.cleanup() [Voice Agent](https://docs.runanywhere.ai/kotlin/voice-agent) [Error Handling](https://docs.runanywhere.ai/kotlin/error-handling) ⌘I --- # generateStream() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/llm/stream#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation LLM (Language Models) generateStream() On this page * [LLMStreamingResult](https://docs.runanywhere.ai/flutter/llm/stream#llmstreamingresult) * [Flutter Widget Example](https://docs.runanywhere.ai/flutter/llm/stream#flutter-widget-example) * [Cancellation](https://docs.runanywhere.ai/flutter/llm/stream#cancellation) * [Best Practices](https://docs.runanywhere.ai/flutter/llm/stream#best-practices) * [See Also](https://docs.runanywhere.ai/flutter/llm/stream#see-also) Stream tokens in real-time for a responsive user experience. Ideal for chat interfaces where users expect to see text appear progressively. Copy Ask AI final streamResult = await RunAnywhere.generateStream( 'Tell me a story about a robot', options: LLMGenerationOptions(maxTokens: 500), ); // Display tokens as they arrive await for (final token in streamResult.stream) { stdout.write(token); // Real-time output // Or update UI: setState(() => _response += token); } // Get final metrics after streaming completes final metrics = await streamResult.result; print('\n\nGenerated ${metrics.tokensUsed} tokens'); print('Speed: ${metrics.tokensPerSecond.toStringAsFixed(1)} tok/s'); [​](https://docs.runanywhere.ai/flutter/llm/stream#llmstreamingresult) LLMStreamingResult -------------------------------------------------------------------------------------------- | Property | Type | Description | | --- | --- | --- | | `stream` | `Stream` | Stream of tokens | | `result` | `Future` | Final result with metrics | | `cancel` | `void Function()` | Cancel generation | [​](https://docs.runanywhere.ai/flutter/llm/stream#flutter-widget-example) Flutter Widget Example ---------------------------------------------------------------------------------------------------- Copy Ask AI class StreamingChatWidget extends StatefulWidget { @override _StreamingChatWidgetState createState() => _StreamingChatWidgetState(); } class _StreamingChatWidgetState extends State { String _response = ''; bool _isStreaming = false; LLMStreamingResult? _currentStream; Future _startStreaming(String prompt) async { setState(() { _response = ''; _isStreaming = true; }); try { _currentStream = await RunAnywhere.generateStream( prompt, options: LLMGenerationOptions(maxTokens: 300), ); await for (final token in _currentStream!.stream) { setState(() => _response += token); } final metrics = await _currentStream!.result; print('Generated at ${metrics.tokensPerSecond.toStringAsFixed(1)} tok/s'); } finally { setState(() => _isStreaming = false); } } void _cancelStreaming() { _currentStream?.cancel(); } @override Widget build(BuildContext context) { return Column( children: [\ Expanded(\ child: SingleChildScrollView(\ child: Text(_response),\ ),\ ),\ Row(\ children: [\ ElevatedButton(\ onPressed: _isStreaming ? null : () => _startStreaming('Tell me a joke'),\ child: Text('Generate'),\ ),\ if (_isStreaming)\ TextButton(\ onPressed: _cancelStreaming,\ child: Text('Cancel'),\ ),\ ],\ ),\ ], ); } } [​](https://docs.runanywhere.ai/flutter/llm/stream#cancellation) Cancellation -------------------------------------------------------------------------------- Cancel ongoing generation at any time: Copy Ask AI final streamResult = await RunAnywhere.generateStream('Long story...'); // Start a timer to cancel after 5 seconds Future.delayed(Duration(seconds: 5), () { streamResult.cancel(); print('Generation cancelled'); }); // Or cancel via the static method await RunAnywhere.cancelGeneration(); [​](https://docs.runanywhere.ai/flutter/llm/stream#best-practices) Best Practices ------------------------------------------------------------------------------------ **Use streaming for chat interfaces** — Users perceive the app as more responsive when they see tokens appear progressively, even if total generation time is the same. 1. **Update UI incrementally** — Append tokens to your state as they arrive 2. **Show a cancel button** — Let users stop long generations 3. **Handle cancellation gracefully** — The stream will complete when cancelled 4. **Get final metrics** — Always await `result` for accurate performance data [​](https://docs.runanywhere.ai/flutter/llm/stream#see-also) See Also ------------------------------------------------------------------------ [chat()\ ------\ \ Simple one-liner](https://docs.runanywhere.ai/flutter/llm/chat) [generate()\ ----------\ \ Non-streaming with metrics](https://docs.runanywhere.ai/flutter/llm/generate) [generate()](https://docs.runanywhere.ai/flutter/llm/generate) [System Prompts](https://docs.runanywhere.ai/flutter/llm/system-prompts) ⌘I --- # Voices - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/tts/voices#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation TTS (Text-to-Speech) Voices On this page * [Piper Neural Voices](https://docs.runanywhere.ai/flutter/tts/voices#piper-neural-voices) * [English (US)](https://docs.runanywhere.ai/flutter/tts/voices#english-us) * [English (UK)](https://docs.runanywhere.ai/flutter/tts/voices#english-uk) * [Other Languages](https://docs.runanywhere.ai/flutter/tts/voices#other-languages) * [Registering Voices](https://docs.runanywhere.ai/flutter/tts/voices#registering-voices) * [Switching Voices](https://docs.runanywhere.ai/flutter/tts/voices#switching-voices) * [Voice Selection UI](https://docs.runanywhere.ai/flutter/tts/voices#voice-selection-ui) * [System Voice Fallback](https://docs.runanywhere.ai/flutter/tts/voices#system-voice-fallback) * [Choosing Between Neural and System Voices](https://docs.runanywhere.ai/flutter/tts/voices#choosing-between-neural-and-system-voices) * [See Also](https://docs.runanywhere.ai/flutter/tts/voices#see-also) RunAnywhere supports neural TTS voices via Piper and system voice fallback via `flutter_tts`. [​](https://docs.runanywhere.ai/flutter/tts/voices#piper-neural-voices) Piper Neural Voices ---------------------------------------------------------------------------------------------- High-quality neural voices that run entirely on-device. ### [​](https://docs.runanywhere.ai/flutter/tts/voices#english-us) English (US) | Voice ID | Name | Gender | Style | Size | | --- | --- | --- | --- | --- | | `vits-piper-en_US-lessac-medium` | Lessac | Male | Neutral | ~50MB | | `vits-piper-en_US-amy-medium` | Amy | Female | Neutral | ~50MB | | `vits-piper-en_US-ryan-medium` | Ryan | Male | Conversational | ~50MB | | `vits-piper-en_US-kathleen-low` | Kathleen | Female | Soft | ~20MB | ### [​](https://docs.runanywhere.ai/flutter/tts/voices#english-uk) English (UK) | Voice ID | Name | Gender | Style | Size | | --- | --- | --- | --- | --- | | `vits-piper-en_GB-alan-medium` | Alan | Male | British | ~50MB | | `vits-piper-en_GB-alba-medium` | Alba | Female | Scottish | ~50MB | ### [​](https://docs.runanywhere.ai/flutter/tts/voices#other-languages) Other Languages | Voice ID | Language | Gender | Size | | --- | --- | --- | --- | | `vits-piper-de_DE-thorsten-medium` | German | Male | ~50MB | | `vits-piper-fr_FR-upmc-medium` | French | Male | ~50MB | | `vits-piper-es_ES-sharvard-medium` | Spanish | Male | ~50MB | | `vits-piper-it_IT-riccardo-x_low` | Italian | Male | ~20MB | | `vits-piper-zh_CN-huayan-medium` | Chinese | Female | ~50MB | [​](https://docs.runanywhere.ai/flutter/tts/voices#registering-voices) Registering Voices -------------------------------------------------------------------------------------------- Copy Ask AI // US English - Lessac (recommended default) Onnx.addModel( id: 'vits-piper-en_US-lessac-medium', name: 'Piper US English (Lessac)', url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-models-v1/vits-piper-en_US-lessac-medium.tar.bz2', modality: ModelCategory.textToSpeech, ); // US English - Amy (female) Onnx.addModel( id: 'vits-piper-en_US-amy-medium', name: 'Piper US English (Amy)', url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-models-v1/vits-piper-en_US-amy-medium.tar.bz2', modality: ModelCategory.textToSpeech, ); [​](https://docs.runanywhere.ai/flutter/tts/voices#switching-voices) Switching Voices ---------------------------------------------------------------------------------------- Copy Ask AI // Load default voice await RunAnywhere.loadTTSVoice('vits-piper-en_US-lessac-medium'); // Switch to different voice Future switchVoice(String voiceId) async { await RunAnywhere.unloadTTSVoice(); await RunAnywhere.loadTTSVoice(voiceId); } [​](https://docs.runanywhere.ai/flutter/tts/voices#voice-selection-ui) Voice Selection UI -------------------------------------------------------------------------------------------- Copy Ask AI class VoiceSelectorWidget extends StatefulWidget { @override _VoiceSelectorWidgetState createState() => _VoiceSelectorWidgetState(); } class _VoiceSelectorWidgetState extends State { final voices = [\ {'id': 'vits-piper-en_US-lessac-medium', 'name': 'Lessac (Male)'},\ {'id': 'vits-piper-en_US-amy-medium', 'name': 'Amy (Female)'},\ {'id': 'vits-piper-en_US-ryan-medium', 'name': 'Ryan (Male)'},\ ]; String? _selectedVoice; bool _isLoading = false; Future _selectVoice(String voiceId) async { setState(() => _isLoading = true); try { // Download if needed await for (final p in RunAnywhere.downloadModel(voiceId)) { if (p.state.isCompleted) break; } // Load voice await RunAnywhere.loadTTSVoice(voiceId); setState(() => _selectedVoice = voiceId); // Preview voice await _previewVoice(); } finally { setState(() => _isLoading = false); } } Future _previewVoice() async { final result = await RunAnywhere.synthesize( 'Hello, this is a preview of my voice.', ); // Play audio... } @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [\ Text('Select Voice', style: TextStyle(fontWeight: FontWeight.bold)),\ SizedBox(height: 8),\ ...voices.map((voice) => RadioListTile(\ title: Text(voice['name']!),\ value: voice['id']!,\ groupValue: _selectedVoice,\ onChanged: _isLoading ? null : (id) => _selectVoice(id!),\ )),\ if (_isLoading) LinearProgressIndicator(),\ ], ); } } [​](https://docs.runanywhere.ai/flutter/tts/voices#system-voice-fallback) System Voice Fallback -------------------------------------------------------------------------------------------------- The SDK can fall back to system TTS voices via `flutter_tts` when neural voices aren’t available: Copy Ask AI // System TTS is automatically available // Use it for simple cases or as fallback import 'package:flutter_tts/flutter_tts.dart'; final flutterTts = FlutterTts(); // List available system voices final voices = await flutterTts.getVoices; // Speak with system voice await flutterTts.speak('Hello world'); [​](https://docs.runanywhere.ai/flutter/tts/voices#choosing-between-neural-and-system-voices) Choosing Between Neural and System Voices ------------------------------------------------------------------------------------------------------------------------------------------ | Feature | Piper (Neural) | System TTS | | --- | --- | --- | | Quality | High | Varies | | Latency | ~100-500ms | ~50ms | | Size | 20-50MB per voice | 0 (built-in) | | Offline | Yes | Yes | | Customization | Limited | More options | **Recommendation:** Use Piper neural voices for the best quality. Fall back to system TTS for quick responses or when storage is limited. [​](https://docs.runanywhere.ai/flutter/tts/voices#see-also) See Also ------------------------------------------------------------------------ [synthesize()\ ------------\ \ Basic synthesis](https://docs.runanywhere.ai/flutter/tts/synthesize) [Voice Agent\ -----------\ \ Complete voice pipeline](https://docs.runanywhere.ai/flutter/voice-agent) [Streaming TTS](https://docs.runanywhere.ai/flutter/tts/stream) [Voice Activity Detection](https://docs.runanywhere.ai/flutter/vad) ⌘I --- # Error Handling - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/error-handling#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Flutter SDK Error Handling On this page * [Basic Error Handling](https://docs.runanywhere.ai/flutter/error-handling#basic-error-handling) * [Error Categories](https://docs.runanywhere.ai/flutter/error-handling#error-categories) * [Handling Specific Errors](https://docs.runanywhere.ai/flutter/error-handling#handling-specific-errors) * [SDKError Factory Methods](https://docs.runanywhere.ai/flutter/error-handling#sdkerror-factory-methods) * [STT/TTS Specific Errors](https://docs.runanywhere.ai/flutter/error-handling#stt%2Ftts-specific-errors) * [Voice Agent Errors](https://docs.runanywhere.ai/flutter/error-handling#voice-agent-errors) * [Download Errors](https://docs.runanywhere.ai/flutter/error-handling#download-errors) * [User-Friendly Error Messages](https://docs.runanywhere.ai/flutter/error-handling#user-friendly-error-messages) * [Error Widget Pattern](https://docs.runanywhere.ai/flutter/error-handling#error-widget-pattern) * [See Also](https://docs.runanywhere.ai/flutter/error-handling#see-also) The SDK provides comprehensive error handling through `SDKError` with specific error codes for different failure scenarios. [​](https://docs.runanywhere.ai/flutter/error-handling#basic-error-handling) Basic Error Handling ---------------------------------------------------------------------------------------------------- Copy Ask AI try { await RunAnywhere.loadModel('my-model'); final result = await RunAnywhere.generate('Hello'); print(result.text); } on SDKError catch (error) { print('Error: ${error.message}'); print('Code: ${error.code}'); } [​](https://docs.runanywhere.ai/flutter/error-handling#error-categories) Error Categories -------------------------------------------------------------------------------------------- | Category | Description | Common Errors | | --- | --- | --- | | `general` | General SDK errors | notInitialized | | `llm` | LLM generation errors | generationFailed | | `stt` | Speech-to-text errors | sttNotAvailable | | `tts` | Text-to-speech errors | ttsNotAvailable | | `voiceAgent` | Voice pipeline errors | voiceAgentNotReady | | `download` | Model download errors | downloadFailed | | `validation` | Input validation errors | validationFailed | [​](https://docs.runanywhere.ai/flutter/error-handling#handling-specific-errors) Handling Specific Errors ------------------------------------------------------------------------------------------------------------ Copy Ask AI try { await RunAnywhere.loadModel('my-model'); final result = await RunAnywhere.generate('Hello!'); } on SDKError catch (error) { switch (error.code) { case SDKErrorCode.notInitialized: // SDK not initialized showError('Please restart the app'); await RunAnywhere.initialize(); break; case SDKErrorCode.modelNotFound: // Model not registered showError('Model not found. Please check the model ID.'); break; case SDKErrorCode.modelNotDownloaded: // Model needs to be downloaded first showError('Model not downloaded. Downloading now...'); await downloadModel('my-model'); break; case SDKErrorCode.componentNotReady: // Component not loaded showError('Model not loaded. Loading now...'); await RunAnywhere.loadModel('my-model'); break; case SDKErrorCode.generationFailed: // Generation failed showError('Generation failed. Please try again.'); break; default: showError('Error: ${error.message}'); } } [​](https://docs.runanywhere.ai/flutter/error-handling#sdkerror-factory-methods) SDKError Factory Methods ------------------------------------------------------------------------------------------------------------ Common error types with factory constructors: Copy Ask AI // Check error types if (error == SDKError.notInitialized()) { // Handle not initialized } if (error == SDKError.modelNotFound('model-id')) { // Handle model not found } if (error == SDKError.modelNotDownloaded('model-id')) { // Handle model not downloaded } if (error == SDKError.componentNotReady('LLM')) { // Handle component not ready } [​](https://docs.runanywhere.ai/flutter/error-handling#stt/tts-specific-errors) STT/TTS Specific Errors ---------------------------------------------------------------------------------------------------------- Copy Ask AI try { final text = await RunAnywhere.transcribe(audioBytes); } on SDKError catch (error) { switch (error.code) { case SDKErrorCode.sttNotAvailable: showError('Speech recognition not available. Load an STT model.'); break; case SDKErrorCode.componentNotReady: showError('STT model not loaded.'); await RunAnywhere.loadSTTModel('whisper-tiny-en'); break; default: showError('Transcription failed: ${error.message}'); } } try { final result = await RunAnywhere.synthesize('Hello'); } on SDKError catch (error) { switch (error.code) { case SDKErrorCode.ttsNotAvailable: showError('Text-to-speech not available. Load a TTS voice.'); break; case SDKErrorCode.componentNotReady: showError('TTS voice not loaded.'); await RunAnywhere.loadTTSVoice('piper-en-us-amy'); break; default: showError('Synthesis failed: ${error.message}'); } } [​](https://docs.runanywhere.ai/flutter/error-handling#voice-agent-errors) Voice Agent Errors ------------------------------------------------------------------------------------------------ Copy Ask AI try { final session = await RunAnywhere.startVoiceSession(); } on SDKError catch (error) { if (error.code == SDKErrorCode.voiceAgentNotReady) { // Check which component is missing final states = RunAnywhere.getVoiceAgentComponentStates(); if (states.stt != ComponentLoadState.loaded) { showError('STT model not loaded'); await RunAnywhere.loadSTTModel('whisper-tiny-en'); } if (states.llm != ComponentLoadState.loaded) { showError('LLM model not loaded'); await RunAnywhere.loadModel('smollm2-360m'); } if (states.tts != ComponentLoadState.loaded) { showError('TTS voice not loaded'); await RunAnywhere.loadTTSVoice('piper-en-us-amy'); } } } [​](https://docs.runanywhere.ai/flutter/error-handling#download-errors) Download Errors ------------------------------------------------------------------------------------------ Copy Ask AI try { await for (final progress in RunAnywhere.downloadModel('my-model')) { if (progress.state == DownloadProgressState.failed) { throw SDKError.downloadFailed('Download failed'); } if (progress.state.isCompleted) break; } } on SDKError catch (error) { showError('Failed to download model: ${error.message}'); // Suggest checking internet connection showRetryOption(); } [​](https://docs.runanywhere.ai/flutter/error-handling#user-friendly-error-messages) User-Friendly Error Messages -------------------------------------------------------------------------------------------------------------------- Create a helper to convert errors to user-friendly messages: Copy Ask AI String getUserFriendlyMessage(SDKError error) { switch (error.code) { case SDKErrorCode.notInitialized: return 'The app needs to restart. Please close and reopen the app.'; case SDKErrorCode.modelNotFound: return 'The AI model could not be found. Please check your settings.'; case SDKErrorCode.modelNotDownloaded: return 'This feature needs to download data first. Please connect to WiFi.'; case SDKErrorCode.componentNotReady: return 'Loading AI features... Please wait a moment.'; case SDKErrorCode.generationFailed: return 'Something went wrong. Please try again.'; case SDKErrorCode.sttNotAvailable: return 'Voice recognition is not available right now.'; case SDKErrorCode.ttsNotAvailable: return 'Voice output is not available right now.'; default: return 'An error occurred. Please try again later.'; } } [​](https://docs.runanywhere.ai/flutter/error-handling#error-widget-pattern) Error Widget Pattern ---------------------------------------------------------------------------------------------------- Copy Ask AI class ErrorHandler extends StatelessWidget { final Widget child; final Function(SDKError) onError; const ErrorHandler({ required this.child, required this.onError, }); @override Widget build(BuildContext context) { return child; } static void handle(BuildContext context, SDKError error) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(getUserFriendlyMessage(error)), action: SnackBarAction( label: 'Retry', onPressed: () { // Implement retry logic }, ), ), ); } } [​](https://docs.runanywhere.ai/flutter/error-handling#see-also) See Also ---------------------------------------------------------------------------- [Configuration\ -------------\ \ SDK configuration](https://docs.runanywhere.ai/flutter/configuration) [Best Practices\ --------------\ \ Optimization tips](https://docs.runanywhere.ai/flutter/best-practices) [Configuration](https://docs.runanywhere.ai/flutter/configuration) [Best Practices](https://docs.runanywhere.ai/flutter/best-practices) ⌘I --- # Voice Activity Detection - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/vad#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Flutter SDK Voice Activity Detection On this page * [Overview](https://docs.runanywhere.ai/flutter/vad#overview) * [Automatic VAD with Voice Session](https://docs.runanywhere.ai/flutter/vad#automatic-vad-with-voice-session) * [VoiceSessionConfig for VAD](https://docs.runanywhere.ai/flutter/vad#voicesessionconfig-for-vad) * [Building a Voice Level Indicator](https://docs.runanywhere.ai/flutter/vad#building-a-voice-level-indicator) * [Voice Session with VAD Events](https://docs.runanywhere.ai/flutter/vad#voice-session-with-vad-events) * [VAD Tuning Tips](https://docs.runanywhere.ai/flutter/vad#vad-tuning-tips) * [See Also](https://docs.runanywhere.ai/flutter/vad#see-also) Voice Activity Detection (VAD) automatically detects speech in audio streams, enabling hands-free voice interfaces. [​](https://docs.runanywhere.ai/flutter/vad#overview) Overview ----------------------------------------------------------------- VAD determines when a user is speaking vs. silent, which is essential for: * Knowing when to start/stop recording * Triggering transcription at the right time * Building push-to-talk or hands-free interfaces The SDK provides energy-based VAD with Silero VAD for accurate speech detection. [​](https://docs.runanywhere.ai/flutter/vad#automatic-vad-with-voice-session) Automatic VAD with Voice Session ----------------------------------------------------------------------------------------------------------------- The easiest way to use VAD is through the Voice Agent pipeline: Copy Ask AI final session = await RunAnywhere.startVoiceSession( config: VoiceSessionConfig( speechThreshold: 0.03, // Audio level threshold silenceDuration: 1.5, // Seconds of silence before processing ), ); session.events.listen((event) { switch (event) { case VoiceSessionListening(:final audioLevel): // Show audio level meter updateAudioMeter(audioLevel); case VoiceSessionSpeechStarted(): print('User started speaking'); case VoiceSessionProcessing(): print('Processing speech...'); } }); [​](https://docs.runanywhere.ai/flutter/vad#voicesessionconfig-for-vad) VoiceSessionConfig for VAD ----------------------------------------------------------------------------------------------------- | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `speechThreshold` | `double` | 0.03 | Audio level to trigger speech detection | | `silenceDuration` | `double` | 1.5 | Seconds of silence before processing | Copy Ask AI // More sensitive (quieter environments) final quietConfig = VoiceSessionConfig( speechThreshold: 0.01, silenceDuration: 1.0, ); // Less sensitive (noisy environments) final noisyConfig = VoiceSessionConfig( speechThreshold: 0.1, silenceDuration: 2.0, ); [​](https://docs.runanywhere.ai/flutter/vad#building-a-voice-level-indicator) Building a Voice Level Indicator ----------------------------------------------------------------------------------------------------------------- Copy Ask AI class VoiceLevelIndicator extends StatefulWidget { final Stream audioLevelStream; const VoiceLevelIndicator({required this.audioLevelStream}); @override _VoiceLevelIndicatorState createState() => _VoiceLevelIndicatorState(); } class _VoiceLevelIndicatorState extends State { double _level = 0.0; StreamSubscription? _subscription; @override void initState() { super.initState(); _subscription = widget.audioLevelStream.listen((level) { setState(() => _level = level); }); } @override Widget build(BuildContext context) { return Container( height: 10, child: LinearProgressIndicator( value: _level.clamp(0.0, 1.0), backgroundColor: Colors.grey[300], valueColor: AlwaysStoppedAnimation( _level > 0.03 ? Colors.green : Colors.grey, ), ), ); } @override void dispose() { _subscription?.cancel(); super.dispose(); } } [​](https://docs.runanywhere.ai/flutter/vad#voice-session-with-vad-events) Voice Session with VAD Events ----------------------------------------------------------------------------------------------------------- Copy Ask AI class VoiceAssistant extends StatefulWidget { @override _VoiceAssistantState createState() => _VoiceAssistantState(); } class _VoiceAssistantState extends State { VoiceSessionHandle? _session; double _audioLevel = 0.0; bool _isSpeaking = false; String _status = 'Ready'; Future _startSession() async { _session = await RunAnywhere.startVoiceSession( config: VoiceSessionConfig( speechThreshold: 0.03, silenceDuration: 1.5, autoPlayTTS: true, continuousMode: true, ), ); _session!.events.listen((event) { setState(() { switch (event) { case VoiceSessionListening(:final audioLevel): _audioLevel = audioLevel; _status = 'Listening...'; case VoiceSessionSpeechStarted(): _isSpeaking = true; _status = 'Speaking detected'; case VoiceSessionProcessing(): _isSpeaking = false; _status = 'Processing...'; case VoiceSessionTranscribed(:final text): _status = 'You: $text'; case VoiceSessionResponded(:final text): _status = 'AI: $text'; case VoiceSessionSpeaking(): _status = 'AI speaking...'; case VoiceSessionTurnCompleted(): _status = 'Ready'; case VoiceSessionStopped(): _status = 'Stopped'; } }); }); } void _stopSession() { _session?.stop(); } @override Widget build(BuildContext context) { return Column( mainAxisAlignment: MainAxisAlignment.center, children: [\ // Audio level indicator\ Container(\ width: 100,\ height: 100,\ decoration: BoxDecoration(\ shape: BoxShape.circle,\ color: _isSpeaking ? Colors.green : Colors.blue,\ boxShadow: [\ BoxShadow(\ color: (_isSpeaking ? Colors.green : Colors.blue)\ .withOpacity(0.5),\ blurRadius: _audioLevel * 50,\ spreadRadius: _audioLevel * 20,\ ),\ ],\ ),\ child: Icon(\ _isSpeaking ? Icons.mic : Icons.mic_none,\ color: Colors.white,\ size: 48,\ ),\ ),\ \ SizedBox(height: 24),\ Text(_status, textAlign: TextAlign.center),\ \ SizedBox(height: 24),\ ElevatedButton(\ onPressed: _session == null ? _startSession : _stopSession,\ child: Text(_session == null ? 'Start' : 'Stop'),\ ),\ ], ); } } [​](https://docs.runanywhere.ai/flutter/vad#vad-tuning-tips) VAD Tuning Tips ------------------------------------------------------------------------------- Threshold Adjustment Lower thresholds (0.01) detect quieter speech but may trigger on background noise. Higher thresholds (0.1) require louder speech but are more robust to noise. Silence Duration Shorter duration (0.5s) feels more responsive but may cut off pauses mid-sentence. Longer duration (2.0s) allows natural pauses but feels slower. Environment Calibration Consider measuring ambient noise level and adjusting threshold dynamically. [​](https://docs.runanywhere.ai/flutter/vad#see-also) See Also ----------------------------------------------------------------- [Voice Agent\ -----------\ \ Complete voice pipeline](https://docs.runanywhere.ai/flutter/voice-agent) [Speech-to-Text\ --------------\ \ Audio transcription](https://docs.runanywhere.ai/flutter/stt/transcribe) [Voices](https://docs.runanywhere.ai/flutter/tts/voices) [Voice Agent](https://docs.runanywhere.ai/flutter/voice-agent) ⌘I --- # STT Options - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/stt/options#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation STT (Speech-to-Text) STT Options On this page * [Model Selection](https://docs.runanywhere.ai/flutter/stt/options#model-selection) * [Register Multiple Models](https://docs.runanywhere.ai/flutter/stt/options#register-multiple-models) * [Switch Models at Runtime](https://docs.runanywhere.ai/flutter/stt/options#switch-models-at-runtime) * [Memory Management](https://docs.runanywhere.ai/flutter/stt/options#memory-management) * [Audio Preprocessing Tips](https://docs.runanywhere.ai/flutter/stt/options#audio-preprocessing-tips) * [Error Handling](https://docs.runanywhere.ai/flutter/stt/options#error-handling) * [Best Practices](https://docs.runanywhere.ai/flutter/stt/options#best-practices) * [See Also](https://docs.runanywhere.ai/flutter/stt/options#see-also) Configure STT behavior for different use cases and languages. [​](https://docs.runanywhere.ai/flutter/stt/options#model-selection) Model Selection --------------------------------------------------------------------------------------- Choose the right model based on your needs: | Model | Size | Languages | Quality | Speed | Use Case | | --- | --- | --- | --- | --- | --- | | `whisper-tiny.en` | ~75MB | English | Good | Fastest | Quick commands | | `whisper-base.en` | ~150MB | English | Better | Fast | General use | | `whisper-small.en` | ~250MB | English | Best | Medium | Accuracy-critical | | `whisper-tiny` | ~75MB | Multi | Good | Fast | Multilingual apps | [​](https://docs.runanywhere.ai/flutter/stt/options#register-multiple-models) Register Multiple Models --------------------------------------------------------------------------------------------------------- Copy Ask AI // English-optimized for primary use Onnx.addModel( id: 'whisper-tiny-en', name: 'Whisper Tiny English', url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-models-v1/sherpa-onnx-whisper-tiny.en.tar.gz', modality: ModelCategory.speechRecognition, ); // Multilingual for international users Onnx.addModel( id: 'whisper-tiny-multi', name: 'Whisper Tiny Multilingual', url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-models-v1/sherpa-onnx-whisper-tiny.tar.gz', modality: ModelCategory.speechRecognition, ); [​](https://docs.runanywhere.ai/flutter/stt/options#switch-models-at-runtime) Switch Models at Runtime --------------------------------------------------------------------------------------------------------- Copy Ask AI // Load English model by default await RunAnywhere.loadSTTModel('whisper-tiny-en'); // Switch to multilingual when needed Future switchToMultilingual() async { await RunAnywhere.unloadSTTModel(); await RunAnywhere.loadSTTModel('whisper-tiny-multi'); } [​](https://docs.runanywhere.ai/flutter/stt/options#memory-management) Memory Management ------------------------------------------------------------------------------------------- Unload STT model when not needed to free memory: Copy Ask AI // Check if loaded if (RunAnywhere.isSTTModelLoaded) { print('Current STT model: ${RunAnywhere.currentSTTModelId}'); } // Unload to free memory await RunAnywhere.unloadSTTModel(); [​](https://docs.runanywhere.ai/flutter/stt/options#audio-preprocessing-tips) Audio Preprocessing Tips --------------------------------------------------------------------------------------------------------- Sample Rate Conversion If your audio isn’t 16kHz, convert it before transcription: `dart // Example: Convert 44.1kHz to 16kHz // Use a package like 'flutter_sound' for resampling` Noise Reduction For noisy environments, consider preprocessing audio: - Apply a high-pass filter to remove low-frequency noise - Normalize audio levels - Remove silence at beginning/end Audio Format Always ensure correct format: - PCM16 (16-bit signed integer) - 16,000 Hz sample rate - Mono (single channel) [​](https://docs.runanywhere.ai/flutter/stt/options#error-handling) Error Handling ------------------------------------------------------------------------------------- Copy Ask AI try { final text = await RunAnywhere.transcribe(audioBytes); print('Transcribed: $text'); } on SDKError catch (e) { switch (e.code) { case SDKErrorCode.sttNotAvailable: print('STT not available. Load an STT model first.'); break; case SDKErrorCode.componentNotReady: print('STT model not loaded.'); break; default: print('STT error: ${e.message}'); } } [​](https://docs.runanywhere.ai/flutter/stt/options#best-practices) Best Practices ------------------------------------------------------------------------------------- **Start with the smallest model** that meets your accuracy needs. You can always upgrade later if needed. 1. **Preload during idle time** — Download and load STT model before user needs it 2. **Use English-specific models** — They’re smaller and more accurate for English 3. **Handle empty audio** — Check audio length before transcribing 4. **Provide feedback** — Show transcription progress to users [​](https://docs.runanywhere.ai/flutter/stt/options#see-also) See Also ------------------------------------------------------------------------- [transcribe()\ ------------\ \ Basic transcription](https://docs.runanywhere.ai/flutter/stt/transcribe) [Voice Agent\ -----------\ \ Complete voice pipeline](https://docs.runanywhere.ai/flutter/voice-agent) [Streaming STT](https://docs.runanywhere.ai/flutter/stt/stream) [synthesize()](https://docs.runanywhere.ai/flutter/tts/synthesize) ⌘I --- # Installation - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/installation#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Kotlin SDK Installation On this page * [Gradle Setup](https://docs.runanywhere.ai/kotlin/installation#gradle-setup) * [Module Overview](https://docs.runanywhere.ai/kotlin/installation#module-overview) * [Supported Model Formats](https://docs.runanywhere.ai/kotlin/installation#supported-model-formats) * [Android Manifest](https://docs.runanywhere.ai/kotlin/installation#android-manifest) * [ProGuard Rules](https://docs.runanywhere.ai/kotlin/installation#proguard-rules) * [Next Steps](https://docs.runanywhere.ai/kotlin/installation#next-steps) [​](https://docs.runanywhere.ai/kotlin/installation#gradle-setup) Gradle Setup --------------------------------------------------------------------------------- Add the RunAnywhere SDK to your module-level `build.gradle.kts`: build.gradle.kts (Module: app) Copy Ask AI dependencies { // Core SDK (required) implementation("com.runanywhere.sdk:runanywhere-kotlin:0.1.4") // LLM support - llama.cpp backend (~34MB) implementation("com.runanywhere.sdk:runanywhere-core-llamacpp:0.1.4") // STT/TTS/VAD support - ONNX backend (~25MB) implementation("com.runanywhere.sdk:runanywhere-core-onnx:0.1.4") } Include only the modules you need. Each native module adds to your APK size: - **runanywhere-core-llamacpp**: ~34MB (for LLM text generation) - **runanywhere-core-onnx**: ~25MB (for STT, TTS, and VAD) [​](https://docs.runanywhere.ai/kotlin/installation#module-overview) Module Overview --------------------------------------------------------------------------------------- | Module | Size | Features | | --- | --- | --- | | `runanywhere-kotlin` | ~2MB | Core SDK, model management, events | | `runanywhere-core-llamacpp` | ~34MB | LLM text generation (GGUF models) | | `runanywhere-core-onnx` | ~25MB | STT, TTS, VAD (ONNX models) | [​](https://docs.runanywhere.ai/kotlin/installation#supported-model-formats) Supported Model Formats ------------------------------------------------------------------------------------------------------- | Format | Extension | Backend | Use Case | | --- | --- | --- | --- | | GGUF | `.gguf` | llama.cpp | LLM text generation | | ONNX | `.onnx` | ONNX Runtime | STT, TTS, VAD | | ORT | `.ort` | ONNX Runtime | Optimized STT/TTS | [​](https://docs.runanywhere.ai/kotlin/installation#android-manifest) Android Manifest ----------------------------------------------------------------------------------------- Add the required permissions to your `AndroidManifest.xml`: AndroidManifest.xml Copy Ask AI `INTERNET` is required for model downloads. `RECORD_AUDIO` is only needed if you’re using STT or VAD with microphone input. [​](https://docs.runanywhere.ai/kotlin/installation#proguard-rules) ProGuard Rules ------------------------------------------------------------------------------------- If using ProGuard/R8 minification, add these rules: proguard-rules.pro Copy Ask AI -keep class com.runanywhere.sdk.** { *; } -keepclassmembers class com.runanywhere.sdk.** { *; } [​](https://docs.runanywhere.ai/kotlin/installation#next-steps) Next Steps ----------------------------------------------------------------------------- [Quick Start\ -----------\ \ Initialize the SDK and run your first inference →](https://docs.runanywhere.ai/kotlin/quick-start) [Introduction](https://docs.runanywhere.ai/kotlin/introduction) [Quick Start](https://docs.runanywhere.ai/kotlin/quick-start) ⌘I --- # System Prompts - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/llm/system-prompts#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation LLM (Language Models) System Prompts On this page * [Basic Usage](https://docs.runanywhere.ai/flutter/llm/system-prompts#basic-usage) * [Common Patterns](https://docs.runanywhere.ai/flutter/llm/system-prompts#common-patterns) * [Coding Assistant](https://docs.runanywhere.ai/flutter/llm/system-prompts#coding-assistant) * [Customer Support Bot](https://docs.runanywhere.ai/flutter/llm/system-prompts#customer-support-bot) * [JSON Output](https://docs.runanywhere.ai/flutter/llm/system-prompts#json-output) * [Character/Persona](https://docs.runanywhere.ai/flutter/llm/system-prompts#character%2Fpersona) * [Tips for Effective System Prompts](https://docs.runanywhere.ai/flutter/llm/system-prompts#tips-for-effective-system-prompts) * [Reusable Prompt Class](https://docs.runanywhere.ai/flutter/llm/system-prompts#reusable-prompt-class) * [See Also](https://docs.runanywhere.ai/flutter/llm/system-prompts#see-also) System prompts set the context and behavior for your AI model. Use them to create specialized assistants, enforce response formats, or constrain the model’s persona. [​](https://docs.runanywhere.ai/flutter/llm/system-prompts#basic-usage) Basic Usage -------------------------------------------------------------------------------------- Copy Ask AI final result = await RunAnywhere.generate( 'Write a function to sort an array', options: LLMGenerationOptions( maxTokens: 300, systemPrompt: 'You are a helpful coding assistant. Write clean, well-commented code.', ), ); [​](https://docs.runanywhere.ai/flutter/llm/system-prompts#common-patterns) Common Patterns ---------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/flutter/llm/system-prompts#coding-assistant) Coding Assistant Copy Ask AI const codingPrompt = ''' You are an expert programmer. Follow these rules: - Write clean, readable code with comments - Use best practices and design patterns - Explain your approach briefly before the code - Handle edge cases '''; final result = await RunAnywhere.generate( 'Implement a binary search in Dart', options: LLMGenerationOptions( systemPrompt: codingPrompt, maxTokens: 400, ), ); ### [​](https://docs.runanywhere.ai/flutter/llm/system-prompts#customer-support-bot) Customer Support Bot Copy Ask AI const supportPrompt = ''' You are a friendly customer support agent for TechCorp. - Be helpful and empathetic - Keep responses concise (2-3 sentences) - If you don't know something, say so - Never make up information about products '''; ### [​](https://docs.runanywhere.ai/flutter/llm/system-prompts#json-output) JSON Output Copy Ask AI const jsonPrompt = ''' You are a data extraction assistant. Always respond with valid JSON only, no additional text. Extract the requested information into the specified format. '''; final result = await RunAnywhere.generate( 'Extract: "John Smith, 25 years old, engineer at Google"', options: LLMGenerationOptions( systemPrompt: jsonPrompt, maxTokens: 100, temperature: 0.1, // Lower temperature for consistent format ), ); // Parse the JSON response final data = jsonDecode(result.text); ### [​](https://docs.runanywhere.ai/flutter/llm/system-prompts#character/persona) Character/Persona Copy Ask AI const personaPrompt = ''' You are Captain Nova, a space explorer from the year 3000. - Speak with enthusiasm about space and technology - Reference your adventures across the galaxy - Use occasional space-themed expressions - Stay in character at all times '''; [​](https://docs.runanywhere.ai/flutter/llm/system-prompts#tips-for-effective-system-prompts) Tips for Effective System Prompts ---------------------------------------------------------------------------------------------------------------------------------- Be Specific Vague prompts lead to inconsistent results. Specify exactly what you want: ❌ “Be helpful” ✅ “Provide step-by-step instructions. Use bullet points. Keep each step under 20 words.” Use Examples Show the model what you expect: `Format responses like this example: Q: What is 2+2? A: **4** — Two plus two equals four.` Set Boundaries Tell the model what NOT to do: `- Do not provide medical advice - Do not generate harmful content - If asked about topics outside your expertise, politely decline` Keep It Concise Shorter prompts use fewer tokens and leave more room for generation: ❌ Long, rambling instructions with repetition ✅ Clear, bullet-pointed rules [​](https://docs.runanywhere.ai/flutter/llm/system-prompts#reusable-prompt-class) Reusable Prompt Class ---------------------------------------------------------------------------------------------------------- Create a helper class for managing prompts: Copy Ask AI class SystemPrompts { static const String coding = ''' You are an expert programmer. Write clean, well-documented code. '''; static const String creative = ''' You are a creative writing assistant. Be imaginative and engaging. '''; static String forDomain(String domain) => ''' You are an expert in $domain. Provide accurate, helpful information. '''; } // Usage final result = await RunAnywhere.generate( prompt, options: LLMGenerationOptions( systemPrompt: SystemPrompts.coding, ), ); [​](https://docs.runanywhere.ai/flutter/llm/system-prompts#see-also) See Also -------------------------------------------------------------------------------- [generate()\ ----------\ \ Full generation API](https://docs.runanywhere.ai/flutter/llm/generate) [Best Practices\ --------------\ \ Optimization tips](https://docs.runanywhere.ai/flutter/best-practices) [generateStream()](https://docs.runanywhere.ai/flutter/llm/stream) [transcribe()](https://docs.runanywhere.ai/flutter/stt/transcribe) ⌘I --- # synthesize() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/tts/synthesize#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation TTS (Text-to-Speech) synthesize() On this page * [Basic Usage](https://docs.runanywhere.ai/flutter/tts/synthesize#basic-usage) * [TTSResult](https://docs.runanywhere.ai/flutter/tts/synthesize#ttsresult) * [Parameters](https://docs.runanywhere.ai/flutter/tts/synthesize#parameters) * [Setup](https://docs.runanywhere.ai/flutter/tts/synthesize#setup) * [1\. Register ONNX Backend](https://docs.runanywhere.ai/flutter/tts/synthesize#1-register-onnx-backend) * [2\. Add TTS Voice](https://docs.runanywhere.ai/flutter/tts/synthesize#2-add-tts-voice) * [3\. Download & Load](https://docs.runanywhere.ai/flutter/tts/synthesize#3-download-%26-load) * [Playing Audio](https://docs.runanywhere.ai/flutter/tts/synthesize#playing-audio) * [Complete Example](https://docs.runanywhere.ai/flutter/tts/synthesize#complete-example) * [See Also](https://docs.runanywhere.ai/flutter/tts/synthesize#see-also) Synthesize natural-sounding speech from text using on-device Piper TTS models. [​](https://docs.runanywhere.ai/flutter/tts/synthesize#basic-usage) Basic Usage ---------------------------------------------------------------------------------- Copy Ask AI // Load a TTS voice await RunAnywhere.loadTTSVoice('vits-piper-en_US-lessac-medium'); // Synthesize speech final result = await RunAnywhere.synthesize( 'Hello! Welcome to RunAnywhere.', rate: 1.0, pitch: 1.0, ); // result.samples contains PCM Float32 audio // result.sampleRate is typically 22050 Hz print('Duration: ${result.durationSeconds}s'); [​](https://docs.runanywhere.ai/flutter/tts/synthesize#ttsresult) TTSResult ------------------------------------------------------------------------------ | Property | Type | Description | | --- | --- | --- | | `samples` | `Float32List` | Audio samples (PCM float) | | `sampleRate` | `int` | Sample rate in Hz (typically 22050) | | `durationMs` | `int` | Duration in milliseconds | | `durationSeconds` | `double` | Duration in seconds | | `numSamples` | `int` | Number of audio samples | [​](https://docs.runanywhere.ai/flutter/tts/synthesize#parameters) Parameters -------------------------------------------------------------------------------- | Parameter | Type | Default | Description | | --- | --- | --- | --- | | `rate` | `double` | 1.0 | Speech rate (0.5 to 2.0) | | `pitch` | `double` | 1.0 | Voice pitch (0.5 to 2.0) | | `volume` | `double` | 1.0 | Volume (0.0 to 1.0) | Copy Ask AI // Slower, lower pitch for emphasis final result = await RunAnywhere.synthesize( 'Important announcement!', rate: 0.8, pitch: 0.9, volume: 1.0, ); [​](https://docs.runanywhere.ai/flutter/tts/synthesize#setup) Setup ---------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/flutter/tts/synthesize#1-register-onnx-backend) 1\. Register ONNX Backend Copy Ask AI import 'package:runanywhere_onnx/runanywhere_onnx.dart'; await Onnx.register(); ### [​](https://docs.runanywhere.ai/flutter/tts/synthesize#2-add-tts-voice) 2\. Add TTS Voice Copy Ask AI Onnx.addModel( id: 'vits-piper-en_US-lessac-medium', name: 'Piper US English (Lessac)', url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-models-v1/vits-piper-en_US-lessac-medium.tar.bz2', modality: ModelCategory.textToSpeech, ); ### [​](https://docs.runanywhere.ai/flutter/tts/synthesize#3-download-&-load) 3\. Download & Load Copy Ask AI // Download await for (final progress in RunAnywhere.downloadModel('vits-piper-en_US-lessac-medium')) { print('${(progress.percentage * 100).toStringAsFixed(1)}%'); if (progress.state.isCompleted) break; } // Load await RunAnywhere.loadTTSVoice('vits-piper-en_US-lessac-medium'); [​](https://docs.runanywhere.ai/flutter/tts/synthesize#playing-audio) Playing Audio -------------------------------------------------------------------------------------- Use a package like `audioplayers` to play the synthesized audio: Copy Ask AI import 'package:audioplayers/audioplayers.dart'; final player = AudioPlayer(); Future speakText(String text) async { final result = await RunAnywhere.synthesize(text); // Convert Float32 samples to bytes for playback final bytes = _convertToBytes(result.samples, result.sampleRate); // Play using audioplayers await player.play(BytesSource(bytes)); } Uint8List _convertToBytes(Float32List samples, int sampleRate) { // Convert Float32 PCM to Int16 PCM WAV format final int16Samples = Int16List(samples.length); for (var i = 0; i < samples.length; i++) { int16Samples[i] = (samples[i] * 32767).clamp(-32768, 32767).toInt(); } // Create WAV header + data return _createWavFile(int16Samples, sampleRate); } [​](https://docs.runanywhere.ai/flutter/tts/synthesize#complete-example) Complete Example -------------------------------------------------------------------------------------------- Copy Ask AI class TextToSpeechDemo extends StatefulWidget { @override _TextToSpeechDemoState createState() => _TextToSpeechDemoState(); } class _TextToSpeechDemoState extends State { final _controller = TextEditingController(); final _player = AudioPlayer(); bool _isSpeaking = false; bool _isLoaded = false; @override void initState() { super.initState(); _initTTS(); } Future _initTTS() async { // Download if needed final models = await RunAnywhere.availableModels(); final ttsModel = models.firstWhere( (m) => m.id == 'vits-piper-en_US-lessac-medium', ); if (!ttsModel.isDownloaded) { await for (final p in RunAnywhere.downloadModel(ttsModel.id)) { if (p.state.isCompleted) break; } } // Load voice await RunAnywhere.loadTTSVoice('vits-piper-en_US-lessac-medium'); setState(() => _isLoaded = true); } Future _speak() async { if (_controller.text.isEmpty) return; setState(() => _isSpeaking = true); try { final result = await RunAnywhere.synthesize(_controller.text); // Play audio (implementation depends on your audio setup) await _playAudio(result); } finally { setState(() => _isSpeaking = false); } } @override Widget build(BuildContext context) { return Column( children: [\ TextField(\ controller: _controller,\ decoration: InputDecoration(\ hintText: 'Enter text to speak...',\ ),\ maxLines: 3,\ ),\ SizedBox(height: 16),\ ElevatedButton.icon(\ onPressed: _isLoaded && !_isSpeaking ? _speak : null,\ icon: Icon(_isSpeaking ? Icons.stop : Icons.volume_up),\ label: Text(_isSpeaking ? 'Speaking...' : 'Speak'),\ ),\ ], ); } @override void dispose() { _controller.dispose(); _player.dispose(); super.dispose(); } } [​](https://docs.runanywhere.ai/flutter/tts/synthesize#see-also) See Also ---------------------------------------------------------------------------- [Streaming TTS\ -------------\ \ Stream audio as it’s generated](https://docs.runanywhere.ai/flutter/tts/stream) [Available Voices\ ----------------\ \ Browse voice options](https://docs.runanywhere.ai/flutter/tts/voices) [STT Options](https://docs.runanywhere.ai/flutter/stt/options) [Streaming TTS](https://docs.runanywhere.ai/flutter/tts/stream) ⌘I --- # Quick Start - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/quick-start#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Flutter SDK Quick Start On this page * [Complete Example](https://docs.runanywhere.ai/flutter/quick-start#complete-example) * [Step-by-Step Breakdown](https://docs.runanywhere.ai/flutter/quick-start#step-by-step-breakdown) * [1\. Initialize the SDK](https://docs.runanywhere.ai/flutter/quick-start#1-initialize-the-sdk) * [2\. Register Backend Modules](https://docs.runanywhere.ai/flutter/quick-start#2-register-backend-modules) * [3\. Register Models](https://docs.runanywhere.ai/flutter/quick-start#3-register-models) * [4\. Download & Load Models](https://docs.runanywhere.ai/flutter/quick-start#4-download-%26-load-models) * [5\. Generate Text](https://docs.runanywhere.ai/flutter/quick-start#5-generate-text) * [Environment Options](https://docs.runanywhere.ai/flutter/quick-start#environment-options) * [Starter Example Repository](https://docs.runanywhere.ai/flutter/quick-start#starter-example-repository) * [Next Steps](https://docs.runanywhere.ai/flutter/quick-start#next-steps) **Want a complete working app?** Clone our [Flutter Starter Example](https://github.com/RunanywhereAI/flutter-starter-example) to get started immediately with a full-featured demo app. [​](https://docs.runanywhere.ai/flutter/quick-start#complete-example) Complete Example ----------------------------------------------------------------------------------------- Here’s a complete example to get you started with on-device text generation: Copy Ask AI import 'package:flutter/material.dart'; import 'package:runanywhere/runanywhere.dart'; import 'package:runanywhere_llamacpp/runanywhere_llamacpp.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); // 1. Initialize SDK await RunAnywhere.initialize(); // 2. Register LlamaCpp backend await LlamaCpp.register(); // 3. Add a model LlamaCpp.addModel( id: 'smollm2-360m-q8_0', name: 'SmolLM2 360M Q8_0', url: 'https://huggingface.co/prithivMLmods/SmolLM2-360M-GGUF/resolve/main/SmolLM2-360M.Q8_0.gguf', memoryRequirement: 500000000, ); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: ChatScreen(), ); } } class ChatScreen extends StatefulWidget { @override _ChatScreenState createState() => _ChatScreenState(); } class _ChatScreenState extends State { String _response = ''; bool _isLoading = false; bool _isModelLoaded = false; Future _loadModel() async { setState(() => _isLoading = true); try { // Download model (with progress) await for (final progress in RunAnywhere.downloadModel('smollm2-360m-q8_0')) { print('Download: ${(progress.percentage * 100).toStringAsFixed(1)}%'); if (progress.state.isCompleted) break; } // Load model await RunAnywhere.loadModel('smollm2-360m-q8_0'); setState(() => _isModelLoaded = true); } catch (e) { setState(() => _response = 'Error: $e'); } finally { setState(() => _isLoading = false); } } Future _generateText() async { setState(() => _isLoading = true); try { final result = await RunAnywhere.generate( 'Explain quantum computing in simple terms', options: LLMGenerationOptions( maxTokens: 200, temperature: 0.7, ), ); setState(() => _response = result.text); print('Speed: ${result.tokensPerSecond.toStringAsFixed(1)} tok/s'); } catch (e) { setState(() => _response = 'Error: $e'); } finally { setState(() => _isLoading = false); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text('RunAnywhere Demo')), body: Padding( padding: EdgeInsets.all(16), child: Column( children: [\ if (!_isModelLoaded)\ ElevatedButton(\ onPressed: _isLoading ? null : _loadModel,\ child: Text(_isLoading ? 'Loading...' : 'Download & Load Model'),\ ),\ if (_isModelLoaded)\ ElevatedButton(\ onPressed: _isLoading ? null : _generateText,\ child: Text(_isLoading ? 'Generating...' : 'Generate'),\ ),\ SizedBox(height: 20),\ Expanded(\ child: SingleChildScrollView(\ child: Text(_response),\ ),\ ),\ ], ), ), ); } } [​](https://docs.runanywhere.ai/flutter/quick-start#step-by-step-breakdown) Step-by-Step Breakdown ----------------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/flutter/quick-start#1-initialize-the-sdk) 1\. Initialize the SDK Copy Ask AI await RunAnywhere.initialize(); Initialize once at app startup. Development mode requires no API key. ### [​](https://docs.runanywhere.ai/flutter/quick-start#2-register-backend-modules) 2\. Register Backend Modules Copy Ask AI await LlamaCpp.register(); // For LLM await Onnx.register(); // For STT/TTS (optional) Register the backends you need. Each backend is a separate package. ### [​](https://docs.runanywhere.ai/flutter/quick-start#3-register-models) 3\. Register Models Copy Ask AI LlamaCpp.addModel( id: 'smollm2-360m-q8_0', name: 'SmolLM2 360M Q8_0', url: 'https://huggingface.co/.../SmolLM2-360M.Q8_0.gguf', memoryRequirement: 500000000, ); Register models with their download URLs. Models are downloaded on-demand. ### [​](https://docs.runanywhere.ai/flutter/quick-start#4-download-&-load-models) 4\. Download & Load Models Copy Ask AI // Download with progress tracking await for (final progress in RunAnywhere.downloadModel('smollm2-360m-q8_0')) { print('${(progress.percentage * 100).toStringAsFixed(1)}%'); if (progress.state.isCompleted) break; } // Load into memory await RunAnywhere.loadModel('smollm2-360m-q8_0'); ### [​](https://docs.runanywhere.ai/flutter/quick-start#5-generate-text) 5\. Generate Text Copy Ask AI // Simple chat final response = await RunAnywhere.chat('Hello!'); // Full generation with metrics final result = await RunAnywhere.generate( 'Your prompt here', options: LLMGenerationOptions(maxTokens: 200), ); print('Response: ${result.text}'); print('Speed: ${result.tokensPerSecond} tok/s'); [​](https://docs.runanywhere.ai/flutter/quick-start#environment-options) Environment Options ----------------------------------------------------------------------------------------------- | Environment | Description | API Key Required | | --- | --- | --- | | `.development` | Verbose logging, local-only | No | | `.staging` | Testing with real services | Yes | | `.production` | Minimal logging, telemetry | Yes | Copy Ask AI // Production initialization await RunAnywhere.initialize( apiKey: 'your-api-key', baseURL: 'https://api.runanywhere.ai', environment: SDKEnvironment.production, ); [​](https://docs.runanywhere.ai/flutter/quick-start#starter-example-repository) Starter Example Repository ------------------------------------------------------------------------------------------------------------- For a complete working application with all features demonstrated, clone our starter example: Copy Ask AI git clone https://github.com/RunanywhereAI/flutter-starter-example.git cd flutter-starter-example flutter pub get cd ios && pod install && cd .. flutter run The [Flutter Starter Example](https://github.com/RunanywhereAI/flutter-starter-example) includes: * AI Chat with streaming responses * Speech-to-Text transcription * Text-to-Speech synthesis * Voice Assistant pipeline * Model download and management UI [​](https://docs.runanywhere.ai/flutter/quick-start#next-steps) Next Steps ----------------------------------------------------------------------------- [LLM Chat\ --------\ \ Simple text generation](https://docs.runanywhere.ai/flutter/llm/chat) [Streaming\ ---------\ \ Real-time token streaming](https://docs.runanywhere.ai/flutter/llm/stream) [Speech-to-Text\ --------------\ \ Audio transcription](https://docs.runanywhere.ai/flutter/stt/transcribe) [Text-to-Speech\ --------------\ \ Voice synthesis](https://docs.runanywhere.ai/flutter/tts/synthesize) [Installation](https://docs.runanywhere.ai/flutter/installation) [chat()](https://docs.runanywhere.ai/flutter/llm/chat) ⌘I --- # Introduction - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/introduction#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Kotlin SDK Introduction On this page * [Overview](https://docs.runanywhere.ai/kotlin/introduction#overview) * [Key Capabilities](https://docs.runanywhere.ai/kotlin/introduction#key-capabilities) * [Core Philosophy](https://docs.runanywhere.ai/kotlin/introduction#core-philosophy) * [Features](https://docs.runanywhere.ai/kotlin/introduction#features) * [Language Models (LLM)](https://docs.runanywhere.ai/kotlin/introduction#language-models-llm) * [Speech-to-Text (STT)](https://docs.runanywhere.ai/kotlin/introduction#speech-to-text-stt) * [Text-to-Speech (TTS)](https://docs.runanywhere.ai/kotlin/introduction#text-to-speech-tts) * [Voice Activity Detection (VAD)](https://docs.runanywhere.ai/kotlin/introduction#voice-activity-detection-vad) * [Voice Agent Pipeline](https://docs.runanywhere.ai/kotlin/introduction#voice-agent-pipeline) * [System Requirements](https://docs.runanywhere.ai/kotlin/introduction#system-requirements) * [SDK Modules](https://docs.runanywhere.ai/kotlin/introduction#sdk-modules) * [Architecture](https://docs.runanywhere.ai/kotlin/introduction#architecture) * [Next Steps](https://docs.runanywhere.ai/kotlin/introduction#next-steps) [​](https://docs.runanywhere.ai/kotlin/introduction#overview) Overview ------------------------------------------------------------------------- The **RunAnywhere Kotlin SDK** is a production-grade, on-device AI SDK for Android. It enables developers to run AI models directly on Android devices without requiring network connectivity for inference, ensuring minimal latency and maximum privacy for your users. The SDK provides a unified interface to multiple AI capabilities: [LLM\ ---\ \ Text generation with streaming support via Kotlin Flows](https://docs.runanywhere.ai/kotlin/llm/chat) [STT\ ---\ \ Speech-to-text transcription with Whisper models](https://docs.runanywhere.ai/kotlin/stt/transcribe) [TTS\ ---\ \ Neural voice synthesis with Sherpa-ONNX](https://docs.runanywhere.ai/kotlin/tts/synthesize) [VAD\ ---\ \ Real-time voice activity detection](https://docs.runanywhere.ai/kotlin/vad) [​](https://docs.runanywhere.ai/kotlin/introduction#key-capabilities) Key Capabilities ----------------------------------------------------------------------------------------- * **Multi-backend architecture** – Choose from LlamaCPP (GGUF models) or ONNX Runtime * **GPU acceleration** – Hardware-accelerated inference on supported devices * **Kotlin-first** – Built with Coroutines and Flows for async operations * **Production-ready** – Built-in analytics, logging, and model lifecycle management [​](https://docs.runanywhere.ai/kotlin/introduction#core-philosophy) Core Philosophy --------------------------------------------------------------------------------------- On-Device First All AI inference runs locally, ensuring low latency and data privacy. Once models are downloaded, no network connection is required for inference. Modular Architecture Backend engines are optional modules—include only what you need. This keeps your APK size minimal. Privacy by Design Audio and text data never leaves the device unless explicitly configured. Only anonymous analytics are collected by default. Platform Parity API mirrors the iOS Swift SDK for consistent cross-platform development. [​](https://docs.runanywhere.ai/kotlin/introduction#features) Features ------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/kotlin/introduction#language-models-llm) Language Models (LLM) * On-device text generation with streaming support * Kotlin Flow-based token streaming * System prompts and customizable generation parameters * Support for thinking/reasoning models * LlamaCPP backend for GGUF models ### [​](https://docs.runanywhere.ai/kotlin/introduction#speech-to-text-stt) Speech-to-Text (STT) * Real-time streaming transcription * Batch audio transcription * Multi-language support * Whisper-based models via ONNX Runtime ### [​](https://docs.runanywhere.ai/kotlin/introduction#text-to-speech-tts) Text-to-Speech (TTS) * Neural voice synthesis with Sherpa-ONNX * System voices via Android TTS * Streaming audio generation for long text * Customizable voice, pitch, rate, and volume ### [​](https://docs.runanywhere.ai/kotlin/introduction#voice-activity-detection-vad) Voice Activity Detection (VAD) * Energy-based speech detection with Silero VAD * Configurable sensitivity thresholds * Real-time audio stream processing ### [​](https://docs.runanywhere.ai/kotlin/introduction#voice-agent-pipeline) Voice Agent Pipeline * Full VAD → STT → LLM → TTS orchestration * Complete voice conversation flow * Streaming and batch processing modes [​](https://docs.runanywhere.ai/kotlin/introduction#system-requirements) System Requirements ----------------------------------------------------------------------------------------------- | Platform | Minimum Version | | --- | --- | | Android | API 24 (7.0+) | **Kotlin:** 2.0+ **Gradle:** 8.0+ ARM64 devices are recommended for best performance. GPU acceleration provides significant speedups on supported devices. [​](https://docs.runanywhere.ai/kotlin/introduction#sdk-modules) SDK Modules ------------------------------------------------------------------------------- | Module | Purpose | | --- | --- | | `runanywhere-core` | Core SDK (required) | | `runanywhere-llamacpp` | LLM text generation with GGUF models | | `runanywhere-onnx` | STT/TTS/VAD via ONNX Runtime | [​](https://docs.runanywhere.ai/kotlin/introduction#architecture) Architecture --------------------------------------------------------------------------------- [​](https://docs.runanywhere.ai/kotlin/introduction#next-steps) Next Steps ----------------------------------------------------------------------------- [Installation\ ------------\ \ Add the SDK to your project via Gradle](https://docs.runanywhere.ai/kotlin/installation) [Quick Start\ -----------\ \ Build your first AI feature in minutes](https://docs.runanywhere.ai/kotlin/quick-start) [Best Practices](https://docs.runanywhere.ai/swift/best-practices) [Installation](https://docs.runanywhere.ai/kotlin/installation) ⌘I --- # transcribe() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/flutter/stt/transcribe#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation STT (Speech-to-Text) transcribe() On this page * [Basic Usage](https://docs.runanywhere.ai/flutter/stt/transcribe#basic-usage) * [With Detailed Result](https://docs.runanywhere.ai/flutter/stt/transcribe#with-detailed-result) * [STTResult](https://docs.runanywhere.ai/flutter/stt/transcribe#sttresult) * [Setup](https://docs.runanywhere.ai/flutter/stt/transcribe#setup) * [1\. Register ONNX Backend](https://docs.runanywhere.ai/flutter/stt/transcribe#1-register-onnx-backend) * [2\. Add STT Model](https://docs.runanywhere.ai/flutter/stt/transcribe#2-add-stt-model) * [3\. Download & Load](https://docs.runanywhere.ai/flutter/stt/transcribe#3-download-%26-load) * [Audio Format Requirements](https://docs.runanywhere.ai/flutter/stt/transcribe#audio-format-requirements) * [Recording Audio](https://docs.runanywhere.ai/flutter/stt/transcribe#recording-audio) * [Available Models](https://docs.runanywhere.ai/flutter/stt/transcribe#available-models) * [Complete Example](https://docs.runanywhere.ai/flutter/stt/transcribe#complete-example) * [See Also](https://docs.runanywhere.ai/flutter/stt/transcribe#see-also) Transcribe audio data to text using on-device Whisper models via ONNX Runtime. [​](https://docs.runanywhere.ai/flutter/stt/transcribe#basic-usage) Basic Usage ---------------------------------------------------------------------------------- Copy Ask AI // Load STT model first await RunAnywhere.loadSTTModel('sherpa-onnx-whisper-tiny.en'); // Transcribe audio data (PCM16 at 16kHz mono) final text = await RunAnywhere.transcribe(audioBytes); print('Transcription: $text'); [​](https://docs.runanywhere.ai/flutter/stt/transcribe#with-detailed-result) With Detailed Result ---------------------------------------------------------------------------------------------------- Get confidence scores and metadata with `transcribeWithResult()`: Copy Ask AI final result = await RunAnywhere.transcribeWithResult(audioBytes); print('Text: ${result.text}'); print('Confidence: ${(result.confidence * 100).toStringAsFixed(1)}%'); print('Duration: ${result.durationMs}ms'); if (result.language != null) { print('Language: ${result.language}'); } [​](https://docs.runanywhere.ai/flutter/stt/transcribe#sttresult) STTResult ------------------------------------------------------------------------------ | Property | Type | Description | | --- | --- | --- | | `text` | `String` | Transcribed text | | `confidence` | `double` | Confidence score (0.0 to 1.0) | | `durationMs` | `int` | Audio duration in milliseconds | | `language` | `String?` | Detected language code | [​](https://docs.runanywhere.ai/flutter/stt/transcribe#setup) Setup ---------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/flutter/stt/transcribe#1-register-onnx-backend) 1\. Register ONNX Backend Copy Ask AI import 'package:runanywhere_onnx/runanywhere_onnx.dart'; await Onnx.register(); ### [​](https://docs.runanywhere.ai/flutter/stt/transcribe#2-add-stt-model) 2\. Add STT Model Copy Ask AI Onnx.addModel( id: 'sherpa-onnx-whisper-tiny.en', name: 'Whisper Tiny English', url: 'https://github.com/RunanywhereAI/sherpa-onnx/releases/download/runanywhere-models-v1/sherpa-onnx-whisper-tiny.en.tar.gz', modality: ModelCategory.speechRecognition, ); ### [​](https://docs.runanywhere.ai/flutter/stt/transcribe#3-download-&-load) 3\. Download & Load Copy Ask AI // Download await for (final progress in RunAnywhere.downloadModel('sherpa-onnx-whisper-tiny.en')) { print('${(progress.percentage * 100).toStringAsFixed(1)}%'); if (progress.state.isCompleted) break; } // Load await RunAnywhere.loadSTTModel('sherpa-onnx-whisper-tiny.en'); [​](https://docs.runanywhere.ai/flutter/stt/transcribe#audio-format-requirements) Audio Format Requirements -------------------------------------------------------------------------------------------------------------- Audio must be in the correct format for accurate transcription. | Property | Required Value | | --- | --- | | Format | PCM (raw audio) | | Sample Rate | 16,000 Hz (16kHz) | | Channels | 1 (mono) | | Bit Depth | 16-bit | [​](https://docs.runanywhere.ai/flutter/stt/transcribe#recording-audio) Recording Audio ------------------------------------------------------------------------------------------ Use a package like `record` to capture audio: Copy Ask AI import 'package:record/record.dart'; final recorder = AudioRecorder(); // Start recording with correct format await recorder.start( const RecordConfig( encoder: AudioEncoder.pcm16bits, sampleRate: 16000, numChannels: 1, ), path: tempFilePath, ); // Stop and get audio await recorder.stop(); final audioBytes = await File(tempFilePath).readAsBytes(); // Transcribe final text = await RunAnywhere.transcribe(audioBytes); [​](https://docs.runanywhere.ai/flutter/stt/transcribe#available-models) Available Models -------------------------------------------------------------------------------------------- | Model ID | Size | Languages | Speed | | --- | --- | --- | --- | | `sherpa-onnx-whisper-tiny.en` | ~75MB | English | Fast | | `sherpa-onnx-whisper-base.en` | ~150MB | English | Medium | | `sherpa-onnx-whisper-small.en` | ~250MB | English | Slower | | `sherpa-onnx-whisper-tiny` | ~75MB | Multilingual | Fast | [​](https://docs.runanywhere.ai/flutter/stt/transcribe#complete-example) Complete Example -------------------------------------------------------------------------------------------- Copy Ask AI class TranscriptionDemo extends StatefulWidget { @override _TranscriptionDemoState createState() => _TranscriptionDemoState(); } class _TranscriptionDemoState extends State { final _recorder = AudioRecorder(); String _transcription = ''; bool _isRecording = false; bool _isTranscribing = false; Future _toggleRecording() async { if (_isRecording) { // Stop and transcribe final path = await _recorder.stop(); if (path != null) { setState(() { _isRecording = false; _isTranscribing = true; }); final audioBytes = await File(path).readAsBytes(); final text = await RunAnywhere.transcribe(audioBytes); setState(() { _transcription = text; _isTranscribing = false; }); } } else { // Start recording if (await _recorder.hasPermission()) { final tempDir = await getTemporaryDirectory(); final path = '${tempDir.path}/recording.pcm'; await _recorder.start( const RecordConfig( encoder: AudioEncoder.pcm16bits, sampleRate: 16000, numChannels: 1, ), path: path, ); setState(() => _isRecording = true); } } } @override Widget build(BuildContext context) { return Column( children: [\ Text(_transcription),\ ElevatedButton(\ onPressed: _isTranscribing ? null : _toggleRecording,\ child: Text(_isRecording ? 'Stop' : 'Record'),\ ),\ if (_isTranscribing) CircularProgressIndicator(),\ ], ); } } [​](https://docs.runanywhere.ai/flutter/stt/transcribe#see-also) See Also ---------------------------------------------------------------------------- [Streaming STT\ -------------\ \ Real-time transcription](https://docs.runanywhere.ai/flutter/stt/stream) [STT Options\ -----------\ \ Configuration options](https://docs.runanywhere.ai/flutter/stt/options) [System Prompts](https://docs.runanywhere.ai/flutter/llm/system-prompts) [Streaming STT](https://docs.runanywhere.ai/flutter/stt/stream) ⌘I --- # Error Handling - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/error-handling#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Kotlin SDK Error Handling On this page * [SDKError](https://docs.runanywhere.ai/kotlin/error-handling#sdkerror) * [Basic Error Handling](https://docs.runanywhere.ai/kotlin/error-handling#basic-error-handling) * [Error Categories](https://docs.runanywhere.ai/kotlin/error-handling#error-categories) * [Error Categories Reference](https://docs.runanywhere.ai/kotlin/error-handling#error-categories-reference) * [Common Error Codes](https://docs.runanywhere.ai/kotlin/error-handling#common-error-codes) * [Error Factory Methods](https://docs.runanywhere.ai/kotlin/error-handling#error-factory-methods) * [Example: Comprehensive Error Handler](https://docs.runanywhere.ai/kotlin/error-handling#example-comprehensive-error-handler) * [Subscribe to Error Events](https://docs.runanywhere.ai/kotlin/error-handling#subscribe-to-error-events) [​](https://docs.runanywhere.ai/kotlin/error-handling#sdkerror) SDKError --------------------------------------------------------------------------- All SDK operations throw `SDKError` for error conditions: Copy Ask AI data class SDKError( val code: ErrorCode, // Specific error type val category: ErrorCategory, // Error group val message: String, // Human-readable message val cause: Throwable? // Underlying exception ) : Exception(message, cause) [​](https://docs.runanywhere.ai/kotlin/error-handling#basic-error-handling) Basic Error Handling --------------------------------------------------------------------------------------------------- Copy Ask AI try { RunAnywhere.loadLLMModel("my-model") val result = RunAnywhere.generate("Hello") } catch (e: SDKError) { when (e.code) { ErrorCode.NOT_INITIALIZED -> { showError("Please restart the app") } ErrorCode.MODEL_NOT_FOUND -> { showError("Model not found. Please download it first.") } ErrorCode.MODEL_LOAD_FAILED -> { showError("Failed to load model: ${e.message}") } ErrorCode.LLM_GENERATION_FAILED -> { showError("Generation failed: ${e.message}") } ErrorCode.INSUFFICIENT_STORAGE -> { showError("Not enough storage space") } else -> { showError(e.message ?: "Unknown error") } } } [​](https://docs.runanywhere.ai/kotlin/error-handling#error-categories) Error Categories ------------------------------------------------------------------------------------------- Handle errors by category for broader matching: Copy Ask AI try { // SDK operations... } catch (e: SDKError) { when (e.category) { ErrorCategory.INITIALIZATION -> { // SDK not properly initialized restartApp() } ErrorCategory.MODEL -> { // Model-related issues promptModelDownload() } ErrorCategory.LLM -> { // Text generation errors retryWithSmallerPrompt() } ErrorCategory.STT -> { // Speech recognition errors checkMicrophonePermission() } ErrorCategory.TTS -> { // Speech synthesis errors checkAudioOutput() } ErrorCategory.NETWORK -> { // Network connectivity issues showOfflineMessage() } ErrorCategory.STORAGE -> { // Storage/file system errors promptStorageCleanup() } else -> { logError(e) showGenericError() } } } [​](https://docs.runanywhere.ai/kotlin/error-handling#error-categories-reference) Error Categories Reference --------------------------------------------------------------------------------------------------------------- | Category | Description | Common Errors | | --- | --- | --- | | `INITIALIZATION` | SDK startup | `NOT_INITIALIZED`, `ALREADY_INITIALIZED` | | `MODEL` | Model operations | `MODEL_NOT_FOUND`, `MODEL_LOAD_FAILED` | | `LLM` | Text generation | `LLM_GENERATION_FAILED` | | `STT` | Speech-to-text | `STT_TRANSCRIPTION_FAILED` | | `TTS` | Text-to-speech | `TTS_SYNTHESIS_FAILED` | | `VAD` | Voice detection | `VAD_DETECTION_FAILED` | | `NETWORK` | Network issues | `NETWORK_UNAVAILABLE`, `TIMEOUT` | | `DOWNLOAD` | Model downloads | `DOWNLOAD_FAILED`, `DOWNLOAD_CANCELLED` | | `STORAGE` | Storage issues | `INSUFFICIENT_STORAGE`, `FILE_NOT_FOUND` | [​](https://docs.runanywhere.ai/kotlin/error-handling#common-error-codes) Common Error Codes ----------------------------------------------------------------------------------------------- Copy Ask AI enum class ErrorCode { // General SUCCESS, UNKNOWN, INVALID_ARGUMENT, // Initialization NOT_INITIALIZED, ALREADY_INITIALIZED, // Model MODEL_NOT_FOUND, MODEL_NOT_LOADED, MODEL_LOAD_FAILED, // LLM LLM_GENERATION_FAILED, // STT STT_TRANSCRIPTION_FAILED, // TTS TTS_SYNTHESIS_FAILED, // VAD VAD_DETECTION_FAILED, // Network NETWORK_ERROR, NETWORK_UNAVAILABLE, TIMEOUT, // Download DOWNLOAD_FAILED, DOWNLOAD_CANCELLED, // Storage INSUFFICIENT_STORAGE, FILE_NOT_FOUND, OUT_OF_MEMORY } [​](https://docs.runanywhere.ai/kotlin/error-handling#error-factory-methods) Error Factory Methods ----------------------------------------------------------------------------------------------------- Create specific errors programmatically: Copy Ask AI // These are used internally by the SDK SDKError.modelNotFound(modelId) SDKError.modelNotLoaded(modelId) SDKError.modelLoadFailed(modelId, reason) SDKError.llmGenerationFailed(reason) SDKError.sttTranscriptionFailed(reason) SDKError.ttsSynthesisFailed(reason) SDKError.networkUnavailable() SDKError.timeout(operation, timeoutMs) SDKError.insufficientStorage(requiredBytes) SDKError.fileNotFound(path) [​](https://docs.runanywhere.ai/kotlin/error-handling#example-comprehensive-error-handler) Example: Comprehensive Error Handler ---------------------------------------------------------------------------------------------------------------------------------- Copy Ask AI class SDKErrorHandler { fun handle(error: SDKError, context: Context) { Log.e("SDK", "Error: ${error.code} - ${error.message}", error.cause) val userMessage = when (error.code) { // Initialization errors ErrorCode.NOT_INITIALIZED -> "The AI system isn't ready yet. Please wait or restart the app." // Model errors ErrorCode.MODEL_NOT_FOUND -> "This model isn't available. Please download it first." ErrorCode.MODEL_LOAD_FAILED -> "Couldn't load the AI model. Try freeing up some memory." // Generation errors ErrorCode.LLM_GENERATION_FAILED -> "Couldn't generate a response. Please try again." ErrorCode.STT_TRANSCRIPTION_FAILED -> "Couldn't understand the audio. Please speak clearly." ErrorCode.TTS_SYNTHESIS_FAILED -> "Couldn't create audio. Please try again." // Network errors ErrorCode.NETWORK_UNAVAILABLE -> "No internet connection. Some features may be limited." ErrorCode.TIMEOUT -> "Request took too long. Please try again." // Download errors ErrorCode.DOWNLOAD_FAILED -> "Download failed. Please check your connection and try again." ErrorCode.DOWNLOAD_CANCELLED -> "Download was cancelled." // Storage errors ErrorCode.INSUFFICIENT_STORAGE -> "Not enough storage space. Free up some space and try again." ErrorCode.OUT_OF_MEMORY -> "Not enough memory. Try closing other apps." else -> "Something went wrong. Please try again." } Toast.makeText(context, userMessage, Toast.LENGTH_LONG).show() } } [​](https://docs.runanywhere.ai/kotlin/error-handling#subscribe-to-error-events) Subscribe to Error Events ------------------------------------------------------------------------------------------------------------- Copy Ask AI lifecycleScope.launch { RunAnywhere.events.errorEvents.collect { errorEvent -> Log.e("SDK", "Error event: ${errorEvent.code} - ${errorEvent.message}") // Handle or report error } } [Configuration](https://docs.runanywhere.ai/kotlin/configuration) [Best Practices](https://docs.runanywhere.ai/kotlin/best-practices) ⌘I --- # chat() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/llm/chat#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation LLM (Language Models) chat() On this page * [When to Use](https://docs.runanywhere.ai/kotlin/llm/chat#when-to-use) * [Example: Simple Q&A](https://docs.runanywhere.ai/kotlin/llm/chat#example-simple-q%26a) * [Example: Chat Bot](https://docs.runanywhere.ai/kotlin/llm/chat#example-chat-bot) The simplest way to generate text—a single function call that returns the response directly. Copy Ask AI // One-liner for quick responses val response = RunAnywhere.chat("What is the capital of France?") println(response) // "The capital of France is Paris." [​](https://docs.runanywhere.ai/kotlin/llm/chat#when-to-use) When to Use --------------------------------------------------------------------------- Use `chat()` when you need: * Quick, simple responses * No metrics or metadata * Minimal code For more control, use [`generate()`](https://docs.runanywhere.ai/kotlin/llm/generate) or [`generateStream()`](https://docs.runanywhere.ai/kotlin/llm/stream) . [​](https://docs.runanywhere.ai/kotlin/llm/chat#example-simple-q&a) Example: Simple Q&A ------------------------------------------------------------------------------------------ Copy Ask AI lifecycleScope.launch { try { val answer = RunAnywhere.chat("Explain machine learning in one sentence") textView.text = answer } catch (e: SDKError) { showError(e.message) } } [​](https://docs.runanywhere.ai/kotlin/llm/chat#example-chat-bot) Example: Chat Bot -------------------------------------------------------------------------------------- Copy Ask AI suspend fun sendMessage(userMessage: String): String { // Ensure model is loaded if (!RunAnywhere.isLLMModelLoaded()) { RunAnywhere.loadLLMModel(modelId) } return RunAnywhere.chat(userMessage) } `chat()` uses default generation options. For custom temperature, max tokens, or system prompts, use [`generate()`](https://docs.runanywhere.ai/kotlin/llm/generate) instead. [Quick Start](https://docs.runanywhere.ai/kotlin/quick-start) [generate()](https://docs.runanywhere.ai/kotlin/llm/generate) ⌘I --- # generate() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/llm/generate#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation LLM (Language Models) generate() On this page * [LLMGenerationResult](https://docs.runanywhere.ai/kotlin/llm/generate#llmgenerationresult) * [LLMGenerationOptions](https://docs.runanywhere.ai/kotlin/llm/generate#llmgenerationoptions) * [Example: Creative Writing](https://docs.runanywhere.ai/kotlin/llm/generate#example-creative-writing) * [Example: Factual Response](https://docs.runanywhere.ai/kotlin/llm/generate#example-factual-response) * [Cancel Generation](https://docs.runanywhere.ai/kotlin/llm/generate#cancel-generation) Use `generate()` for full control over text generation with detailed performance metrics. Copy Ask AI val result = RunAnywhere.generate( prompt = "Write a haiku about Kotlin programming", options = LLMGenerationOptions( maxTokens = 50, temperature = 1.0f, topP = 0.9f, stopSequences = listOf("###") ) ) println("Response: ${result.text}") println("Model: ${result.modelUsed}") println("Tokens: ${result.tokensUsed}") println("Speed: ${result.tokensPerSecond} tok/s") println("Latency: ${result.latencyMs}ms") // For reasoning models (e.g., models with thinking capability) result.thinkingContent?.let { thinking -> println("Reasoning: $thinking") } [​](https://docs.runanywhere.ai/kotlin/llm/generate#llmgenerationresult) LLMGenerationResult ----------------------------------------------------------------------------------------------- The result object contains comprehensive metrics: | Property | Type | Description | | --- | --- | --- | | `text` | `String` | Generated response text | | `thinkingContent` | `String?` | Reasoning content (for thinking models) | | `inputTokens` | `Int` | Number of prompt tokens | | `tokensUsed` | `Int` | Number of output tokens | | `modelUsed` | `String` | Model ID used for generation | | `latencyMs` | `Double` | Total generation time in milliseconds | | `tokensPerSecond` | `Double` | Generation speed | | `timeToFirstTokenMs` | `Double?` | Time to first token (streaming) | | `framework` | `String?` | Inference framework used | [​](https://docs.runanywhere.ai/kotlin/llm/generate#llmgenerationoptions) LLMGenerationOptions ------------------------------------------------------------------------------------------------- Customize generation behavior: Copy Ask AI data class LLMGenerationOptions( val maxTokens: Int = 100, // Maximum tokens to generate val temperature: Float = 0.8f, // Creativity (0.0-2.0) val topP: Float = 1.0f, // Nucleus sampling (0.0-1.0) val stopSequences: List = emptyList(), val streamingEnabled: Boolean = false, val systemPrompt: String? = null // System behavior prompt ) [​](https://docs.runanywhere.ai/kotlin/llm/generate#example-creative-writing) Example: Creative Writing ---------------------------------------------------------------------------------------------------------- Copy Ask AI val story = RunAnywhere.generate( prompt = "Write a short story about a robot learning to paint", options = LLMGenerationOptions( maxTokens = 500, temperature = 1.2f, // Higher = more creative topP = 0.95f ) ) [​](https://docs.runanywhere.ai/kotlin/llm/generate#example-factual-response) Example: Factual Response ---------------------------------------------------------------------------------------------------------- Copy Ask AI val facts = RunAnywhere.generate( prompt = "List the planets in our solar system", options = LLMGenerationOptions( maxTokens = 200, temperature = 0.1f, // Lower = more deterministic topP = 0.5f ) ) [​](https://docs.runanywhere.ai/kotlin/llm/generate#cancel-generation) Cancel Generation ------------------------------------------------------------------------------------------- Cancel an ongoing generation: Copy Ask AI // Start generation in a coroutine val job = lifecycleScope.launch { val result = RunAnywhere.generate(longPrompt, options) } // Cancel if needed cancelButton.setOnClickListener { RunAnywhere.cancelGeneration() job.cancel() } [chat()](https://docs.runanywhere.ai/kotlin/llm/chat) [generateStream()](https://docs.runanywhere.ai/kotlin/llm/stream) ⌘I --- # Introduction - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/react-native/introduction#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation React Native SDK Introduction On this page * [Overview](https://docs.runanywhere.ai/react-native/introduction#overview) * [Key Capabilities](https://docs.runanywhere.ai/react-native/introduction#key-capabilities) * [Core Philosophy](https://docs.runanywhere.ai/react-native/introduction#core-philosophy) * [Features](https://docs.runanywhere.ai/react-native/introduction#features) * [Language Models (LLM)](https://docs.runanywhere.ai/react-native/introduction#language-models-llm) * [Speech-to-Text (STT)](https://docs.runanywhere.ai/react-native/introduction#speech-to-text-stt) * [Text-to-Speech (TTS)](https://docs.runanywhere.ai/react-native/introduction#text-to-speech-tts) * [Voice Activity Detection (VAD)](https://docs.runanywhere.ai/react-native/introduction#voice-activity-detection-vad) * [Voice Agent Pipeline](https://docs.runanywhere.ai/react-native/introduction#voice-agent-pipeline) * [System Requirements](https://docs.runanywhere.ai/react-native/introduction#system-requirements) * [Multi-Package Architecture](https://docs.runanywhere.ai/react-native/introduction#multi-package-architecture) * [Architecture](https://docs.runanywhere.ai/react-native/introduction#architecture) * [Example Apps](https://docs.runanywhere.ai/react-native/introduction#example-apps) * [Next Steps](https://docs.runanywhere.ai/react-native/introduction#next-steps) [​](https://docs.runanywhere.ai/react-native/introduction#overview) Overview ------------------------------------------------------------------------------- The **RunAnywhere React Native SDK** is a production-grade, on-device AI SDK for React Native applications. It enables developers to run AI models directly on iOS and Android devices without requiring network connectivity for inference, ensuring minimal latency and maximum privacy for your users. The SDK provides a unified interface to multiple AI capabilities: [LLM\ ---\ \ Text generation with streaming support via async iterators](https://docs.runanywhere.ai/react-native/llm/chat) [STT\ ---\ \ Speech-to-text transcription with Whisper models](https://docs.runanywhere.ai/react-native/stt/transcribe) [TTS\ ---\ \ Neural voice synthesis with Piper TTS](https://docs.runanywhere.ai/react-native/tts/synthesize) [VAD\ ---\ \ Real-time voice activity detection with Silero VAD](https://docs.runanywhere.ai/react-native/vad) [​](https://docs.runanywhere.ai/react-native/introduction#key-capabilities) Key Capabilities ----------------------------------------------------------------------------------------------- * **Multi-backend architecture** – Choose from LlamaCPP (GGUF models) or ONNX Runtime * **Cross-platform** – Single codebase for iOS and Android * **TypeScript-first** – Full type safety and IDE autocomplete * **Production-ready** – Built-in analytics, logging, and model lifecycle management [​](https://docs.runanywhere.ai/react-native/introduction#core-philosophy) Core Philosophy --------------------------------------------------------------------------------------------- On-Device First All AI inference runs locally, ensuring low latency and data privacy. Once models are downloaded, no network connection is required for inference. Modular Architecture Backend engines are optional packages—include only what you need. This keeps your app bundle size minimal. Privacy by Design Audio and text data never leaves the device unless explicitly configured. Only anonymous analytics are collected by default. Platform Parity API mirrors the iOS Swift SDK and Android Kotlin SDK for consistent cross-platform development. [​](https://docs.runanywhere.ai/react-native/introduction#features) Features ------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/react-native/introduction#language-models-llm) Language Models (LLM) * On-device text generation with streaming support * Async iterator-based token streaming * System prompts and customizable generation parameters * Support for thinking/reasoning models * LlamaCPP backend for GGUF models ### [​](https://docs.runanywhere.ai/react-native/introduction#speech-to-text-stt) Speech-to-Text (STT) * Real-time streaming transcription * Batch audio transcription * Multi-language support * Whisper-based models via ONNX Runtime ### [​](https://docs.runanywhere.ai/react-native/introduction#text-to-speech-tts) Text-to-Speech (TTS) * Neural voice synthesis with Piper TTS * System voices via platform TTS * Streaming audio generation for long text * Customizable voice, pitch, rate, and volume ### [​](https://docs.runanywhere.ai/react-native/introduction#voice-activity-detection-vad) Voice Activity Detection (VAD) * Energy-based speech detection with Silero VAD * Configurable sensitivity thresholds * Real-time audio stream processing ### [​](https://docs.runanywhere.ai/react-native/introduction#voice-agent-pipeline) Voice Agent Pipeline * Full VAD → STT → LLM → TTS orchestration * Complete voice conversation flow * Push-to-talk and hands-free modes [​](https://docs.runanywhere.ai/react-native/introduction#system-requirements) System Requirements ----------------------------------------------------------------------------------------------------- | Platform | Minimum Version | | --- | --- | | React Native | 0.74+ | | iOS | 15.1+ | | Android | API 24 (7.0+) | **Node.js:** 18+ **TypeScript:** 5.0+ (recommended) Apple Silicon devices (M1/M2/M3, A14+) and Android devices with 6GB+ RAM are recommended. Metal GPU acceleration provides 3-5x speedup on iOS. [​](https://docs.runanywhere.ai/react-native/introduction#multi-package-architecture) Multi-Package Architecture ------------------------------------------------------------------------------------------------------------------- | Package | Purpose | | --- | --- | | `@runanywhere/core` | Core SDK (required) | | `@runanywhere/llamacpp` | LLM text generation with GGUF models | | `@runanywhere/onnx` | STT/TTS/VAD via ONNX Runtime | [​](https://docs.runanywhere.ai/react-native/introduction#architecture) Architecture --------------------------------------------------------------------------------------- [​](https://docs.runanywhere.ai/react-native/introduction#example-apps) Example Apps --------------------------------------------------------------------------------------- Working example apps to help you get started: * [**React Native Starter App**](https://github.com/RunanywhereAI/react-native-starter-app) – Bare React Native CLI app with Chat, STT, TTS, and Voice Pipeline demos * [**Monorepo Example**](https://github.com/RunanywhereAI/runanywhere-sdks/tree/main/examples/react-native/RunAnywhereAI) – Full-featured reference app from the SDK repository [​](https://docs.runanywhere.ai/react-native/introduction#next-steps) Next Steps ----------------------------------------------------------------------------------- [Installation\ ------------\ \ Add the SDK to your project via npm](https://docs.runanywhere.ai/react-native/installation) [Quick Start\ -----------\ \ Build your first AI feature in minutes](https://docs.runanywhere.ai/react-native/quick-start) [Best Practices](https://docs.runanywhere.ai/kotlin/best-practices) [Installation](https://docs.runanywhere.ai/react-native/installation) ⌘I --- # Installation - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/swift/installation#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Swift SDK Installation On this page * [Swift Package Manager (Xcode)](https://docs.runanywhere.ai/swift/installation#swift-package-manager-xcode) * [Package.swift](https://docs.runanywhere.ai/swift/installation#package-swift) * [Available Products](https://docs.runanywhere.ai/swift/installation#available-products) * [Binary Size Impact](https://docs.runanywhere.ai/swift/installation#binary-size-impact) * [Verify Installation](https://docs.runanywhere.ai/swift/installation#verify-installation) * [Troubleshooting](https://docs.runanywhere.ai/swift/installation#troubleshooting) * [Next Steps](https://docs.runanywhere.ai/swift/installation#next-steps) [​](https://docs.runanywhere.ai/swift/installation#swift-package-manager-xcode) Swift Package Manager (Xcode) ---------------------------------------------------------------------------------------------------------------- 1 [](https://docs.runanywhere.ai/swift/installation#) Open your project Open your project in Xcode 2 [](https://docs.runanywhere.ai/swift/installation#) Add package dependency Go to **File → Add Package Dependencies…** 3 [](https://docs.runanywhere.ai/swift/installation#) Enter repository URL Enter the repository URL: `https://github.com/RunanywhereAI/runanywhere-sdks` 4 [](https://docs.runanywhere.ai/swift/installation#) Select version Select the version (e.g., `from: "0.16.0"`) 5 [](https://docs.runanywhere.ai/swift/installation#) Choose products Choose the products you need: - **RunAnywhere** (required) – Core SDK - **RunAnywhereLlamaCPP** – LLM text generation with GGUF models - **RunAnywhereONNX** – ONNX Runtime for STT/TTS/VAD [​](https://docs.runanywhere.ai/swift/installation#package-swift) Package.swift ---------------------------------------------------------------------------------- For Swift packages, add the dependency directly to your `Package.swift`: Package.swift Copy Ask AI dependencies: [\ .package(url: "https://github.com/RunanywhereAI/runanywhere-sdks", from: "0.16.0")\ ] Then add the products you need to your target dependencies: Package.swift Copy Ask AI targets: [\ .target(\ name: "YourApp",\ dependencies: [\ .product(name: "RunAnywhere", package: "runanywhere-sdks"),\ .product(name: "RunAnywhereLlamaCPP", package: "runanywhere-sdks"),\ .product(name: "RunAnywhereONNX", package: "runanywhere-sdks"),\ ]\ )\ ] [​](https://docs.runanywhere.ai/swift/installation#available-products) Available Products -------------------------------------------------------------------------------------------- | Product | Description | | --- | --- | | `RunAnywhere` | Core SDK (required for all features) | | `RunAnywhereLlamaCPP` | LLM capability with GGUF models | | `RunAnywhereONNX` | STT, TTS, and VAD via ONNX Runtime | Only include the products you need to minimize your app’s binary size. The modular architecture means you can add capabilities incrementally. [​](https://docs.runanywhere.ai/swift/installation#binary-size-impact) Binary Size Impact -------------------------------------------------------------------------------------------- | Configuration | Approximate Size | | --- | --- | | LLM only | ~17 MB | | STT only (ONNX) | ~52 MB | | LLM + STT + TTS | ~87 MB | | Full (all backends) | ~95 MB | [​](https://docs.runanywhere.ai/swift/installation#verify-installation) Verify Installation ---------------------------------------------------------------------------------------------- After installation, verify everything is working: Copy Ask AI import RunAnywhere // Check SDK version print("SDK Version: \(RunAnywhere.version)") [​](https://docs.runanywhere.ai/swift/installation#troubleshooting) Troubleshooting -------------------------------------------------------------------------------------- Package resolution fails Try resetting package caches: 1. Go to **File → Packages → Reset Package Caches** 2. Clean the build folder: **Product → Clean Build Folder** 3. Try adding the package again Module not found errors Ensure you’ve added the correct product to your target’s dependencies. Each module must be explicitly added. Linker errors with XCFrameworks If you encounter linker errors, ensure your deployment target meets the minimum requirements: - iOS 17.0+ - macOS 14.0+ [​](https://docs.runanywhere.ai/swift/installation#next-steps) Next Steps ---------------------------------------------------------------------------- [Quick Start\ -----------\ \ Build your first AI feature →](https://docs.runanywhere.ai/swift/quick-start) [Introduction](https://docs.runanywhere.ai/swift/introduction) [Quick Start](https://docs.runanywhere.ai/swift/quick-start) ⌘I --- # Best Practices - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/best-practices#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Kotlin SDK Best Practices On this page * [Memory Management](https://docs.runanywhere.ai/kotlin/best-practices#memory-management) * [Load Only What You Need](https://docs.runanywhere.ai/kotlin/best-practices#load-only-what-you-need) * [Unload When Not Needed](https://docs.runanywhere.ai/kotlin/best-practices#unload-when-not-needed) * [Monitor Memory Before Loading](https://docs.runanywhere.ai/kotlin/best-practices#monitor-memory-before-loading) * [Performance Optimization](https://docs.runanywhere.ai/kotlin/best-practices#performance-optimization) * [Use Quantized Models](https://docs.runanywhere.ai/kotlin/best-practices#use-quantized-models) * [Use Streaming for Better UX](https://docs.runanywhere.ai/kotlin/best-practices#use-streaming-for-better-ux) * [Set Appropriate Token Limits](https://docs.runanywhere.ai/kotlin/best-practices#set-appropriate-token-limits) * [App Lifecycle](https://docs.runanywhere.ai/kotlin/best-practices#app-lifecycle) * [Handle Background/Foreground](https://docs.runanywhere.ai/kotlin/best-practices#handle-background%2Fforeground) * [Preload Models at Launch](https://docs.runanywhere.ai/kotlin/best-practices#preload-models-at-launch) * [Error Handling](https://docs.runanywhere.ai/kotlin/best-practices#error-handling) * [Always Handle Errors](https://docs.runanywhere.ai/kotlin/best-practices#always-handle-errors) * [Provide User Feedback](https://docs.runanywhere.ai/kotlin/best-practices#provide-user-feedback) * [Testing](https://docs.runanywhere.ai/kotlin/best-practices#testing) * [Test on Real Devices](https://docs.runanywhere.ai/kotlin/best-practices#test-on-real-devices) * [Measure Performance](https://docs.runanywhere.ai/kotlin/best-practices#measure-performance) * [Security](https://docs.runanywhere.ai/kotlin/best-practices#security) * [Protect API Keys](https://docs.runanywhere.ai/kotlin/best-practices#protect-api-keys) * [Clear Sensitive Data](https://docs.runanywhere.ai/kotlin/best-practices#clear-sensitive-data) * [Summary Checklist](https://docs.runanywhere.ai/kotlin/best-practices#summary-checklist) [​](https://docs.runanywhere.ai/kotlin/best-practices#memory-management) Memory Management --------------------------------------------------------------------------------------------- On-device AI models are memory-intensive. Proper memory management is critical for app stability. ### [​](https://docs.runanywhere.ai/kotlin/best-practices#load-only-what-you-need) Load Only What You Need Copy Ask AI // ❌ Don't load multiple large models RunAnywhere.loadLLMModel("model-3b") RunAnywhere.loadSTTModel("whisper-large") // ✅ Load one LLM at a time, use smaller models RunAnywhere.loadLLMModel("model-0.5b") ### [​](https://docs.runanywhere.ai/kotlin/best-practices#unload-when-not-needed) Unload When Not Needed Copy Ask AI // Unload models when switching tasks or backgrounding override fun onStop() { super.onStop() lifecycleScope.launch { RunAnywhere.unloadLLMModel() RunAnywhere.unloadSTTModel() } } ### [​](https://docs.runanywhere.ai/kotlin/best-practices#monitor-memory-before-loading) Monitor Memory Before Loading Copy Ask AI val modelInfo = RunAnywhere.model(modelId) val requiredMemory = modelInfo?.downloadSize ?: 0 val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager val memoryInfo = ActivityManager.MemoryInfo() activityManager.getMemoryInfo(memoryInfo) if (memoryInfo.availMem < requiredMemory * 1.5) { showWarning("Low memory - performance may be affected") } [​](https://docs.runanywhere.ai/kotlin/best-practices#performance-optimization) Performance Optimization ----------------------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/kotlin/best-practices#use-quantized-models) Use Quantized Models | Model Type | Size | Performance | Quality | | --- | --- | --- | --- | | Q8 (8-bit) | Larger | Slower | Best | | Q4 (4-bit) | Smaller | Faster | Good | | Q2 (2-bit) | Smallest | Fastest | Acceptable | Copy Ask AI // ✅ Use Q4 models for mobile devices val model = RunAnywhere.registerModel( name = "Qwen 0.5B Q4", url = "...qwen2.5-0.5b-instruct-q4_0.gguf", framework = InferenceFramework.LLAMA_CPP ) ### [​](https://docs.runanywhere.ai/kotlin/best-practices#use-streaming-for-better-ux) Use Streaming for Better UX Copy Ask AI // ✅ Stream tokens for perceived faster responses RunAnywhere.generateStream(prompt) .collect { token -> textView.append(token) } // ❌ Waiting for full response feels slow val result = RunAnywhere.generate(prompt) textView.text = result.text ### [​](https://docs.runanywhere.ai/kotlin/best-practices#set-appropriate-token-limits) Set Appropriate Token Limits Copy Ask AI // ✅ Match maxTokens to your use case val shortAnswer = LLMGenerationOptions(maxTokens = 50) // Quick Q&A val mediumAnswer = LLMGenerationOptions(maxTokens = 200) // General chat val longForm = LLMGenerationOptions(maxTokens = 500) // Stories/articles [​](https://docs.runanywhere.ai/kotlin/best-practices#app-lifecycle) App Lifecycle ------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/kotlin/best-practices#handle-background/foreground) Handle Background/Foreground Copy Ask AI class MyApplication : Application(), LifecycleEventObserver { override fun onCreate() { super.onCreate() ProcessLifecycleOwner.get().lifecycle.addObserver(this) RunAnywhere.initialize(environment = SDKEnvironment.PRODUCTION) } override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { when (event) { Lifecycle.Event.ON_STOP -> { // App backgrounded - release resources CoroutineScope(Dispatchers.Main).launch { RunAnywhere.stopVoiceSession() RunAnywhere.cleanup() } } Lifecycle.Event.ON_START -> { // App foregrounded - reinitialize if needed } else -> {} } } } ### [​](https://docs.runanywhere.ai/kotlin/best-practices#preload-models-at-launch) Preload Models at Launch Copy Ask AI class SplashActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycleScope.launch { // Show loading UI showLoading() // Preload commonly used models val models = listOf("qwen-0.5b", "whisper-tiny") models.forEach { modelId -> if (!RunAnywhere.isModelDownloaded(modelId)) { RunAnywhere.downloadModel(modelId).collect { progress -> updateProgress(modelId, progress.progress) } } } // Pre-load the primary model RunAnywhere.loadLLMModel("qwen-0.5b") // Navigate to main screen startActivity(Intent(this@SplashActivity, MainActivity::class.java)) finish() } } } [​](https://docs.runanywhere.ai/kotlin/best-practices#error-handling) Error Handling --------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/kotlin/best-practices#always-handle-errors) Always Handle Errors Copy Ask AI // ✅ Comprehensive error handling lifecycleScope.launch { try { val result = RunAnywhere.generate(prompt) showResponse(result.text) } catch (e: SDKError) { when (e.category) { ErrorCategory.MODEL -> promptModelDownload() ErrorCategory.STORAGE -> promptStorageCleanup() else -> showGenericError(e.message) } } } ### [​](https://docs.runanywhere.ai/kotlin/best-practices#provide-user-feedback) Provide User Feedback Copy Ask AI // ✅ Show meaningful progress RunAnywhere.downloadModel(modelId).collect { progress -> when (progress.state) { DownloadState.DOWNLOADING -> { progressBar.progress = (progress.progress * 100).toInt() statusText.text = "Downloading AI model..." } DownloadState.EXTRACTING -> { statusText.text = "Preparing model..." } DownloadState.COMPLETED -> { statusText.text = "Ready!" } DownloadState.ERROR -> { showError("Download failed: ${progress.error}") } } } [​](https://docs.runanywhere.ai/kotlin/best-practices#testing) Testing ------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/kotlin/best-practices#test-on-real-devices) Test on Real Devices Copy Ask AI // Simulators don't accurately reflect: // - Memory constraints // - CPU performance // - Thermal throttling // Always test on physical devices before release ### [​](https://docs.runanywhere.ai/kotlin/best-practices#measure-performance) Measure Performance Copy Ask AI val result = RunAnywhere.generate(prompt, options) Log.d("Performance", """ Model: ${result.modelUsed} Tokens: ${result.tokensUsed} Speed: ${result.tokensPerSecond} tok/s Latency: ${result.latencyMs}ms TTFT: ${result.timeToFirstTokenMs}ms """.trimIndent()) [​](https://docs.runanywhere.ai/kotlin/best-practices#security) Security --------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/kotlin/best-practices#protect-api-keys) Protect API Keys Copy Ask AI // ❌ Don't hardcode API keys RunAnywhere.initialize(apiKey = "sk-12345...") // ✅ Use BuildConfig or secure storage RunAnywhere.initialize(apiKey = BuildConfig.RUNANYWHERE_API_KEY) ### [​](https://docs.runanywhere.ai/kotlin/best-practices#clear-sensitive-data) Clear Sensitive Data Copy Ask AI // Clear conversation history when appropriate RunAnywhere.clearVoiceConversation() // Reset SDK to clear all state RunAnywhere.reset() [​](https://docs.runanywhere.ai/kotlin/best-practices#summary-checklist) Summary Checklist --------------------------------------------------------------------------------------------- * [ ] Use quantized models (Q4) for mobile devices * [ ] Unload models when backgrounding the app * [ ] Use streaming for long text generation * [ ] Handle all error categories appropriately * [ ] Test on physical devices, not simulators * [ ] Preload commonly used models at app startup * [ ] Monitor memory before loading large models * [ ] Secure API keys using BuildConfig or secure storage [Error Handling](https://docs.runanywhere.ai/kotlin/error-handling) [Introduction](https://docs.runanywhere.ai/react-native/introduction) ⌘I --- # Streaming TTS - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/tts/stream#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation TTS (Text-to-Speech) Streaming TTS On this page * [Streaming Synthesis](https://docs.runanywhere.ai/kotlin/tts/stream#streaming-synthesis) * [Example: Streaming Audio Player](https://docs.runanywhere.ai/kotlin/tts/stream#example-streaming-audio-player) * [Example: Chat Response with Streaming TTS](https://docs.runanywhere.ai/kotlin/tts/stream#example-chat-response-with-streaming-tts) * [Stop Synthesis](https://docs.runanywhere.ai/kotlin/tts/stream#stop-synthesis) * [When to Use Streaming](https://docs.runanywhere.ai/kotlin/tts/stream#when-to-use-streaming) * [Performance Characteristics](https://docs.runanywhere.ai/kotlin/tts/stream#performance-characteristics) Stream audio chunks as they are synthesized, enabling playback to start before the full synthesis completes. [​](https://docs.runanywhere.ai/kotlin/tts/stream#streaming-synthesis) Streaming Synthesis --------------------------------------------------------------------------------------------- Copy Ask AI val longText = """ This is a very long text that will be synthesized in chunks. Each chunk will be delivered as soon as it's ready, allowing playback to start immediately without waiting for the entire synthesis to complete. """.trimIndent() RunAnywhere.synthesizeStream( text = longText, options = TTSOptions(rate = 1.0f), onAudioChunk = { chunk -> // Play each chunk as it arrives audioPlayer.enqueue(chunk) } ) [​](https://docs.runanywhere.ai/kotlin/tts/stream#example-streaming-audio-player) Example: Streaming Audio Player -------------------------------------------------------------------------------------------------------------------- Copy Ask AI class StreamingAudioPlayer { private val audioQueue = ConcurrentLinkedQueue() private var isPlaying = false fun enqueue(audioChunk: ByteArray) { audioQueue.add(audioChunk) if (!isPlaying) { startPlayback() } } private fun startPlayback() { isPlaying = true CoroutineScope(Dispatchers.IO).launch { while (audioQueue.isNotEmpty() || isPlaying) { val chunk = audioQueue.poll() if (chunk != null) { playChunk(chunk) } else { delay(10) // Wait for more chunks } } } } private fun playChunk(chunk: ByteArray) { // Play audio chunk using AudioTrack } fun stop() { isPlaying = false audioQueue.clear() } } [​](https://docs.runanywhere.ai/kotlin/tts/stream#example-chat-response-with-streaming-tts) Example: Chat Response with Streaming TTS ---------------------------------------------------------------------------------------------------------------------------------------- Copy Ask AI class ChatViewModel : ViewModel() { private val audioPlayer = StreamingAudioPlayer() fun sendMessageAndSpeak(prompt: String) { viewModelScope.launch { // Generate text with streaming val streamResult = RunAnywhere.generateStreamWithMetrics(prompt) // Collect full response for TTS val fullResponse = StringBuilder() streamResult.stream.collect { token -> fullResponse.append(token) _displayText.value += token } // Stream synthesize the full response RunAnywhere.synthesizeStream( text = fullResponse.toString(), options = TTSOptions(), onAudioChunk = { chunk -> audioPlayer.enqueue(chunk) } ) } } } [​](https://docs.runanywhere.ai/kotlin/tts/stream#stop-synthesis) Stop Synthesis ----------------------------------------------------------------------------------- Cancel ongoing synthesis: Copy Ask AI // Stop synthesis mid-stream RunAnywhere.stopSynthesis() [​](https://docs.runanywhere.ai/kotlin/tts/stream#when-to-use-streaming) When to Use Streaming ------------------------------------------------------------------------------------------------- | Scenario | Recommended | | --- | --- | | Short text (under 100 chars) | `synthesize()` | | Long text (over 200 chars) | `synthesizeStream()` | | Real-time chat responses | `synthesizeStream()` | | Pre-cached audio | `synthesize()` | Streaming synthesis reduces time-to-first-audio for long text: - **Regular synthesis**: Wait for full synthesis, then play - **Streaming synthesis**: Start playing after first chunk (~100ms) [​](https://docs.runanywhere.ai/kotlin/tts/stream#performance-characteristics) Performance Characteristics ------------------------------------------------------------------------------------------------------------- | Text Length | Regular Synthesis | Streaming First Audio | | --- | --- | --- | | 50 chars | ~100ms | ~100ms | | 200 chars | ~400ms | ~100ms | | 500 chars | ~1000ms | ~100ms | | 1000 chars | ~2000ms | ~100ms | [synthesize()](https://docs.runanywhere.ai/kotlin/tts/synthesize) [Voices](https://docs.runanywhere.ai/kotlin/tts/voices) ⌘I --- # SDK Overview - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/sdks#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Getting Started SDK Overview On this page * [Available SDKs](https://docs.runanywhere.ai/sdks#available-sdks) * [Feature Comparison](https://docs.runanywhere.ai/sdks#feature-comparison) * [Choosing the Right SDK](https://docs.runanywhere.ai/sdks#choosing-the-right-sdk) [​](https://docs.runanywhere.ai/sdks#available-sdks) Available SDKs ---------------------------------------------------------------------- All RunAnywhere SDKs provide the same core AI capabilities with platform-native APIs. Choose the SDK that matches your development stack. * Swift (Apple) * Kotlin (Android) * React Native * Flutter [Swift SDK\ ---------\ \ Production-grade, on-device AI for Apple platforms](https://docs.runanywhere.ai/swift/introduction) ### [​](https://docs.runanywhere.ai/sdks#platform-support) Platform Support | Platform | Minimum Version | | --- | --- | | iOS | 17.0+ | | macOS | 14.0+ | | tvOS | 17.0+ | | watchOS | 10.0+ | ### [​](https://docs.runanywhere.ai/sdks#requirements) Requirements * **Swift:** 5.9+ * **Xcode:** 15.2+ ### [​](https://docs.runanywhere.ai/sdks#key-features) Key Features * Metal acceleration on Apple Silicon * LlamaCPP backend for GGUF models * ONNX Runtime for STT/TTS/VAD * Apple Foundation Models support (iOS 26+) [Installation\ ------------\ \ Add via Swift Package Manager](https://docs.runanywhere.ai/swift/installation) [Quick Start\ -----------\ \ Build your first AI feature](https://docs.runanywhere.ai/swift/quick-start) [Kotlin SDK\ ----------\ \ Production-grade, on-device AI for Android](https://docs.runanywhere.ai/kotlin/introduction) ### [​](https://docs.runanywhere.ai/sdks#platform-support-2) Platform Support | Platform | Minimum Version | | --- | --- | | Android | API 24+ (7.0+) | ### [​](https://docs.runanywhere.ai/sdks#requirements-2) Requirements * **Kotlin:** 2.0+ * **Gradle:** 8.0+ ### [​](https://docs.runanywhere.ai/sdks#key-features-2) Key Features * GPU acceleration support * Coroutines-based async API * LlamaCPP backend for GGUF models * ONNX Runtime for STT/TTS/VAD [Installation\ ------------\ \ Add via Gradle](https://docs.runanywhere.ai/kotlin/installation) [Quick Start\ -----------\ \ Build your first AI feature](https://docs.runanywhere.ai/kotlin/quick-start) [React Native SDK\ ----------------\ \ Cross-platform on-device AI with TypeScript](https://docs.runanywhere.ai/react-native/introduction) ### [​](https://docs.runanywhere.ai/sdks#platform-support-3) Platform Support | Platform | Minimum Version | | --- | --- | | iOS | 15.1+ | | Android | API 24+ (7.0+) | ### [​](https://docs.runanywhere.ai/sdks#requirements-3) Requirements * **React Native:** 0.71+ (recommended 0.74+) * **TypeScript:** 5.0+ ### [​](https://docs.runanywhere.ai/sdks#key-features-3) Key Features * TypeScript-first with full type safety * Single codebase for iOS and Android * TurboModules for optimal performance * LlamaCPP and ONNX backends [Installation\ ------------\ \ Add via npm/yarn](https://docs.runanywhere.ai/react-native/installation) [Quick Start\ -----------\ \ Build your first AI feature](https://docs.runanywhere.ai/react-native/quick-start) [Flutter SDK\ -----------\ \ Cross-platform on-device AI with Dart](https://docs.runanywhere.ai/flutter/introduction) ### [​](https://docs.runanywhere.ai/sdks#platform-support-4) Platform Support | Platform | Minimum Version | | --- | --- | | iOS | 14.0+ | | Android | API 24+ (7.0+) | ### [​](https://docs.runanywhere.ai/sdks#requirements-4) Requirements * **Flutter:** 3.10+ * **Dart:** 3.0+ ### [​](https://docs.runanywhere.ai/sdks#key-features-4) Key Features * Dart-native async/await API * Single codebase for iOS and Android * Platform channels for native performance * LlamaCPP and ONNX backends [Installation\ ------------\ \ Add via pub.dev](https://docs.runanywhere.ai/flutter/installation) [Quick Start\ -----------\ \ Build your first AI feature](https://docs.runanywhere.ai/flutter/quick-start) * * * [​](https://docs.runanywhere.ai/sdks#feature-comparison) Feature Comparison ------------------------------------------------------------------------------ All SDKs have **feature parity** and provide the same core capabilities: | Feature | Swift | Kotlin | React Native | Flutter | | --- | --- | --- | --- | --- | | **LLM (Text Generation)** | | | | | | **STT (Speech-to-Text)** | | | | | | **TTS (Text-to-Speech)** | | | | | | **VAD (Voice Detection)** | | | | | | **Voice Agent Pipeline** | | | | | | **Streaming Support** | | | | | | **Offline Capable** | | | | | | **GPU Acceleration** | Metal | GPU | Native | Native | * * * [​](https://docs.runanywhere.ai/sdks#choosing-the-right-sdk) Choosing the Right SDK -------------------------------------------------------------------------------------- Building a native iOS/macOS app? Use the **Swift SDK** for the best performance and access to Apple-specific features like Metal acceleration and Apple Foundation Models.[Get Started with Swift\ ----------------------](https://docs.runanywhere.ai/swift/introduction) Building a native Android app? Use the **Kotlin SDK** for native Android performance with Coroutines-based async APIs and GPU acceleration.[Get Started with Kotlin\ -----------------------](https://docs.runanywhere.ai/kotlin/introduction) Building a cross-platform app with JavaScript/TypeScript? Use the **React Native SDK** if your team is already using React Native. Get full type safety with TypeScript and a single codebase.[Get Started with React Native\ -----------------------------](https://docs.runanywhere.ai/react-native/introduction) Building a cross-platform app with Flutter/Dart? Use the **Flutter SDK** if your team is already using Flutter. Get native Dart APIs with async/await patterns.[Get Started with Flutter\ ------------------------](https://docs.runanywhere.ai/flutter/introduction) **Not sure which to choose?** All SDKs have feature parity. Pick the one that matches your existing tech stack for the smoothest integration. [Quick Start](https://docs.runanywhere.ai/quickstart) [Introduction](https://docs.runanywhere.ai/swift/introduction) ⌘I --- # System Prompts - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/llm/system-prompts#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation LLM (Language Models) System Prompts On this page * [Basic Usage](https://docs.runanywhere.ai/kotlin/llm/system-prompts#basic-usage) * [Example: Code Assistant](https://docs.runanywhere.ai/kotlin/llm/system-prompts#example-code-assistant) * [Example: Customer Support Bot](https://docs.runanywhere.ai/kotlin/llm/system-prompts#example-customer-support-bot) * [Example: Creative Writer](https://docs.runanywhere.ai/kotlin/llm/system-prompts#example-creative-writer) * [Example: JSON Output](https://docs.runanywhere.ai/kotlin/llm/system-prompts#example-json-output) * [Best Practices](https://docs.runanywhere.ai/kotlin/llm/system-prompts#best-practices) System prompts define how the model should behave, respond, and what role it should assume. [​](https://docs.runanywhere.ai/kotlin/llm/system-prompts#basic-usage) Basic Usage ------------------------------------------------------------------------------------- Copy Ask AI val options = LLMGenerationOptions( maxTokens = 200, systemPrompt = """ You are a senior Kotlin developer. Answer questions with code examples. Use modern Kotlin conventions and coroutines. """.trimIndent() ) val result = RunAnywhere.generate( prompt = "How do I make an HTTP request?", options = options ) [​](https://docs.runanywhere.ai/kotlin/llm/system-prompts#example-code-assistant) Example: Code Assistant ------------------------------------------------------------------------------------------------------------ Copy Ask AI val codeAssistant = LLMGenerationOptions( maxTokens = 500, temperature = 0.3f, // Lower for more precise code systemPrompt = """ You are an expert Android developer assistant. - Always provide working Kotlin code examples - Use Jetpack libraries when appropriate - Follow Material Design guidelines for UI code - Include error handling in your examples - Keep explanations concise """.trimIndent() ) val result = RunAnywhere.generate( prompt = "How do I implement a RecyclerView with DiffUtil?", options = codeAssistant ) [​](https://docs.runanywhere.ai/kotlin/llm/system-prompts#example-customer-support-bot) Example: Customer Support Bot ------------------------------------------------------------------------------------------------------------------------ Copy Ask AI val supportBot = LLMGenerationOptions( maxTokens = 300, temperature = 0.7f, systemPrompt = """ You are a friendly customer support assistant for TechCorp. Guidelines: - Be helpful, patient, and empathetic - Keep responses under 3 paragraphs - If you don't know something, say so - Never make up product features - End with asking if there's anything else you can help with """.trimIndent() ) [​](https://docs.runanywhere.ai/kotlin/llm/system-prompts#example-creative-writer) Example: Creative Writer -------------------------------------------------------------------------------------------------------------- Copy Ask AI val creativeWriter = LLMGenerationOptions( maxTokens = 1000, temperature = 1.2f, // Higher for creativity topP = 0.95f, systemPrompt = """ You are a creative fiction writer with a vivid imagination. Write engaging stories with: - Rich character development - Descriptive settings - Unexpected plot twists - Emotional depth """.trimIndent() ) [​](https://docs.runanywhere.ai/kotlin/llm/system-prompts#example-json-output) Example: JSON Output ------------------------------------------------------------------------------------------------------ Copy Ask AI val jsonFormatter = LLMGenerationOptions( maxTokens = 500, temperature = 0.1f, // Very low for consistent structure systemPrompt = """ You are a data extraction assistant. Always respond with valid JSON only. Do not include any text outside the JSON object. Use this schema: {"name": string, "category": string, "confidence": number} """.trimIndent() ) val result = RunAnywhere.generate( prompt = "Extract product info: 'iPhone 15 Pro Max 256GB Space Black'", options = jsonFormatter ) // Result: {"name": "iPhone 15 Pro Max", "category": "smartphone", "confidence": 0.95} [​](https://docs.runanywhere.ai/kotlin/llm/system-prompts#best-practices) Best Practices ------------------------------------------------------------------------------------------- **Keep system prompts focused and specific:** - Define the role clearly - Set boundaries on what the model should/shouldn’t do - Specify output format if needed - Include examples for complex tasks | Goal | Temperature | System Prompt Style | | --- | --- | --- | | Code generation | 0.1-0.4 | Precise, technical instructions | | Creative writing | 0.9-1.3 | Open-ended, encourage creativity | | Factual Q&A | 0.2-0.5 | Focus on accuracy, cite limitations | | Conversation | 0.6-0.8 | Personality traits, response guidelines | [generateStream()](https://docs.runanywhere.ai/kotlin/llm/stream) [transcribe()](https://docs.runanywhere.ai/kotlin/stt/transcribe) ⌘I --- # Streaming STT - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/stt/stream#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation STT (Speech-to-Text) Streaming STT On this page * [Streaming Transcription](https://docs.runanywhere.ai/kotlin/stt/stream#streaming-transcription) * [Real-Time Microphone Transcription](https://docs.runanywhere.ai/kotlin/stt/stream#real-time-microphone-transcription) * [Stream Audio Samples](https://docs.runanywhere.ai/kotlin/stt/stream#stream-audio-samples) * [Subscribe to STT Events](https://docs.runanywhere.ai/kotlin/stt/stream#subscribe-to-stt-events) * [Example: Voice Search](https://docs.runanywhere.ai/kotlin/stt/stream#example-voice-search) * [Performance Tips](https://docs.runanywhere.ai/kotlin/stt/stream#performance-tips) Stream transcription results as audio is being processed, providing real-time feedback for voice interfaces. [​](https://docs.runanywhere.ai/kotlin/stt/stream#streaming-transcription) Streaming Transcription ----------------------------------------------------------------------------------------------------- Copy Ask AI val audioData = // ... recorded audio bytes RunAnywhere.transcribeStream( audioData = audioData, options = STTOptions(language = "en"), onPartialResult = { partial -> // Update UI with partial transcription transcriptionTextView.text = partial.transcript } ) [​](https://docs.runanywhere.ai/kotlin/stt/stream#real-time-microphone-transcription) Real-Time Microphone Transcription --------------------------------------------------------------------------------------------------------------------------- Copy Ask AI class LiveTranscriptionViewModel : ViewModel() { private val _partialText = MutableStateFlow("") val partialText: StateFlow = _partialText private val _finalText = MutableStateFlow("") val finalText: StateFlow = _finalText fun processAudioSamples(samples: FloatArray) { viewModelScope.launch { // Process streaming audio samples RunAnywhere.processStreamingAudio(samples) } } fun stopTranscription() { viewModelScope.launch { RunAnywhere.stopStreamingTranscription() } } } [​](https://docs.runanywhere.ai/kotlin/stt/stream#stream-audio-samples) Stream Audio Samples ----------------------------------------------------------------------------------------------- For continuous microphone input: Copy Ask AI // Start streaming transcription suspend fun startLiveTranscription( audioSamplesFlow: Flow, onPartialResult: (String) -> Unit ) { audioSamplesFlow.collect { samples -> RunAnywhere.processStreamingAudio(samples) // Handle partial results via event system } } [​](https://docs.runanywhere.ai/kotlin/stt/stream#subscribe-to-stt-events) Subscribe to STT Events ----------------------------------------------------------------------------------------------------- Use the event system for streaming updates: Copy Ask AI lifecycleScope.launch { RunAnywhere.events.sttEvents.collect { event -> when (event.eventType) { STTEventType.PARTIAL_RESULT -> { event.transcript?.let { partial -> partialTextView.text = partial } } STTEventType.TRANSCRIPTION_COMPLETED -> { event.transcript?.let { final -> finalTextView.text = final } } STTEventType.TRANSCRIPTION_FAILED -> { showError(event.error ?: "Transcription failed") } } } } [​](https://docs.runanywhere.ai/kotlin/stt/stream#example-voice-search) Example: Voice Search ------------------------------------------------------------------------------------------------ Copy Ask AI class VoiceSearchActivity : AppCompatActivity() { private lateinit var audioRecorder: AudioRecorder override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Load STT model lifecycleScope.launch { RunAnywhere.loadSTTModel("whisper-tiny") } // Subscribe to transcription events lifecycleScope.launch { RunAnywhere.events.sttEvents.collect { event -> if (event.eventType == STTEventType.PARTIAL_RESULT) { searchInput.setText(event.transcript) } } } micButton.setOnClickListener { if (isRecording) { stopRecording() } else { startRecording() } } } private fun startRecording() { audioRecorder.start { samples -> lifecycleScope.launch { RunAnywhere.processStreamingAudio(samples) } } } private fun stopRecording() { audioRecorder.stop() lifecycleScope.launch { RunAnywhere.stopStreamingTranscription() } } } [​](https://docs.runanywhere.ai/kotlin/stt/stream#performance-tips) Performance Tips --------------------------------------------------------------------------------------- For optimal streaming performance: - Process audio in chunks of 30-100ms - Use 16kHz sample rate for Whisper models - Consider using VAD to detect speech segments | Use Case | Recommended Approach | | --- | --- | | Pre-recorded audio | `transcribe()` | | Live microphone | `processStreamingAudio()` | | Real-time dictation | Streaming + VAD | [transcribe()](https://docs.runanywhere.ai/kotlin/stt/transcribe) [STT Options](https://docs.runanywhere.ai/kotlin/stt/options) ⌘I --- # Voice Activity Detection - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/vad#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Kotlin SDK Voice Activity Detection On this page * [Basic Usage](https://docs.runanywhere.ai/kotlin/vad#basic-usage) * [VADResult](https://docs.runanywhere.ai/kotlin/vad#vadresult) * [Configure VAD](https://docs.runanywhere.ai/kotlin/vad#configure-vad) * [VADConfiguration](https://docs.runanywhere.ai/kotlin/vad#vadconfiguration) * [Streaming VAD](https://docs.runanywhere.ai/kotlin/vad#streaming-vad) * [Calibrate with Ambient Noise](https://docs.runanywhere.ai/kotlin/vad#calibrate-with-ambient-noise) * [Example: Voice Recording with VAD](https://docs.runanywhere.ai/kotlin/vad#example-voice-recording-with-vad) * [VAD Statistics](https://docs.runanywhere.ai/kotlin/vad#vad-statistics) * [Reset VAD](https://docs.runanywhere.ai/kotlin/vad#reset-vad) * [Best Practices](https://docs.runanywhere.ai/kotlin/vad#best-practices) Voice Activity Detection (VAD) identifies speech segments in audio streams, enabling responsive voice interfaces. [​](https://docs.runanywhere.ai/kotlin/vad#basic-usage) Basic Usage ---------------------------------------------------------------------- Copy Ask AI // Detect speech in audio data val audioData: ByteArray = // ... from recording val result = RunAnywhere.detectVoiceActivity(audioData) if (result.hasSpeech) { println("Speech detected!") println("Confidence: ${result.confidence}") } [​](https://docs.runanywhere.ai/kotlin/vad#vadresult) VADResult ------------------------------------------------------------------ | Property | Type | Description | | --- | --- | --- | | `hasSpeech` | `Boolean` | Whether speech was detected | | `confidence` | `Float` | Detection confidence (0.0-1.0) | | `speechStartMs` | `Long?` | Start time of speech segment | | `speechEndMs` | `Long?` | End time of speech segment | | `frameIndex` | `Int` | Audio frame index | | `timestamp` | `Long` | Detection timestamp | [​](https://docs.runanywhere.ai/kotlin/vad#configure-vad) Configure VAD -------------------------------------------------------------------------- Customize detection sensitivity: Copy Ask AI RunAnywhere.configureVAD(VADConfiguration( threshold = 0.5f, // Detection threshold (0.0-1.0) minSpeechDurationMs = 250, // Minimum speech duration minSilenceDurationMs = 300, // Silence before speech end sampleRate = 16000, // Audio sample rate frameSizeMs = 30 // Frame size for processing )) [​](https://docs.runanywhere.ai/kotlin/vad#vadconfiguration) VADConfiguration -------------------------------------------------------------------------------- Copy Ask AI data class VADConfiguration( val threshold: Float = 0.5f, val minSpeechDurationMs: Int = 250, val minSilenceDurationMs: Int = 300, val sampleRate: Int = 16000, val frameSizeMs: Int = 30 ) | Parameter | Default | Description | | --- | --- | --- | | `threshold` | 0.5 | Higher = less sensitive (fewer false positives) | | `minSpeechDurationMs` | 250 | Ignore speech shorter than this | | `minSilenceDurationMs` | 300 | Silence needed to end speech | | `sampleRate` | 16000 | Audio sample rate | | `frameSizeMs` | 30 | Frame duration for processing | [​](https://docs.runanywhere.ai/kotlin/vad#streaming-vad) Streaming VAD -------------------------------------------------------------------------- Process continuous audio with Kotlin Flows: Copy Ask AI // Create a flow of audio samples from microphone val audioSamplesFlow: Flow = microphoneManager.audioFlow // Stream VAD results RunAnywhere.streamVAD(audioSamplesFlow) .collect { result -> if (result.hasSpeech) { updateUI(state = "Speaking...") } else { updateUI(state = "Listening...") } } [​](https://docs.runanywhere.ai/kotlin/vad#calibrate-with-ambient-noise) Calibrate with Ambient Noise -------------------------------------------------------------------------------------------------------- Improve accuracy by calibrating with ambient noise: Copy Ask AI // Record a few seconds of ambient noise val ambientAudio = recordAmbientNoise(durationMs = 2000) // Calibrate VAD RunAnywhere.calibrateVAD(ambientAudio) [​](https://docs.runanywhere.ai/kotlin/vad#example-voice-recording-with-vad) Example: Voice Recording with VAD ----------------------------------------------------------------------------------------------------------------- Copy Ask AI class VoiceRecorderViewModel : ViewModel() { private val _isListening = MutableStateFlow(false) val isListening: StateFlow = _isListening private val _isSpeaking = MutableStateFlow(false) val isSpeaking: StateFlow = _isSpeaking private val audioBuffer = mutableListOf() fun startListening(audioFlow: Flow) { viewModelScope.launch { _isListening.value = true // Configure VAD RunAnywhere.configureVAD(VADConfiguration( threshold = 0.5f, minSpeechDurationMs = 300, minSilenceDurationMs = 500 )) // Stream VAD RunAnywhere.streamVAD(audioFlow) .collect { result -> _isSpeaking.value = result.hasSpeech if (result.hasSpeech) { // Buffer audio during speech // (actual audio capture would be handled separately) } else if (audioBuffer.isNotEmpty()) { // Speech ended - process buffered audio processRecordedAudio() } } } } fun stopListening() { viewModelScope.launch { _isListening.value = false RunAnywhere.resetVAD() } } private suspend fun processRecordedAudio() { // Convert buffer to ByteArray and transcribe val audioData = audioBuffer.toByteArray() val transcription = RunAnywhere.transcribe(audioData) _transcription.value = transcription audioBuffer.clear() } } [​](https://docs.runanywhere.ai/kotlin/vad#vad-statistics) VAD Statistics ---------------------------------------------------------------------------- Get current VAD performance metrics: Copy Ask AI val stats = RunAnywhere.getVADStatistics() println("Total frames processed: ${stats.framesProcessed}") println("Speech frames: ${stats.speechFrames}") println("Current state: ${stats.currentState}") [​](https://docs.runanywhere.ai/kotlin/vad#reset-vad) Reset VAD ------------------------------------------------------------------ Clear VAD state for a fresh start: Copy Ask AI RunAnywhere.resetVAD() [​](https://docs.runanywhere.ai/kotlin/vad#best-practices) Best Practices ---------------------------------------------------------------------------- **Calibration**: Always calibrate VAD with ambient noise for best results in noisy environments.**Threshold tuning**: * Quiet environment: threshold = 0.3-0.5 * Noisy environment: threshold = 0.6-0.8 **Buffer management**: Use VAD to determine when to start/stop recording, but buffer audio slightly before speech detection for complete captures. [Voices](https://docs.runanywhere.ai/kotlin/tts/voices) [Voice Agent](https://docs.runanywhere.ai/kotlin/voice-agent) ⌘I --- # transcribe() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/stt/transcribe#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation STT (Speech-to-Text) transcribe() On this page * [Basic Transcription](https://docs.runanywhere.ai/kotlin/stt/transcribe#basic-transcription) * [Transcription with Options](https://docs.runanywhere.ai/kotlin/stt/transcribe#transcription-with-options) * [STTOutput](https://docs.runanywhere.ai/kotlin/stt/transcribe#sttoutput) * [Example: Transcribe Audio File](https://docs.runanywhere.ai/kotlin/stt/transcribe#example-transcribe-audio-file) * [Example: Record and Transcribe](https://docs.runanywhere.ai/kotlin/stt/transcribe#example-record-and-transcribe) * [Model Management](https://docs.runanywhere.ai/kotlin/stt/transcribe#model-management) * [Supported Audio Formats](https://docs.runanywhere.ai/kotlin/stt/transcribe#supported-audio-formats) Transcribe audio data to text using on-device speech recognition models. [​](https://docs.runanywhere.ai/kotlin/stt/transcribe#basic-transcription) Basic Transcription ------------------------------------------------------------------------------------------------- Copy Ask AI // Load an STT model first RunAnywhere.loadSTTModel("whisper-tiny") // Transcribe audio bytes val audioData: ByteArray = // ... from file or recording val text = RunAnywhere.transcribe(audioData) println(text) // "Hello, how are you today?" [​](https://docs.runanywhere.ai/kotlin/stt/transcribe#transcription-with-options) Transcription with Options --------------------------------------------------------------------------------------------------------------- Get detailed output including confidence scores and timestamps: Copy Ask AI val output = RunAnywhere.transcribeWithOptions( audioData = audioBytes, options = STTOptions( language = "en", enableTimestamps = true, enablePunctuation = true ) ) println("Text: ${output.text}") println("Confidence: ${output.confidence}") // Access word-level timestamps output.wordTimestamps?.forEach { word -> println("[${word.startTime}s - ${word.endTime}s]: ${word.word}") } [​](https://docs.runanywhere.ai/kotlin/stt/transcribe#sttoutput) STTOutput ----------------------------------------------------------------------------- The detailed output object: | Property | Type | Description | | --- | --- | --- | | `text` | `String` | Transcribed text | | `confidence` | `Float` | Confidence score (0.0-1.0) | | `wordTimestamps` | `List?` | Word-level timing | | `detectedLanguage` | `String?` | Auto-detected language code | | `metadata` | `TranscriptionMetadata` | Processing metrics | [​](https://docs.runanywhere.ai/kotlin/stt/transcribe#example-transcribe-audio-file) Example: Transcribe Audio File ---------------------------------------------------------------------------------------------------------------------- Copy Ask AI suspend fun transcribeAudioFile(uri: Uri): String { val audioData = contentResolver.openInputStream(uri)?.readBytes() ?: throw IllegalArgumentException("Cannot read audio file") // Ensure STT model is loaded if (!RunAnywhere.isSTTModelLoaded()) { RunAnywhere.loadSTTModel("whisper-tiny") } return RunAnywhere.transcribe(audioData) } [​](https://docs.runanywhere.ai/kotlin/stt/transcribe#example-record-and-transcribe) Example: Record and Transcribe ---------------------------------------------------------------------------------------------------------------------- Copy Ask AI class VoiceRecorderViewModel : ViewModel() { private var audioRecorder: AudioRecord? = null private val audioBuffer = mutableListOf() fun startRecording() { // Start recording audio... } fun stopAndTranscribe() { viewModelScope.launch { val audioData = audioBuffer.toByteArray() val result = RunAnywhere.transcribeWithOptions( audioData, options = STTOptions( language = "en", enablePunctuation = true ) ) _transcription.value = result.text _confidence.value = result.confidence } } } [​](https://docs.runanywhere.ai/kotlin/stt/transcribe#model-management) Model Management ------------------------------------------------------------------------------------------- Copy Ask AI // Load a specific STT model RunAnywhere.loadSTTModel("whisper-tiny") // Check if loaded val isLoaded = RunAnywhere.isSTTModelLoaded() // Get current model ID val modelId = RunAnywhere.currentSTTModelId // Unload when done RunAnywhere.unloadSTTModel() [​](https://docs.runanywhere.ai/kotlin/stt/transcribe#supported-audio-formats) Supported Audio Formats --------------------------------------------------------------------------------------------------------- | Format | Sample Rate | Notes | | --- | --- | --- | | PCM | 16000 Hz | Recommended for best quality | | WAV | 16000 Hz | Standard audio file format | | MP3 | Any | Converted internally | For best transcription accuracy: - Use 16kHz mono PCM audio - Keep audio clips under 30 seconds for optimal performance - Use a smaller model (whisper-tiny) for faster results, larger models (whisper-base) for better accuracy [System Prompts](https://docs.runanywhere.ai/kotlin/llm/system-prompts) [Streaming STT](https://docs.runanywhere.ai/kotlin/stt/stream) ⌘I --- # generateStream() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/llm/stream#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation LLM (Language Models) generateStream() On this page * [Basic Streaming](https://docs.runanywhere.ai/kotlin/llm/stream#basic-streaming) * [Streaming with Metrics](https://docs.runanywhere.ai/kotlin/llm/stream#streaming-with-metrics) * [LLMStreamingResult](https://docs.runanywhere.ai/kotlin/llm/stream#llmstreamingresult) * [Example: Chat UI with Streaming](https://docs.runanywhere.ai/kotlin/llm/stream#example-chat-ui-with-streaming) * [Example: Jetpack Compose Integration](https://docs.runanywhere.ai/kotlin/llm/stream#example-jetpack-compose-integration) * [Performance Tips](https://docs.runanywhere.ai/kotlin/llm/stream#performance-tips) Use streaming for responsive UIs that display text as it’s generated, providing a better user experience for longer responses. [​](https://docs.runanywhere.ai/kotlin/llm/stream#basic-streaming) Basic Streaming ------------------------------------------------------------------------------------- Copy Ask AI RunAnywhere.generateStream("Tell me a story about AI") .collect { token -> // Display each token as it arrives print(token) textView.append(token) } [​](https://docs.runanywhere.ai/kotlin/llm/stream#streaming-with-metrics) Streaming with Metrics --------------------------------------------------------------------------------------------------- Get both the token stream AND final metrics: Copy Ask AI val streamResult = RunAnywhere.generateStreamWithMetrics( prompt = "Explain quantum computing", options = LLMGenerationOptions(maxTokens = 500) ) // Collect tokens as they arrive streamResult.stream.collect { token -> textView.append(token) } // Get final metrics after streaming completes val metrics = streamResult.result.await() println("\n\nGenerated ${metrics.tokensUsed} tokens") println("Speed: ${metrics.tokensPerSecond} tok/s") println("Time to first token: ${metrics.timeToFirstTokenMs}ms") [​](https://docs.runanywhere.ai/kotlin/llm/stream#llmstreamingresult) LLMStreamingResult ------------------------------------------------------------------------------------------- Copy Ask AI data class LLMStreamingResult( val stream: Flow, // Token stream val result: Deferred // Final metrics (awaitable) ) [​](https://docs.runanywhere.ai/kotlin/llm/stream#example-chat-ui-with-streaming) Example: Chat UI with Streaming -------------------------------------------------------------------------------------------------------------------- Copy Ask AI class ChatViewModel : ViewModel() { private val _currentResponse = MutableStateFlow("") val currentResponse: StateFlow = _currentResponse private val _isGenerating = MutableStateFlow(false) val isGenerating: StateFlow = _isGenerating fun sendMessage(prompt: String) { viewModelScope.launch { _isGenerating.value = true _currentResponse.value = "" try { RunAnywhere.generateStream(prompt) .collect { token -> _currentResponse.value += token } } catch (e: Exception) { _currentResponse.value = "Error: ${e.message}" } finally { _isGenerating.value = false } } } fun cancelGeneration() { RunAnywhere.cancelGeneration() } } [​](https://docs.runanywhere.ai/kotlin/llm/stream#example-jetpack-compose-integration) Example: Jetpack Compose Integration ------------------------------------------------------------------------------------------------------------------------------ Copy Ask AI @Composable fun StreamingTextView(viewModel: ChatViewModel) { val response by viewModel.currentResponse.collectAsState() val isGenerating by viewModel.isGenerating.collectAsState() Column { Text( text = response, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) if (isGenerating) { LinearProgressIndicator( modifier = Modifier.fillMaxWidth() ) } } } [​](https://docs.runanywhere.ai/kotlin/llm/stream#performance-tips) Performance Tips --------------------------------------------------------------------------------------- Streaming provides better perceived performance for long generations: - **Time to First Token (TTFT)**: ~50-100ms - Users see immediate feedback instead of waiting for the full response | Scenario | Recommended Approach | | --- | --- | | Short responses (under 50 tokens) | `generate()` | | Long responses (over 100 tokens) | `generateStream()` | | Chat interfaces | `generateStream()` | | Background processing | `generate()` | [generate()](https://docs.runanywhere.ai/kotlin/llm/generate) [System Prompts](https://docs.runanywhere.ai/kotlin/llm/system-prompts) ⌘I --- # Voices - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/tts/voices#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation TTS (Text-to-Speech) Voices On this page * [List Available Voices](https://docs.runanywhere.ai/kotlin/tts/voices#list-available-voices) * [Load a Voice](https://docs.runanywhere.ai/kotlin/tts/voices#load-a-voice) * [Voice Configuration](https://docs.runanywhere.ai/kotlin/tts/voices#voice-configuration) * [Rate, Pitch, and Volume](https://docs.runanywhere.ai/kotlin/tts/voices#rate-pitch-and-volume) * [Example: Voice Selector](https://docs.runanywhere.ai/kotlin/tts/voices#example-voice-selector) * [Sherpa-ONNX Voices](https://docs.runanywhere.ai/kotlin/tts/voices#sherpa-onnx-voices) * [Download Additional Voices](https://docs.runanywhere.ai/kotlin/tts/voices#download-additional-voices) * [Best Practices](https://docs.runanywhere.ai/kotlin/tts/voices#best-practices) [​](https://docs.runanywhere.ai/kotlin/tts/voices#list-available-voices) List Available Voices ------------------------------------------------------------------------------------------------- Copy Ask AI val voices = RunAnywhere.availableTTSVoices() voices.forEach { voiceId -> println(voiceId) } [​](https://docs.runanywhere.ai/kotlin/tts/voices#load-a-voice) Load a Voice ------------------------------------------------------------------------------- Copy Ask AI // Load a specific voice RunAnywhere.loadTTSVoice("en-us-default") // Check if voice is loaded val isLoaded = RunAnywhere.isTTSVoiceLoaded() // Get current voice ID val currentVoice = RunAnywhere.currentTTSVoiceId // Unload when done RunAnywhere.unloadTTSVoice() [​](https://docs.runanywhere.ai/kotlin/tts/voices#voice-configuration) Voice Configuration --------------------------------------------------------------------------------------------- Customize voice parameters in TTSOptions: Copy Ask AI val options = TTSOptions( voice = "en-US-Neural2-F", // Specific voice ID rate = 0.8f, // 0.0-2.0, slower speed pitch = 1.3f, // 0.0-2.0, higher pitch volume = 1.0f // 0.0-1.0 ) val output = RunAnywhere.synthesize("Hello world", options) [​](https://docs.runanywhere.ai/kotlin/tts/voices#rate-pitch-and-volume) Rate, Pitch, and Volume --------------------------------------------------------------------------------------------------- | Parameter | Range | Default | Effect | | --- | --- | --- | --- | | `rate` | 0.0-2.0 | 1.0 | Speech speed (0.5 = half speed, 2.0 = double speed) | | `pitch` | 0.0-2.0 | 1.0 | Voice pitch (lower = deeper, higher = lighter) | | `volume` | 0.0-1.0 | 1.0 | Audio volume | [​](https://docs.runanywhere.ai/kotlin/tts/voices#example-voice-selector) Example: Voice Selector ---------------------------------------------------------------------------------------------------- Copy Ask AI class VoiceSelectorViewModel : ViewModel() { private val _availableVoices = MutableStateFlow>(emptyList()) val availableVoices: StateFlow> = _availableVoices private val _selectedVoice = MutableStateFlow(null) val selectedVoice: StateFlow = _selectedVoice init { viewModelScope.launch { _availableVoices.value = RunAnywhere.availableTTSVoices() } } fun selectVoice(voiceId: String) { viewModelScope.launch { RunAnywhere.loadTTSVoice(voiceId) _selectedVoice.value = voiceId } } fun previewVoice(voiceId: String) { viewModelScope.launch { RunAnywhere.loadTTSVoice(voiceId) RunAnywhere.speak( "Hello! This is a preview of the selected voice.", TTSOptions(rate = 1.0f) ) } } } [​](https://docs.runanywhere.ai/kotlin/tts/voices#sherpa-onnx-voices) Sherpa-ONNX Voices ------------------------------------------------------------------------------------------- The SDK uses Sherpa-ONNX for neural TTS. Available voice packs include: | Voice ID | Language | Description | | --- | --- | --- | | `en-us-default` | English (US) | Default English voice | | `en-gb-default` | English (UK) | British English voice | | `de-de-default` | German | German voice | | `fr-fr-default` | French | French voice | | `es-es-default` | Spanish | Spanish voice | Voice availability depends on downloaded voice models. Use `availableTTSVoices()` to see what’s available on the device. [​](https://docs.runanywhere.ai/kotlin/tts/voices#download-additional-voices) Download Additional Voices ----------------------------------------------------------------------------------------------------------- Register and download additional TTS voice models: Copy Ask AI // Register a TTS voice model val voiceModel = RunAnywhere.registerModel( name = "Piper English Amy", url = "https://example.com/piper-en-us-amy.onnx", framework = InferenceFramework.ONNX, modality = ModelCategory.SPEECH_SYNTHESIS ) // Download the voice RunAnywhere.downloadModel(voiceModel.id).collect { progress -> println("Downloading: ${(progress.progress * 100).toInt()}%") } // Load and use RunAnywhere.loadTTSVoice(voiceModel.id) [​](https://docs.runanywhere.ai/kotlin/tts/voices#best-practices) Best Practices ----------------------------------------------------------------------------------- * **Preload voices** at app startup for instant TTS - **Use streaming** for long text to reduce latency - **Cache common phrases** as audio files for fastest playback - **Match voice language** to content language for best quality [Streaming TTS](https://docs.runanywhere.ai/kotlin/tts/stream) [Voice Activity Detection](https://docs.runanywhere.ai/kotlin/vad) ⌘I --- # STT Options - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/stt/options#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation STT (Speech-to-Text) STT Options On this page * [STTOptions](https://docs.runanywhere.ai/kotlin/stt/options#sttoptions) * [Configuration Examples](https://docs.runanywhere.ai/kotlin/stt/options#configuration-examples) * [Basic English Transcription](https://docs.runanywhere.ai/kotlin/stt/options#basic-english-transcription) * [Multi-Language Detection](https://docs.runanywhere.ai/kotlin/stt/options#multi-language-detection) * [Transcription with Timestamps](https://docs.runanywhere.ai/kotlin/stt/options#transcription-with-timestamps) * [Speaker Diarization](https://docs.runanywhere.ai/kotlin/stt/options#speaker-diarization) * [Custom Vocabulary](https://docs.runanywhere.ai/kotlin/stt/options#custom-vocabulary) * [Supported Languages](https://docs.runanywhere.ai/kotlin/stt/options#supported-languages) * [AudioFormat](https://docs.runanywhere.ai/kotlin/stt/options#audioformat) * [TranscriptionMetadata](https://docs.runanywhere.ai/kotlin/stt/options#transcriptionmetadata) Customize transcription behavior with `STTOptions`. [​](https://docs.runanywhere.ai/kotlin/stt/options#sttoptions) STTOptions ---------------------------------------------------------------------------- Copy Ask AI data class STTOptions( val language: String = "en", // BCP-47 language code val detectLanguage: Boolean = false, // Auto-detect spoken language val enablePunctuation: Boolean = true, // Add punctuation val enableDiarization: Boolean = false, // Identify speakers val maxSpeakers: Int? = null, // Max speakers to identify val enableTimestamps: Boolean = true, // Word-level timestamps val vocabularyFilter: List = emptyList(), // Custom vocabulary val audioFormat: AudioFormat = AudioFormat.PCM, val sampleRate: Int = 16000 // Audio sample rate ) [​](https://docs.runanywhere.ai/kotlin/stt/options#configuration-examples) Configuration Examples ---------------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/kotlin/stt/options#basic-english-transcription) Basic English Transcription Copy Ask AI val options = STTOptions( language = "en", enablePunctuation = true ) ### [​](https://docs.runanywhere.ai/kotlin/stt/options#multi-language-detection) Multi-Language Detection Copy Ask AI val options = STTOptions( detectLanguage = true, enablePunctuation = true ) val result = RunAnywhere.transcribeWithOptions(audioData, options) println("Detected language: ${result.detectedLanguage}") ### [​](https://docs.runanywhere.ai/kotlin/stt/options#transcription-with-timestamps) Transcription with Timestamps Copy Ask AI val options = STTOptions( language = "en", enableTimestamps = true ) val result = RunAnywhere.transcribeWithOptions(audioData, options) result.wordTimestamps?.forEach { word -> println("[${word.startTime}s - ${word.endTime}s]: ${word.word}") } ### [​](https://docs.runanywhere.ai/kotlin/stt/options#speaker-diarization) Speaker Diarization Copy Ask AI val options = STTOptions( language = "en", enableDiarization = true, maxSpeakers = 2 ) ### [​](https://docs.runanywhere.ai/kotlin/stt/options#custom-vocabulary) Custom Vocabulary Improve recognition for domain-specific terms: Copy Ask AI val options = STTOptions( language = "en", vocabularyFilter = listOf( "RunAnywhere", "Kotlin", "ONNX", "llama.cpp" ) ) [​](https://docs.runanywhere.ai/kotlin/stt/options#supported-languages) Supported Languages ---------------------------------------------------------------------------------------------- | Code | Language | | --- | --- | | `en` | English | | `es` | Spanish | | `fr` | French | | `de` | German | | `it` | Italian | | `pt` | Portuguese | | `zh` | Chinese | | `ja` | Japanese | | `ko` | Korean | Language support depends on the STT model. Whisper models support 99+ languages. [​](https://docs.runanywhere.ai/kotlin/stt/options#audioformat) AudioFormat ------------------------------------------------------------------------------ Copy Ask AI enum class AudioFormat { PCM, // Raw PCM samples WAV, // WAV container MP3, // MP3 compressed AAC, // AAC compressed OGG, // Ogg Vorbis OPUS, // Opus codec FLAC // FLAC lossless } [​](https://docs.runanywhere.ai/kotlin/stt/options#transcriptionmetadata) TranscriptionMetadata -------------------------------------------------------------------------------------------------- Access processing metrics: Copy Ask AI val result = RunAnywhere.transcribeWithOptions(audioData, options) val metadata = result.metadata println("Model: ${metadata.modelId}") println("Processing time: ${metadata.processingTime}s") println("Audio length: ${metadata.audioLength}s") println("Real-time factor: ${metadata.realTimeFactor}x") | Property | Description | | --- | --- | | `modelId` | STT model used | | `processingTime` | Time to process (seconds) | | `audioLength` | Input audio duration (seconds) | | `realTimeFactor` | Processing time / audio length | A real-time factor < 1.0 means the transcription is faster than real-time. For example, 0.2x means 10 seconds of audio processed in 2 seconds. [Streaming STT](https://docs.runanywhere.ai/kotlin/stt/stream) [synthesize()](https://docs.runanywhere.ai/kotlin/tts/synthesize) ⌘I --- # Quick Start - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/quick-start#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Kotlin SDK Quick Start On this page * [Complete Example](https://docs.runanywhere.ai/kotlin/quick-start#complete-example) * [Step-by-Step Guide](https://docs.runanywhere.ai/kotlin/quick-start#step-by-step-guide) * [1\. Initialize the SDK](https://docs.runanywhere.ai/kotlin/quick-start#1-initialize-the-sdk) * [Environment Options](https://docs.runanywhere.ai/kotlin/quick-start#environment-options) * [2\. Register a Model](https://docs.runanywhere.ai/kotlin/quick-start#2-register-a-model) * [3\. Download the Model](https://docs.runanywhere.ai/kotlin/quick-start#3-download-the-model) * [4\. Load and Generate](https://docs.runanywhere.ai/kotlin/quick-start#4-load-and-generate) * [5\. Stream Responses](https://docs.runanywhere.ai/kotlin/quick-start#5-stream-responses) * [What’s Next?](https://docs.runanywhere.ai/kotlin/quick-start#what%E2%80%99s-next) [​](https://docs.runanywhere.ai/kotlin/quick-start#complete-example) Complete Example ---------------------------------------------------------------------------------------- Here’s a complete example to get you started with on-device text generation: MainActivity.kt Copy Ask AI import com.runanywhere.sdk.public.RunAnywhere import com.runanywhere.sdk.public.SDKEnvironment import com.runanywhere.sdk.public.extensions.* import com.runanywhere.sdk.core.types.InferenceFramework class MyApplication : Application() { override fun onCreate() { super.onCreate() // 1. Initialize SDK (fast, ~1-5ms) RunAnywhere.initialize( apiKey = "your-api-key", // Optional for development environment = SDKEnvironment.DEVELOPMENT ) } } // 2. Use in your Activity/Fragment class MainActivity : AppCompatActivity() { private var modelId: String? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) lifecycleScope.launch { // Register and download a model val modelInfo = RunAnywhere.registerModel( name = "Qwen 0.5B", url = "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q8_0.gguf", framework = InferenceFramework.LLAMA_CPP ) modelId = modelInfo.id // Download with progress tracking RunAnywhere.downloadModel(modelInfo.id).collect { progress -> updateProgress((progress.progress * 100).toInt()) } // Load and generate RunAnywhere.loadLLMModel(modelInfo.id) val result = RunAnywhere.generate( prompt = "Explain quantum computing in simple terms", options = LLMGenerationOptions( maxTokens = 200, temperature = 0.7f ) ) showResponse(result.text) Log.d("LLM", "Generated in ${result.latencyMs}ms at ${result.tokensPerSecond} tok/s") } } } [​](https://docs.runanywhere.ai/kotlin/quick-start#step-by-step-guide) Step-by-Step Guide -------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/kotlin/quick-start#1-initialize-the-sdk) 1\. Initialize the SDK Initialize RunAnywhere once in your `Application.onCreate()`: Copy Ask AI RunAnywhere.initialize( apiKey = "your-api-key", // Optional for development mode baseURL = null, // Uses default API endpoint environment = SDKEnvironment.DEVELOPMENT ) ### [​](https://docs.runanywhere.ai/kotlin/quick-start#environment-options) Environment Options | Environment | Log Level | Description | | --- | --- | --- | | `DEVELOPMENT` | Debug | Full logging, local testing | | `STAGING` | Info | Staging backend, moderate logging | | `PRODUCTION` | Warning | Production backend, minimal logging | ### [​](https://docs.runanywhere.ai/kotlin/quick-start#2-register-a-model) 2\. Register a Model Register models from HuggingFace or any direct URL: Copy Ask AI val modelInfo = RunAnywhere.registerModel( name = "Qwen 0.5B", url = "https://huggingface.co/.../model.gguf", framework = InferenceFramework.LLAMA_CPP ) ### [​](https://docs.runanywhere.ai/kotlin/quick-start#3-download-the-model) 3\. Download the Model Download with progress tracking using Kotlin Flows: Copy Ask AI RunAnywhere.downloadModel(modelInfo.id).collect { progress -> when (progress.state) { DownloadState.DOWNLOADING -> { val percent = (progress.progress * 100).toInt() progressBar.progress = percent } DownloadState.COMPLETED -> { showMessage("Download complete!") } DownloadState.ERROR -> { showError(progress.error ?: "Download failed") } } } ### [​](https://docs.runanywhere.ai/kotlin/quick-start#4-load-and-generate) 4\. Load and Generate Copy Ask AI // Load the model into memory RunAnywhere.loadLLMModel(modelInfo.id) // Simple chat val response = RunAnywhere.chat("What is 2+2?") // Or with full metrics val result = RunAnywhere.generate( prompt = "Write a haiku about coding", options = LLMGenerationOptions(maxTokens = 50) ) println("Response: ${result.text}") println("Tokens/sec: ${result.tokensPerSecond}") ### [​](https://docs.runanywhere.ai/kotlin/quick-start#5-stream-responses) 5\. Stream Responses For real-time token streaming: Copy Ask AI RunAnywhere.generateStream("Tell me a story about AI") .collect { token -> // Display tokens as they arrive textView.append(token) } [​](https://docs.runanywhere.ai/kotlin/quick-start#what%E2%80%99s-next) What’s Next? --------------------------------------------------------------------------------------- [LLM Chat\ --------\ \ Simple one-liner for quick responses](https://docs.runanywhere.ai/kotlin/llm/chat) [Streaming\ ---------\ \ Real-time token streaming with Flows](https://docs.runanywhere.ai/kotlin/llm/stream) [Speech-to-Text\ --------------\ \ Transcribe audio to text](https://docs.runanywhere.ai/kotlin/stt/transcribe) [Text-to-Speech\ --------------\ \ Convert text to spoken audio](https://docs.runanywhere.ai/kotlin/tts/synthesize) [Installation](https://docs.runanywhere.ai/kotlin/installation) [chat()](https://docs.runanywhere.ai/kotlin/llm/chat) ⌘I --- # Installation - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/react-native/installation#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation React Native SDK Installation On this page * [Package Installation](https://docs.runanywhere.ai/react-native/installation#package-installation) * [Full Installation (All Features)](https://docs.runanywhere.ai/react-native/installation#full-installation-all-features) * [LLM Only (Text Generation)](https://docs.runanywhere.ai/react-native/installation#llm-only-text-generation) * [Voice Only (STT/TTS)](https://docs.runanywhere.ai/react-native/installation#voice-only-stt%2Ftts) * [Required Peer Dependencies](https://docs.runanywhere.ai/react-native/installation#required-peer-dependencies) * [Package Overview](https://docs.runanywhere.ai/react-native/installation#package-overview) * [Supported Model Formats](https://docs.runanywhere.ai/react-native/installation#supported-model-formats) * [iOS Setup](https://docs.runanywhere.ai/react-native/installation#ios-setup) * [iOS Permissions](https://docs.runanywhere.ai/react-native/installation#ios-permissions) * [Android Setup](https://docs.runanywhere.ai/react-native/installation#android-setup) * [Android Build Requirements](https://docs.runanywhere.ai/react-native/installation#android-build-requirements) * [Android Permissions](https://docs.runanywhere.ai/react-native/installation#android-permissions) * [Running on Physical Device](https://docs.runanywhere.ai/react-native/installation#running-on-physical-device) * [ProGuard Rules](https://docs.runanywhere.ai/react-native/installation#proguard-rules) * [Troubleshooting Installation](https://docs.runanywhere.ai/react-native/installation#troubleshooting-installation) * [iOS: Pod Install Fails](https://docs.runanywhere.ai/react-native/installation#ios-pod-install-fails) * [Android: Native Library Not Found](https://docs.runanywhere.ai/react-native/installation#android-native-library-not-found) * [Android: “hermesEnabled” Property Not Found](https://docs.runanywhere.ai/react-native/installation#android-%E2%80%9Chermesenabled%E2%80%9D-property-not-found) * [Android: “Unable to load script” on Device](https://docs.runanywhere.ai/react-native/installation#android-%E2%80%9Cunable-to-load-script%E2%80%9D-on-device) * [Android: Grey Screen After Launch](https://docs.runanywhere.ai/react-native/installation#android-grey-screen-after-launch) * [Metro: Module Resolution Issues](https://docs.runanywhere.ai/react-native/installation#metro-module-resolution-issues) * [Both Platforms: Fresh Build](https://docs.runanywhere.ai/react-native/installation#both-platforms-fresh-build) * [Native Binary Sizes](https://docs.runanywhere.ai/react-native/installation#native-binary-sizes) * [Next Steps](https://docs.runanywhere.ai/react-native/installation#next-steps) [​](https://docs.runanywhere.ai/react-native/installation#package-installation) Package Installation ------------------------------------------------------------------------------------------------------- Choose the packages based on your feature requirements: ### [​](https://docs.runanywhere.ai/react-native/installation#full-installation-all-features) Full Installation (All Features) Copy Ask AI npm install @runanywhere/core @runanywhere/llamacpp @runanywhere/onnx # or yarn add @runanywhere/core @runanywhere/llamacpp @runanywhere/onnx ### [​](https://docs.runanywhere.ai/react-native/installation#llm-only-text-generation) LLM Only (Text Generation) Copy Ask AI npm install @runanywhere/core @runanywhere/llamacpp # or yarn add @runanywhere/core @runanywhere/llamacpp ### [​](https://docs.runanywhere.ai/react-native/installation#voice-only-stt/tts) Voice Only (STT/TTS) Copy Ask AI npm install @runanywhere/core @runanywhere/onnx # or yarn add @runanywhere/core @runanywhere/onnx ### [​](https://docs.runanywhere.ai/react-native/installation#required-peer-dependencies) Required Peer Dependencies The SDK uses Nitro Modules for its native bridge and requires file system access for model downloads: Copy Ask AI # Required: Native bridge layer npm install react-native-nitro-modules # Required: File system access for model downloads npm install react-native-fs@^2.20.0 react-native-zip-archive@^6.1.0 `react-native-fs` and `react-native-zip-archive` are **required** for model downloads. Without them, you will see: `ERROR: react-native-fs not installed - cannot download models` Include only the SDK modules you need. Each native module adds to your app size: - **@runanywhere/core**: ~2MB (required) - **@runanywhere/llamacpp**: ~15-25MB (for LLM text generation) - **@runanywhere/onnx**: ~50-70MB (for STT, TTS, and VAD) [​](https://docs.runanywhere.ai/react-native/installation#package-overview) Package Overview ----------------------------------------------------------------------------------------------- | Package | Size | Features | | --- | --- | --- | | `@runanywhere/core` | ~2MB | Core SDK, model management, events | | `@runanywhere/llamacpp` | ~15-25MB | LLM text generation (GGUF models) | | `@runanywhere/onnx` | ~50-70MB | STT, TTS, VAD (ONNX models) | [​](https://docs.runanywhere.ai/react-native/installation#supported-model-formats) Supported Model Formats ------------------------------------------------------------------------------------------------------------- | Format | Extension | Backend | Use Case | | --- | --- | --- | --- | | GGUF | `.gguf` | LlamaCPP | LLM text generation | | ONNX | `.onnx` | ONNX Runtime | STT, TTS, VAD | [​](https://docs.runanywhere.ai/react-native/installation#ios-setup) iOS Setup --------------------------------------------------------------------------------- After installing packages, run CocoaPods: Copy Ask AI cd ios && pod install && cd .. ### [​](https://docs.runanywhere.ai/react-native/installation#ios-permissions) iOS Permissions Add required permissions to your `Info.plist`: Info.plist Copy Ask AI NSAppTransportSecurity NSAllowsArbitraryLoads NSMicrophoneUsageDescription This app needs microphone access for voice features. UIBackgroundModes audio `NSMicrophoneUsageDescription` is only required if you’re using STT or VAD with microphone input. [​](https://docs.runanywhere.ai/react-native/installation#android-setup) Android Setup ----------------------------------------------------------------------------------------- Native libraries are automatically downloaded during the Gradle build. ### [​](https://docs.runanywhere.ai/react-native/installation#android-build-requirements) Android Build Requirements | Requirement | Minimum Version | | --- | --- | | Android SDK | compileSdk 36 | | Android NDK | 27.1.12297006 | | JDK | 17+ | | Min API | 24 (Android 7.0+) | ### [​](https://docs.runanywhere.ai/react-native/installation#android-permissions) Android Permissions Add required permissions to your `AndroidManifest.xml`: AndroidManifest.xml Copy Ask AI ### [​](https://docs.runanywhere.ai/react-native/installation#running-on-physical-device) Running on Physical Device 1. **Enable Developer Options:** Settings → About Phone → Tap “Build Number” 7 times 2. **Enable USB Debugging:** Settings → Developer Options → USB Debugging 3. **Connect device:** `adb devices` (should show your device) 4. **Port forwarding:** `adb reverse tcp:8081 tcp:8081` 5. **Start Metro:** `npm start` 6. **Run app:** `npx react-native run-android` ### [​](https://docs.runanywhere.ai/react-native/installation#proguard-rules) ProGuard Rules If using ProGuard/R8 minification, add these rules to `proguard-rules.pro`: proguard-rules.pro Copy Ask AI -keep class com.runanywhere.** { *; } -keepclassmembers class com.runanywhere.** { *; } -keep class ai.runanywhere.** { *; } [​](https://docs.runanywhere.ai/react-native/installation#troubleshooting-installation) Troubleshooting Installation ----------------------------------------------------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/react-native/installation#ios-pod-install-fails) iOS: Pod Install Fails Copy Ask AI # Clean and reinstall pods cd ios rm -rf Pods Podfile.lock pod cache clean --all pod install cd .. ### [​](https://docs.runanywhere.ai/react-native/installation#android-native-library-not-found) Android: Native Library Not Found This error typically occurs when running on an emulator: Copy Ask AI dlopen failed: library "librunanywherecore.so" not found **Solution:** Use a physical ARM64 Android device. Emulators are not supported. If using a physical device: Copy Ask AI # Clean and rebuild cd android ./gradlew clean cd .. npx react-native run-android ### [​](https://docs.runanywhere.ai/react-native/installation#android-%E2%80%9Chermesenabled%E2%80%9D-property-not-found) Android: “hermesEnabled” Property Not Found **Solution:** Copy the gradle.properties example file: Copy Ask AI cp android/gradle.properties.example android/gradle.properties ### [​](https://docs.runanywhere.ai/react-native/installation#android-%E2%80%9Cunable-to-load-script%E2%80%9D-on-device) Android: “Unable to load script” on Device **Solution:** Set up port forwarding for Metro bundler: Copy Ask AI adb reverse tcp:8081 tcp:8081 ### [​](https://docs.runanywhere.ai/react-native/installation#android-grey-screen-after-launch) Android: Grey Screen After Launch **Solution:** Metro bundler may have stopped. Restart it: Copy Ask AI npm start ### [​](https://docs.runanywhere.ai/react-native/installation#metro-module-resolution-issues) Metro: Module Resolution Issues Copy Ask AI # Reset Metro bundler cache npx react-native start --reset-cache ### [​](https://docs.runanywhere.ai/react-native/installation#both-platforms-fresh-build) Both Platforms: Fresh Build Copy Ask AI # Complete clean build rm -rf node_modules npm install cd ios && pod install && cd .. npx react-native run-ios # or run-android [​](https://docs.runanywhere.ai/react-native/installation#native-binary-sizes) Native Binary Sizes ----------------------------------------------------------------------------------------------------- | Framework | iOS (xcframework) | Android (so) | | --- | --- | --- | | RACommons | ~2MB | ~2MB | | RABackendLLAMACPP | ~15-25MB | ~15-25MB | | RABackendONNX | ~50-70MB | ~50-70MB | The ONNX backend is significantly larger due to the ONNX Runtime library. If you only need LLM text generation, consider installing just `@runanywhere/llamacpp` to reduce app size. [​](https://docs.runanywhere.ai/react-native/installation#next-steps) Next Steps ----------------------------------------------------------------------------------- [Quick Start\ -----------\ \ Initialize the SDK and run your first inference →](https://docs.runanywhere.ai/react-native/quick-start) [Introduction](https://docs.runanywhere.ai/react-native/introduction) [Quick Start](https://docs.runanywhere.ai/react-native/quick-start) ⌘I --- # Introduction - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/swift/introduction#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Swift SDK Introduction On this page * [Overview](https://docs.runanywhere.ai/swift/introduction#overview) * [Key Capabilities](https://docs.runanywhere.ai/swift/introduction#key-capabilities) * [Core Philosophy](https://docs.runanywhere.ai/swift/introduction#core-philosophy) * [Features](https://docs.runanywhere.ai/swift/introduction#features) * [Language Models (LLM)](https://docs.runanywhere.ai/swift/introduction#language-models-llm) * [Speech-to-Text (STT)](https://docs.runanywhere.ai/swift/introduction#speech-to-text-stt) * [Text-to-Speech (TTS)](https://docs.runanywhere.ai/swift/introduction#text-to-speech-tts) * [Voice Activity Detection (VAD)](https://docs.runanywhere.ai/swift/introduction#voice-activity-detection-vad) * [Voice Agent Pipeline](https://docs.runanywhere.ai/swift/introduction#voice-agent-pipeline) * [Model Management](https://docs.runanywhere.ai/swift/introduction#model-management) * [System Requirements](https://docs.runanywhere.ai/swift/introduction#system-requirements) * [SDK Modules](https://docs.runanywhere.ai/swift/introduction#sdk-modules) * [Next Steps](https://docs.runanywhere.ai/swift/introduction#next-steps) [​](https://docs.runanywhere.ai/swift/introduction#overview) Overview ------------------------------------------------------------------------ The **RunAnywhere Swift SDK** is a production-grade, on-device AI SDK for Apple platforms. It enables developers to run AI models directly on Apple devices without requiring network connectivity for inference, ensuring minimal latency and maximum privacy for your users. The SDK provides a unified interface to multiple AI capabilities: [LLM\ ---\ \ Text generation with streaming support and structured output](https://docs.runanywhere.ai/swift/llm/chat) [STT\ ---\ \ Speech-to-text transcription with multiple backends](https://docs.runanywhere.ai/swift/stt/transcribe) [TTS\ ---\ \ Neural and system voice synthesis](https://docs.runanywhere.ai/swift/tts/synthesize) [VAD\ ---\ \ Real-time voice activity detection](https://docs.runanywhere.ai/swift/vad) [​](https://docs.runanywhere.ai/swift/introduction#key-capabilities) Key Capabilities ---------------------------------------------------------------------------------------- * **Multi-backend architecture** – Choose from LlamaCPP (GGUF models), ONNX Runtime, or Apple Foundation Models * **Metal acceleration** – GPU-accelerated inference on Apple Silicon * **Event-driven design** – Subscribe to SDK events for reactive UI updates * **Production-ready** – Built-in analytics, logging, device registration, and model lifecycle management [​](https://docs.runanywhere.ai/swift/introduction#core-philosophy) Core Philosophy -------------------------------------------------------------------------------------- On-Device First All AI inference runs locally, ensuring low latency and data privacy. Once models are downloaded, no network connection is required for inference. Plugin Architecture Backend engines are optional modules—include only what you need. This keeps your app binary size minimal. Privacy by Design Audio and text data never leaves the device unless explicitly configured. Only anonymous analytics are collected by default. Event-Driven Subscribe to SDK events for reactive UI updates and observability. Track generation progress, model loading, and errors in real-time. [​](https://docs.runanywhere.ai/swift/introduction#features) Features ------------------------------------------------------------------------ ### [​](https://docs.runanywhere.ai/swift/introduction#language-models-llm) Language Models (LLM) * On-device text generation with streaming support * Structured output generation with `Generatable` protocol * System prompts and customizable generation parameters * Support for thinking/reasoning models with token extraction * Multiple framework backends (LlamaCPP, Apple Foundation Models) ### [​](https://docs.runanywhere.ai/swift/introduction#speech-to-text-stt) Speech-to-Text (STT) * Real-time streaming transcription * Batch audio transcription * Multi-language support * Whisper-based models via ONNX Runtime ### [​](https://docs.runanywhere.ai/swift/introduction#text-to-speech-tts) Text-to-Speech (TTS) * Neural voice synthesis with ONNX models * System voices via AVSpeechSynthesizer * Streaming audio generation for long text * Customizable voice, pitch, rate, and volume ### [​](https://docs.runanywhere.ai/swift/introduction#voice-activity-detection-vad) Voice Activity Detection (VAD) * Energy-based speech detection * Configurable sensitivity thresholds * Real-time audio stream processing ### [​](https://docs.runanywhere.ai/swift/introduction#voice-agent-pipeline) Voice Agent Pipeline * Full VAD → STT → LLM → TTS orchestration * Complete voice conversation flow * Streaming and batch processing modes ### [​](https://docs.runanywhere.ai/swift/introduction#model-management) Model Management * Automatic model discovery and catalog sync * Download with progress tracking (download, extract, validate stages) * In-memory model storage with file system caching * Framework-specific model assignment [​](https://docs.runanywhere.ai/swift/introduction#system-requirements) System Requirements ---------------------------------------------------------------------------------------------- | Platform | Minimum Version | | --- | --- | | iOS | 17.0+ | | macOS | 14.0+ | | tvOS | 17.0+ | | watchOS | 10.0+ | **Swift Version:** 5.9+ **Xcode:** 15.2+ Some optional modules have higher runtime requirements: - Apple Foundation Models (`RunAnywhereAppleAI`): iOS 26+ / macOS 26+ at runtime [​](https://docs.runanywhere.ai/swift/introduction#sdk-modules) SDK Modules ------------------------------------------------------------------------------ | Module | Purpose | | --- | --- | | `RunAnywhere` | Core SDK (required) | | `RunAnywhereLlamaCPP` | LLM text generation with GGUF models | | `RunAnywhereONNX` | STT/TTS/VAD via ONNX Runtime | [​](https://docs.runanywhere.ai/swift/introduction#next-steps) Next Steps ---------------------------------------------------------------------------- [Installation\ ------------\ \ Install the SDK via Swift Package Manager](https://docs.runanywhere.ai/swift/installation) [Quick Start\ -----------\ \ Build your first AI feature in minutes](https://docs.runanywhere.ai/swift/quick-start) [SDK Overview](https://docs.runanywhere.ai/sdks) [Installation](https://docs.runanywhere.ai/swift/installation) ⌘I --- # synthesize() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/tts/synthesize#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation TTS (Text-to-Speech) synthesize() On this page * [Basic Synthesis](https://docs.runanywhere.ai/kotlin/tts/synthesize#basic-synthesis) * [Simple Speak API](https://docs.runanywhere.ai/kotlin/tts/synthesize#simple-speak-api) * [TTSOutput](https://docs.runanywhere.ai/kotlin/tts/synthesize#ttsoutput) * [TTSOptions](https://docs.runanywhere.ai/kotlin/tts/synthesize#ttsoptions) * [Example: Custom Voice Settings](https://docs.runanywhere.ai/kotlin/tts/synthesize#example-custom-voice-settings) * [Example: Playing Audio with AudioTrack](https://docs.runanywhere.ai/kotlin/tts/synthesize#example-playing-audio-with-audiotrack) * [Example: Text-to-Speech ViewModel](https://docs.runanywhere.ai/kotlin/tts/synthesize#example-text-to-speech-viewmodel) * [Check Speaking Status](https://docs.runanywhere.ai/kotlin/tts/synthesize#check-speaking-status) * [Synthesis Metadata](https://docs.runanywhere.ai/kotlin/tts/synthesize#synthesis-metadata) Synthesize text into audio using on-device neural TTS models. [​](https://docs.runanywhere.ai/kotlin/tts/synthesize#basic-synthesis) Basic Synthesis ----------------------------------------------------------------------------------------- Copy Ask AI // Load a TTS voice first RunAnywhere.loadTTSVoice("en-us-default") // Synthesize text to audio val output = RunAnywhere.synthesize( text = "Hello, welcome to RunAnywhere!", options = TTSOptions(rate = 1.0f, pitch = 1.0f) ) // Play the audio val audioTrack = createAudioTrack(output.format, output.audioData) audioTrack.play() [​](https://docs.runanywhere.ai/kotlin/tts/synthesize#simple-speak-api) Simple Speak API ------------------------------------------------------------------------------------------- For convenience, use `speak()` which handles synthesis and playback: Copy Ask AI // Speak text aloud (handles audio playback automatically) val result = RunAnywhere.speak( text = "Hello, this is a test message", options = TTSOptions(rate = 1.0f) ) println("Duration: ${result.duration}s") [​](https://docs.runanywhere.ai/kotlin/tts/synthesize#ttsoutput) TTSOutput ----------------------------------------------------------------------------- The synthesis result object: | Property | Type | Description | | --- | --- | --- | | `audioData` | `ByteArray` | Synthesized audio bytes | | `format` | `AudioFormat` | Audio format (PCM, WAV, etc.) | | `duration` | `Double` | Duration in seconds | | `phonemeTimestamps` | `List?` | Phoneme timing | | `metadata` | `TTSSynthesisMetadata` | Processing metrics | [​](https://docs.runanywhere.ai/kotlin/tts/synthesize#ttsoptions) TTSOptions ------------------------------------------------------------------------------- Customize voice synthesis: Copy Ask AI data class TTSOptions( val voice: String? = null, // Voice ID (uses loaded voice if null) val language: String = "en-US", // Language code val rate: Float = 1.0f, // Speed (0.0-2.0) val pitch: Float = 1.0f, // Pitch (0.0-2.0) val volume: Float = 1.0f, // Volume (0.0-1.0) val audioFormat: AudioFormat = AudioFormat.PCM, val sampleRate: Int = 22050, val useSSML: Boolean = false // Enable SSML markup ) [​](https://docs.runanywhere.ai/kotlin/tts/synthesize#example-custom-voice-settings) Example: Custom Voice Settings ---------------------------------------------------------------------------------------------------------------------- Copy Ask AI val output = RunAnywhere.synthesize( text = "The quick brown fox jumps over the lazy dog.", options = TTSOptions( rate = 0.8f, // Slower speech pitch = 1.2f, // Higher pitch volume = 0.9f ) ) [​](https://docs.runanywhere.ai/kotlin/tts/synthesize#example-playing-audio-with-audiotrack) Example: Playing Audio with AudioTrack -------------------------------------------------------------------------------------------------------------------------------------- Copy Ask AI suspend fun playAudio(audioData: ByteArray, sampleRate: Int = 22050) { val audioTrack = AudioTrack.Builder() .setAudioAttributes( AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_MEDIA) .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH) .build() ) .setAudioFormat( android.media.AudioFormat.Builder() .setEncoding(android.media.AudioFormat.ENCODING_PCM_16BIT) .setSampleRate(sampleRate) .setChannelMask(android.media.AudioFormat.CHANNEL_OUT_MONO) .build() ) .setBufferSizeInBytes(audioData.size) .setTransferMode(AudioTrack.MODE_STATIC) .build() audioTrack.write(audioData, 0, audioData.size) audioTrack.play() } [​](https://docs.runanywhere.ai/kotlin/tts/synthesize#example-text-to-speech-viewmodel) Example: Text-to-Speech ViewModel ---------------------------------------------------------------------------------------------------------------------------- Copy Ask AI class TTSViewModel : ViewModel() { private val _isSpeaking = MutableStateFlow(false) val isSpeaking: StateFlow = _isSpeaking init { viewModelScope.launch { // Load TTS voice on init RunAnywhere.loadTTSVoice("en-us-default") } } fun speak(text: String) { viewModelScope.launch { _isSpeaking.value = true try { RunAnywhere.speak(text, TTSOptions(rate = 1.0f)) } finally { _isSpeaking.value = false } } } fun stopSpeaking() { viewModelScope.launch { RunAnywhere.stopSpeaking() _isSpeaking.value = false } } } [​](https://docs.runanywhere.ai/kotlin/tts/synthesize#check-speaking-status) Check Speaking Status ----------------------------------------------------------------------------------------------------- Copy Ask AI // Check if currently speaking val isSpeaking = RunAnywhere.isSpeaking() // Stop current playback RunAnywhere.stopSpeaking() [​](https://docs.runanywhere.ai/kotlin/tts/synthesize#synthesis-metadata) Synthesis Metadata ----------------------------------------------------------------------------------------------- Copy Ask AI val output = RunAnywhere.synthesize(text, options) println("Voice: ${output.metadata.voice}") println("Language: ${output.metadata.language}") println("Processing time: ${output.metadata.processingTime}s") println("Characters: ${output.metadata.characterCount}") println("Speed: ${output.metadata.charactersPerSecond} char/s") [STT Options](https://docs.runanywhere.ai/kotlin/stt/options) [Streaming TTS](https://docs.runanywhere.ai/kotlin/tts/stream) ⌘I --- # Voice Agent - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/kotlin/voice-agent#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation Kotlin SDK Voice Agent On this page * [Overview](https://docs.runanywhere.ai/kotlin/voice-agent#overview) * [Configure Voice Agent](https://docs.runanywhere.ai/kotlin/voice-agent#configure-voice-agent) * [VoiceAgentConfiguration](https://docs.runanywhere.ai/kotlin/voice-agent#voiceagentconfiguration) * [Process Voice Turn](https://docs.runanywhere.ai/kotlin/voice-agent#process-voice-turn) * [VoiceAgentResult](https://docs.runanywhere.ai/kotlin/voice-agent#voiceagentresult) * [Voice Session (Event-Driven)](https://docs.runanywhere.ai/kotlin/voice-agent#voice-session-event-driven) * [VoiceSessionEvent](https://docs.runanywhere.ai/kotlin/voice-agent#voicesessionevent) * [Session Control](https://docs.runanywhere.ai/kotlin/voice-agent#session-control) * [Example: Complete Voice Assistant](https://docs.runanywhere.ai/kotlin/voice-agent#example-complete-voice-assistant) * [Component States](https://docs.runanywhere.ai/kotlin/voice-agent#component-states) * [Performance Optimization](https://docs.runanywhere.ai/kotlin/voice-agent#performance-optimization) * [Typical Latencies (Pixel 7)](https://docs.runanywhere.ai/kotlin/voice-agent#typical-latencies-pixel-7) * [Related](https://docs.runanywhere.ai/kotlin/voice-agent#related) [​](https://docs.runanywhere.ai/kotlin/voice-agent#overview) Overview ------------------------------------------------------------------------ The Voice Agent orchestrates the complete voice interaction pipeline: **VAD → STT → LLM → TTS**. This enables full conversational AI with a single API. [​](https://docs.runanywhere.ai/kotlin/voice-agent#configure-voice-agent) Configure Voice Agent -------------------------------------------------------------------------------------------------- Copy Ask AI RunAnywhere.configureVoiceAgent(VoiceAgentConfiguration( sttModelId = "whisper-tiny", llmModelId = "qwen-0.5b", ttsVoiceId = "en-us-default", systemPrompt = "You are a helpful assistant. Keep responses brief.", interruptionEnabled = true )) [​](https://docs.runanywhere.ai/kotlin/voice-agent#voiceagentconfiguration) VoiceAgentConfiguration ------------------------------------------------------------------------------------------------------ Copy Ask AI data class VoiceAgentConfiguration( val sttModelId: String, // Speech-to-text model val llmModelId: String, // Language model val ttsVoiceId: String, // Text-to-speech voice val systemPrompt: String? = null, // LLM system prompt val vadConfiguration: VADConfiguration? = null, val interruptionEnabled: Boolean = true // Allow user interruption ) [​](https://docs.runanywhere.ai/kotlin/voice-agent#process-voice-turn) Process Voice Turn -------------------------------------------------------------------------------------------- Process a complete voice turn (listen → transcribe → respond → speak): Copy Ask AI val audioData = // ... recorded audio from user val result = RunAnywhere.processVoice(audioData) println("User said: ${result.transcription}") println("AI response: ${result.response}") println("Total latency: ${result.totalLatencyMs}ms") // Play the response audio result.audioData?.let { audio -> audioPlayer.play(audio) } [​](https://docs.runanywhere.ai/kotlin/voice-agent#voiceagentresult) VoiceAgentResult ---------------------------------------------------------------------------------------- | Property | Type | Description | | --- | --- | --- | | `transcription` | `String` | User’s transcribed speech | | `response` | `String` | AI’s text response | | `audioData` | `ByteArray?` | Synthesized response audio | | `totalLatencyMs` | `Double` | Total processing time | | `sttLatencyMs` | `Double` | Speech-to-text time | | `llmLatencyMs` | `Double` | LLM generation time | | `ttsLatencyMs` | `Double` | Text-to-speech time | [​](https://docs.runanywhere.ai/kotlin/voice-agent#voice-session-event-driven) Voice Session (Event-Driven) -------------------------------------------------------------------------------------------------------------- Start a continuous voice session with event streaming: Copy Ask AI lifecycleScope.launch { RunAnywhere.startVoiceSession() .collect { event -> when (event) { is VoiceSessionEvent.Listening -> { updateUI("Listening...") showMicrophoneActive() } is VoiceSessionEvent.Transcribed -> { updateUI("You: ${event.text}") } is VoiceSessionEvent.Thinking -> { updateUI("Thinking...") showLoadingIndicator() } is VoiceSessionEvent.Responded -> { updateUI("AI: ${event.text}") } is VoiceSessionEvent.Speaking -> { updateUI("Speaking...") } is VoiceSessionEvent.Idle -> { updateUI("Ready") } is VoiceSessionEvent.Error -> { showError(event.message) } } } } [​](https://docs.runanywhere.ai/kotlin/voice-agent#voicesessionevent) VoiceSessionEvent ------------------------------------------------------------------------------------------ Copy Ask AI sealed class VoiceSessionEvent { object Listening : VoiceSessionEvent() data class Transcribed(val text: String) : VoiceSessionEvent() object Thinking : VoiceSessionEvent() data class Responded(val text: String) : VoiceSessionEvent() object Speaking : VoiceSessionEvent() object Idle : VoiceSessionEvent() data class Error(val message: String) : VoiceSessionEvent() } [​](https://docs.runanywhere.ai/kotlin/voice-agent#session-control) Session Control -------------------------------------------------------------------------------------- Copy Ask AI // Stop the voice session RunAnywhere.stopVoiceSession() // Check if session is active val isActive = RunAnywhere.isVoiceSessionActive() // Clear conversation history RunAnywhere.clearVoiceConversation() // Update system prompt mid-session RunAnywhere.setVoiceSystemPrompt("You are now a coding assistant.") [​](https://docs.runanywhere.ai/kotlin/voice-agent#example-complete-voice-assistant) Example: Complete Voice Assistant ------------------------------------------------------------------------------------------------------------------------- Copy Ask AI class VoiceAssistantActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_voice_assistant) lifecycleScope.launch { // Configure voice agent RunAnywhere.configureVoiceAgent(VoiceAgentConfiguration( sttModelId = "whisper-tiny", llmModelId = "qwen-0.5b", ttsVoiceId = "en-us-default", systemPrompt = """ You are a helpful voice assistant. Keep responses under 2 sentences. Be friendly and conversational. """.trimIndent() )) // Check if ready if (!RunAnywhere.isVoiceAgentReady()) { showMessage("Loading models...") RunAnywhere.initializeVoiceAgentWithLoadedModels() } } startButton.setOnClickListener { startVoiceSession() } stopButton.setOnClickListener { lifecycleScope.launch { RunAnywhere.stopVoiceSession() } } } private fun startVoiceSession() { lifecycleScope.launch { RunAnywhere.startVoiceSession() .collect { event -> runOnUiThread { when (event) { is VoiceSessionEvent.Listening -> { statusText.text = "🎤 Listening..." micButton.setColorFilter(Color.RED) } is VoiceSessionEvent.Transcribed -> { transcriptionText.text = event.text } is VoiceSessionEvent.Thinking -> { statusText.text = "🤔 Thinking..." } is VoiceSessionEvent.Responded -> { responseText.text = event.text } is VoiceSessionEvent.Speaking -> { statusText.text = "🔊 Speaking..." } is VoiceSessionEvent.Idle -> { statusText.text = "Ready" micButton.clearColorFilter() } is VoiceSessionEvent.Error -> { Toast.makeText(this@VoiceAssistantActivity, event.message, Toast.LENGTH_SHORT).show() } } } } } } } [​](https://docs.runanywhere.ai/kotlin/voice-agent#component-states) Component States ---------------------------------------------------------------------------------------- Check individual component readiness: Copy Ask AI val states = RunAnywhere.voiceAgentComponentStates() println("STT ready: ${states.sttReady}") println("LLM ready: ${states.llmReady}") println("TTS ready: ${states.ttsReady}") println("VAD ready: ${states.vadReady}") [​](https://docs.runanywhere.ai/kotlin/voice-agent#performance-optimization) Performance Optimization -------------------------------------------------------------------------------------------------------- **Minimize total latency:** Use smaller models (whisper-tiny, 0.5B LLM), enable streaming for both LLM and TTS, and preload all models at app startup. ### [​](https://docs.runanywhere.ai/kotlin/voice-agent#typical-latencies-pixel-7) Typical Latencies (Pixel 7) | Stage | Latency | | --- | --- | | STT | 200-400ms for 5s audio | | LLM | 150-300ms for 50 tokens | | TTS | 100-200ms for short responses | | **Total round-trip** | **500-900ms** | [​](https://docs.runanywhere.ai/kotlin/voice-agent#related) Related ---------------------------------------------------------------------- [VAD\ ---\ \ Voice Activity Detection](https://docs.runanywhere.ai/kotlin/vad) [STT\ ---\ \ Speech-to-Text](https://docs.runanywhere.ai/kotlin/stt/transcribe) [TTS\ ---\ \ Text-to-Speech](https://docs.runanywhere.ai/kotlin/tts/synthesize) [LLM\ ---\ \ Text Generation](https://docs.runanywhere.ai/kotlin/llm/chat) [Voice Activity Detection](https://docs.runanywhere.ai/kotlin/vad) [Configuration](https://docs.runanywhere.ai/kotlin/configuration) ⌘I --- # chat() - RunAnywhere Documentation [Skip to main content](https://docs.runanywhere.ai/react-native/llm/chat#content-area) [RunAnywhere Documentation home page![light logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)![dark logo](https://mintcdn.com/runanywhere/LBew9r1yliJTxAIH/logo-gradient.svg?fit=max&auto=format&n=LBew9r1yliJTxAIH&q=85&s=8321e635ba8217e2714200582a9b09a8)](https://docs.runanywhere.ai/) Search... ⌘KAsk AI Search... Navigation LLM (Language Models) chat() On this page * [Overview](https://docs.runanywhere.ai/react-native/llm/chat#overview) * [Basic Usage](https://docs.runanywhere.ai/react-native/llm/chat#basic-usage) * [API Reference](https://docs.runanywhere.ai/react-native/llm/chat#api-reference) * [Parameters](https://docs.runanywhere.ai/react-native/llm/chat#parameters) * [Returns](https://docs.runanywhere.ai/react-native/llm/chat#returns) * [Throws](https://docs.runanywhere.ai/react-native/llm/chat#throws) * [Examples](https://docs.runanywhere.ai/react-native/llm/chat#examples) * [Simple Q&A](https://docs.runanywhere.ai/react-native/llm/chat#simple-q%26a) * [React Component](https://docs.runanywhere.ai/react-native/llm/chat#react-component) * [With Error Handling](https://docs.runanywhere.ai/react-native/llm/chat#with-error-handling) * [Chat vs Generate](https://docs.runanywhere.ai/react-native/llm/chat#chat-vs-generate) * [Related](https://docs.runanywhere.ai/react-native/llm/chat#related) [​](https://docs.runanywhere.ai/react-native/llm/chat#overview) Overview --------------------------------------------------------------------------- The `chat()` method provides the simplest way to interact with an LLM. It takes a prompt and returns just the response text, making it perfect for quick integrations. [​](https://docs.runanywhere.ai/react-native/llm/chat#basic-usage) Basic Usage --------------------------------------------------------------------------------- Copy Ask AI import { RunAnywhere } from '@runanywhere/core' // Simple question const response = await RunAnywhere.chat('What is the capital of France?') console.log(response) // "Paris is the capital of France." // Follow-up (stateless - each call is independent) const answer = await RunAnywhere.chat('What is 2 + 2?') console.log(answer) // "4" [​](https://docs.runanywhere.ai/react-native/llm/chat#api-reference) API Reference ------------------------------------------------------------------------------------- Copy Ask AI await RunAnywhere.chat(prompt: string): Promise ### [​](https://docs.runanywhere.ai/react-native/llm/chat#parameters) Parameters | Parameter | Type | Description | | --- | --- | --- | | `prompt` | `string` | The user’s message or question | ### [​](https://docs.runanywhere.ai/react-native/llm/chat#returns) Returns | Type | Description | | --- | --- | | `Promise` | The generated response text | ### [​](https://docs.runanywhere.ai/react-native/llm/chat#throws) Throws | Error Code | Description | | --- | --- | | `notInitialized` | SDK not initialized | | `modelNotLoaded` | No LLM model loaded | | `generationFailed` | Generation failed | [​](https://docs.runanywhere.ai/react-native/llm/chat#examples) Examples --------------------------------------------------------------------------- ### [​](https://docs.runanywhere.ai/react-native/llm/chat#simple-q&a) Simple Q&A Copy Ask AI const capital = await RunAnywhere.chat('What is the capital of Japan?') // "Tokyo is the capital of Japan." const math = await RunAnywhere.chat('Calculate 15% of 200') // "15% of 200 is 30." const translation = await RunAnywhere.chat('Translate "Hello" to Spanish') // "Hola" ### [​](https://docs.runanywhere.ai/react-native/llm/chat#react-component) React Component ChatComponent.tsx Copy Ask AI import React, { useState } from 'react' import { View, TextInput, Button, Text } from 'react-native' import { RunAnywhere } from '@runanywhere/core' export function ChatComponent() { const [input, setInput] = useState('') const [response, setResponse] = useState('') const [loading, setLoading] = useState(false) const handleSend = async () => { if (!input.trim()) return setLoading(true) try { const answer = await RunAnywhere.chat(input) setResponse(answer) } catch (error) { setResponse('Error: ' + (error as Error).message) } finally { setLoading(false) } } return (