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61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
# 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()

```