# Flare Platform - Güncel Tasarım Dokümanı ## 🏗 Genel Mimari Flare, modüler LLM provider desteği ile çalışan çok adımlı ve akıllı bir orchestration katmanıdır. Provider-agnostic tasarımı sayesinde farklı LLM, TTS ve STT motorları ile çalışabilir. ### Temel Özellikler - ✅ Provider-based mimari (LLM, TTS, STT) - ✅ Intent detection ve parameter extraction - ✅ Akıllı parametre toplama (smart grouping) - ✅ Onay mekanizması (requiresApproval) - ✅ Multi-language destek (LocalizedExample, LocalizedCaption) - ✅ Session-based state machine - ✅ API orchestration ve response mapping - ✅ Activity logging ve audit trail ## 📋 Konfigürasyon Yapısı ### service_config.jsonc - Ana Yapı ```json { "config": { // Provider tanımları "llm_provider": { "name": "spark|gpt4o|gpt4o-mini", "api_key": "enc:...", // Şifrelenmiş "endpoint": "https://...", "settings": { "internal_prompt": "Global LLM yönergesi", "parameter_collection_config": { "max_params_per_question": 2, "smart_grouping": true, "retry_unanswered": true, "collection_prompt": "..." } } }, "tts_provider": { "name": "no_tts|elevenlabs|blaze", "api_key": "enc:...", "endpoint": null, "settings": {} }, "stt_provider": { "name": "no_stt|google|azure|flicker", "api_key": "/path/to/credentials.json", "endpoint": null, "settings": { "language": "tr-TR", "model": "latest_long" } }, "providers": [ // Kullanılabilir provider tanımları ], "users": [...] }, "projects": [...], "apis": [...], "activity_log": [...], "project_id_counter": 1, "last_update_date": null, "last_update_user": null } ``` ### Provider Sistemi #### Provider Config ```json { "type": "llm|tts|stt", "name": "spark", "display_name": "Spark LLM", "requires_endpoint": true, "requires_api_key": true, "requires_repo_info": false, "description": "YTU Cosmos Spark LLM" } ``` #### Provider Settings ```json { "name": "provider_name", "api_key": "enc:encrypted_key", "endpoint": "https://endpoint", "settings": { // Provider-specific ayarlar } } ``` ### Project Yapısı ```json { "id": 1, "name": "project_name", "caption": "Proje Başlığı", "icon": "folder", "description": "Açıklama", "enabled": true, "default_locale": "tr", "supported_locales": ["tr", "en"], "timezone": "Europe/Istanbul", "region": "tr-TR", "versions": [...], "version_id_counter": 1, "deleted": false, "created_date": "2024-01-01T00:00:00Z", "created_by": "username", "last_update_date": null, "last_update_user": null } ``` ### Version Yapısı ```json { "id": 1, "no": 1, "caption": "v1", "description": "Version açıklaması", "published": true, "deleted": false, "general_prompt": "Asistan için genel yönerge", "welcome_prompt": "Hoşgeldin mesajı yönergesi", "llm": { "repo_id": "model-id", "generation_config": {}, "use_fine_tune": false, "fine_tune_zip": "" }, "intents": [...], "created_date": "2024-01-01T00:00:00Z", "created_by": "username", "publish_date": null, "published_by": null } ``` ### Intent Yapısı ```json { "name": "intent_name", "caption": "Intent Başlığı", "requiresApproval": false, "dependencies": [], "examples": [ { "locale_code": "tr", "example": "Örnek cümle" } ], "detection_prompt": "Intent algılama yönergesi", "parameters": [...], "action": "api_name", "fallback_timeout_prompt": "Zaman aşımı mesajı", "fallback_error_prompt": "Hata mesajı" } ``` ### Parameter Yapısı ```json { "name": "param_name", "caption": [ { "locale_code": "tr", "caption": "Parametre Başlığı" } ], "type": "str|int|float|bool|date", "required": true, "variable_name": "variable_name", "extraction_prompt": "Parametre çıkarma yönergesi", "validation_regex": "^pattern$", "invalid_prompt": "Geçersiz değer mesajı", "type_error_prompt": "Tip hatası mesajı" } ``` ### API Yapısı ```json { "name": "api_name", "description": "{{variables.x}} için işlem açıklaması", "url": "https://api-endpoint", "method": "GET|POST|PUT|DELETE", "headers": "{}", // JSON string "body_template": "{}", // JSON string "timeout_seconds": 10, "retry": { "max_attempts": 3, "backoff_seconds": 2, "strategy": "static|exponential" }, "auth": { "enabled": true, "token_endpoint": "https://auth-endpoint", "response_token_path": "access_token", "token_request_body": "{}", "token_refresh_endpoint": null, "token_refresh_body": "{}" }, "response_mappings": [ { "variable_name": "result", "caption": "Sonuç", "type": "str", "json_path": "$.data.result" } ], "response_prompt": "Response insanileştirme yönergesi", "deleted": false, "created_date": "2024-01-01T00:00:00Z", "created_by": "username" } ``` ## 🔄 Session ve State Yönetimi ### Session Özellikleri ```python class Session: session_id: str project_name: str version_number: int version_config: VersionConfig # State machine state: str # idle | await_param | call_api | humanize last_intent: str | None awaiting_parameters: List[str] missing_ask_count: int # Data storage variables: Dict[str, str] auth_tokens: Dict[str, Dict] chat_history: List[Dict[str, str]] # Smart parameter tracking asked_parameters: Dict[str, int] unanswered_parameters: List[str] parameter_ask_rounds: int # Real-time support is_realtime_session: bool active_websocket: Any ``` ### State Machine Flow ``` start_session → welcome_prompt ↓ idle ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ← ↓ ↑ detect_intent → collect_params → approval? → call_api → humanize ↑ ↓ ← await_param ← ``` ## 🔐 Onay Mekanizması Intent'te `requiresApproval: true` olduğunda: 1. **Otomatik parametre ekleme**: `is_approved` parametresi dinamik olarak eklenir 2. **Onay sorusu oluşturma**: API description'daki placeholder'lar değiştirilir 3. **Onay kontrolü**: - Onay verilirse → API çağrısı - Onay verilmezse → İşlem iptali ## 🌍 Multi-Language Destek ### Locale Yönetimi - Project seviyesinde `default_locale` ve `supported_locales` - LocalizedExample ve LocalizedCaption yapıları - Locale JSON dosyaları (`tr.json`, `en.json`, vb.) ### LocaleManager ```python # Locale bilgilerini yönetir LocaleManager.get_locale("tr") LocaleManager.format_date(date, "tr") LocaleManager.parse_date_expression("yarın", "tr") LocaleManager.format_number(1234.56, "tr") ``` ## 🎤 TTS/STT Entegrasyonu ### TTS Providers - **ElevenLabs**: Yüksek kaliteli, çok dilli - **Blaze**: Alternatif TTS - **No TTS**: Devre dışı ### STT Providers - **Google**: Cloud Speech-to-Text - **Azure**: Azure Speech Services - **Flicker**: Alternatif STT - **No STT**: Devre dışı ### Real-time Features - WebSocket-based audio streaming - Voice Activity Detection (VAD) - Noise reduction - Interim results ## 🚀 LLM Provider Desteği ### Spark - YTU Cosmos modelleri - HuggingFace Cloud veya on-premise - Custom fine-tuning desteği ### GPT-4o / GPT-4o-mini - OpenAI API entegrasyonu - Temperature ve max_tokens kontrolü - Maliyet optimizasyonu ### Provider Seçimi ```python # chat_handler.py if llm_provider.name == "spark": llm = SparkLLM(endpoint, token) elif llm_provider.name.startswith("gpt4o"): llm = GPT4oLLM(api_key, model) ``` ## 📡 API Yönetimi ### API Çağrı Süreci 1. **Variable substitution**: `{{variables.xxx}}` → gerçek değerler 2. **Auth token yönetimi**: Otomatik token alma ve yenileme 3. **Retry logic**: Configurable retry stratejisi 4. **Response mapping**: JSON path ile veri çıkarma 5. **Response humanization**: LLM ile insanileştirme ### Auth Mekanizması ```python # Token alma ve cache'leme if api.auth.enabled: token = get_or_refresh_token(api, session) headers["Authorization"] = f"Bearer {token}" ``` ## 🔒 Güvenlik ### Encryption - API key'ler `enc:` prefix ile şifrelenmiş saklanır - Fernet encryption (symmetric) - Environment variable: `FERNET_KEY` ### Authentication - JWT-based session yönetimi - Bcrypt password hashing - Session timeout kontrolü ### Race Condition Koruması - `last_update_date` ile optimistic locking - Thread-safe session store - Concurrent update kontrolü ## 📊 Monitoring ve Logging ### Activity Log ```json { "timestamp": "2024-01-01T00:00:00Z", "username": "admin", "action": "CREATE_PROJECT", "entity_type": "project", "entity_id": 1, "entity_name": "project_name", "details": "Additional info" } ``` ### Log Actions - Project CRUD: CREATE, UPDATE, DELETE, ENABLE, DISABLE - Version: CREATE, UPDATE, PUBLISH, DELETE - API: CREATE, UPDATE, DELETE - Environment: UPDATE_ENVIRONMENT - Import/Export: IMPORT_PROJECT, EXPORT_PROJECT ## 🧪 Test ve Development ### Mock Backend - Scenario-based testing - Configurable responses - Error simulation ### Debug Features - Detailed timestamped logging - Request/Response tracking - Performance metrics ## 🔄 Import/Export ### Project Export Format ```json { "name": "project_name", "caption": "Project Caption", "icon": "folder", "description": "Description", "default_locale": "tr", "supported_locales": ["tr", "en"], "versions": [ { "caption": "v1", "general_prompt": "...", "llm": {...}, "intents": [...] } ] } ``` ## 🚦 Production Deployment ### Docker Support - HuggingFace Spaces uyumlu - Health check endpoint - Environment-based configuration - Volume mount için permission handling ### Environment Variables ```bash FERNET_KEY=... # Encryption key SPARK_TOKEN=... # Spark API token OPENAI_API_KEY=... # GPT-4o key GOOGLE_APPLICATION_CREDENTIALS=... # STT credentials HF_HOME=/app/.cache # HuggingFace cache ``` ### Health Check ```python @app.get("/") def health(): return {"status": "ok"} # Hugging Face için daemon thread threading.Thread(target=run_health_server, daemon=True).start() ```