forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchat.py
More file actions
2175 lines (1931 loc) · 86.8 KB
/
Copy pathchat.py
File metadata and controls
2175 lines (1931 loc) · 86.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import binascii
import json
import tempfile
import uuid
import re
import base64
from datetime import datetime, timezone
from typing import List, Optional
from pathlib import Path
from utils.executors import critical_executor, db_executor, llm_executor, storage_executor, sync_executor, run_blocking
from fastapi import (
APIRouter,
Depends,
Header,
HTTPException,
Query,
Request,
UploadFile,
File,
Form,
WebSocket,
WebSocketDisconnect,
)
from fastapi.responses import StreamingResponse
from multipart.multipart import shutil
from pydantic import BaseModel
import database.chat as chat_db
from utils.chat_session_target import resolve_chat_target
import database.llm_usage as llm_usage_db
from database.apps import record_app_usage
from models.app import App, UsageHistoryType
from models.chat import (
ChatEvidenceEnvelope,
ChatSession,
Message,
SendMessageRequest,
MessageSender,
ResponseMessage,
MessageConversation,
FileChat,
RateMessageRequest,
ShareChatMessagesRequest,
)
from utils.apps import get_available_app_by_id
from utils.conversation_helpers import extract_memory_ids
from utils.chat import (
acquire_chat_session,
emit_stream_error_fallback,
initial_message_util,
process_voice_message_segment_stream,
resolve_voice_message_language,
transcribe_voice_message_segment,
transcribe_pcm_bytes,
)
from utils.sync.files import retrieve_file_paths, decode_files_to_wav
from utils.stt.streaming import STTService, connect_stt_socket_with_fallback, drain_stt_socket
from utils.stt.streaming import get_stt_service_for_language, process_audio_modulate, process_audio_parakeet
from utils.stt.provider_resilience import close_rejected_socket, fallback_socket_is_serving
from utils.stt.pre_recorded import get_prerecorded_service
from config.prerecorded_stt import TranscriptionOutcome
from config.stt_provider_policy import MODULATE_PROVIDER, STTServingSurface, provider_for_service
from utils.stt.outcomes import TranscriptionFailure, failure_from_exception
from utils.observability.transcription import TranscriptionAttempt
from utils.llm.goals import extract_and_update_goal_progress
from database.redis_db import try_acquire_goal_extraction_lock, check_rate_limit, store_chat_share, get_chat_share
from database.users import set_chat_message_rating_score
from utils.chat_rating_triage import extract_rating_triage_fields
from utils.feedback import record_chat_message_feedback
from utils.rate_limit_config import get_effective_limit, RATE_LIMIT_SHADOW
from utils.llm.gateway_client import CHAT_AGENT_ROUTE_DIRECT, get_chat_agent_route
from utils.subscription import enforce_chat_quota, is_trial_paywalled
from utils import share_links
from utils.other import endpoints as auth, storage
from utils.other.chat_file import FileChatTool, UnsupportedChatFileError
from utils.multipart import (
CHAT_FILE_MAX_PART_SIZE,
MultipartMaxPartSizeRoute,
VOICE_MESSAGE_MAX_PART_SIZE,
max_part_size,
parse_multipart_form,
)
from utils.retrieval.graph import execute_chat_stream
from utils.llm.usage_tracker import set_usage_context, reset_usage_context, Features
from utils.users import get_user_display_name
from utils.log_sanitizer import sanitize_pii
from utils.chat_followup import followup_content_blocks
from utils.observability import submit_langsmith_feedback
from utils.observability.fallback import record_fallback
from utils.journey_metrics_contract import resolve_client_kind, resolve_client_kind_from_headers
from utils.observability.journeys import ClientJourneyAttempt, JourneyAttempt
from utils.voice_duration_limiter import (
MAX_SESSION_DURATION_S,
compute_pcm_duration_ms,
read_wav_duration_ms,
try_consume_budget,
try_reserve_session_budget,
settle_reserved_duration,
record_actual_duration,
)
from testing.parity_pack_v0.live_capture import SurfaceParityCapture
import logging
logger = logging.getLogger(__name__)
router = APIRouter(route_class=MultipartMaxPartSizeRoute)
# WS idle timeout: close if no audio bytes received for this long
_WS_IDLE_TIMEOUT_S = 60
# Hard body-size cap for octet-stream uploads (200 MB).
# Prevents memory exhaustion from oversized payloads regardless of budget.
_MAX_PCM_BODY_BYTES = 200_000_000
class VoiceMessageTranscriptionResponse(BaseModel):
transcript: str
language: Optional[str] = None
stt_provider: Optional[str] = None
stt_model: Optional[str] = None
outcome: Optional[TranscriptionOutcome] = None
class TranscriptionErrorDetail(BaseModel):
error: str
outcome: TranscriptionOutcome
provider: str
retryable: bool
message: str
class TranscriptionErrorResponse(BaseModel):
detail: TranscriptionErrorDetail
def _transcription_http_error(failure: TranscriptionFailure) -> HTTPException:
logger.warning(
'Transcription request failed: outcome=%s provider=%s retryable=%s',
failure.outcome.value,
failure.provider,
failure.retryable,
)
return HTTPException(status_code=failure.status_code, detail=failure.as_detail())
def _cleanup_temp_voice_wavs(paths: List[str], uid: str) -> None:
for path in paths:
if path.startswith(f'/tmp/{uid}_'):
try:
Path(path).unlink()
except OSError:
pass
class MessageReportResponse(BaseModel):
message: str
class ChatRatingResponse(BaseModel):
status: str
class ShareChatMessagesResponse(BaseModel):
url: str
token: str
class SharedChatMessage(BaseModel):
id: str
text: str
sender: str
created_at: Optional[str] = None
class SharedChatMessagesResponse(BaseModel):
sender_name: str
messages: List[SharedChatMessage] = []
count: int
def _parse_context_keywords(raw: Optional[str]) -> List[str]:
if not raw:
return []
keywords = []
seen = set()
for item in raw.split(','):
keyword = item.strip()
if len(keyword) < 2 or len(keyword) > 80:
continue
key = keyword.lower()
if key in seen:
continue
seen.add(key)
keywords.append(keyword)
if len(keywords) >= 100:
break
return keywords
def _mobile_chat_stream_succeeded(frame: str) -> bool:
"""A mobile answer succeeds only at a terminal frame with renderable text."""
if not frame.startswith('done: '):
return False
try:
payload = json.loads(base64.b64decode(frame.removeprefix('done: ').strip()).decode('utf-8'))
except (ValueError, TypeError, UnicodeDecodeError, json.JSONDecodeError):
return False
answer = payload.get('text') if isinstance(payload, dict) else None
return isinstance(answer, str) and bool(answer.strip())
def _mobile_chat_stream_failed(frame: str) -> bool:
"""Typed in-band errors are failures even when a fallback done frame follows."""
return frame.lstrip().startswith('error: ')
def filter_messages(messages, app_id):
logger.info(f'filter_messages {len(messages)} {app_id}')
collected = []
for message in messages:
if message.sender == MessageSender.ai and message.plugin_id != app_id:
break
collected.append(message)
logger.info(f'filter_messages output: {len(collected)}')
return collected
def _build_quota_exceeded_reply(
uid: str,
data: SendMessageRequest,
compat_app_id: Optional[str],
detail: dict,
chat_session: Optional[ChatSession] = None,
) -> ResponseMessage:
"""Persist the user's question + a canned AI reply and return it.
Both messages join `chat_session` when the request named one. Without it the
turn is stored unthreaded: the client shows it optimistically against the
session the user is looking at, and then it disappears on the next history
load, because that read is scoped to the session and these rows belong to no
session at all.
Mobile clients render the reply as a normal AI message, so users on
older builds without structured 402 handling at least see *why* nothing
happened instead of a silent failure. Desktop never reaches this path —
its client-side quota pre-check in AgentBridge throws BridgeError.quotaExceeded
before the request fires.
"""
now = datetime.now(timezone.utc)
user_msg = Message(
id=str(uuid.uuid4()),
text=data.text,
created_at=now,
sender='human',
type='text',
app_id=compat_app_id,
chat_session_id=chat_session.id if chat_session else None,
)
chat_db.add_message(uid, user_msg.model_dump())
if chat_session:
chat_db.add_message_to_chat_session(uid, chat_session.id, user_msg.id)
plan = detail.get('plan') or 'Free'
unit = detail.get('unit')
limit = detail.get('limit')
reset_at = detail.get('reset_at')
if unit == 'cost_usd' and isinstance(limit, (int, float)):
limit_phrase = f"your ${int(limit)} monthly AI compute budget"
elif isinstance(limit, (int, float)):
limit_phrase = f"your {int(limit)} monthly chat question limit"
else:
limit_phrase = "your monthly chat limit"
reset_phrase = ''
if reset_at:
try:
reset_dt = datetime.fromtimestamp(int(reset_at), tz=timezone.utc)
reset_phrase = f' Your limit resets on {reset_dt.strftime("%B %-d")}.'
except (TypeError, ValueError):
pass
canned = (
f"You've reached {limit_phrase} on the {plan} plan.{reset_phrase}\n\n"
"Upgrade your plan to keep chatting, or bring your own API keys in Settings "
"to use Omi free."
)
ai_msg = Message(
id=str(uuid.uuid4()),
text=canned,
created_at=datetime.now(timezone.utc),
sender='ai',
type='text',
app_id=compat_app_id,
chat_session_id=chat_session.id if chat_session else None,
)
chat_db.add_message(uid, ai_msg.model_dump())
if chat_session:
chat_db.add_message_to_chat_session(uid, chat_session.id, ai_msg.id)
return ResponseMessage(**ai_msg.model_dump(), ask_for_nps=False)
def _build_quota_accounting_unavailable_reply(compat_app_id: Optional[str]) -> ResponseMessage:
"""SSE-visible retry copy when Free-plan counter persistence fails.
Returned as an in-memory ``done:`` frame only — do not persist a human or AI
message here. Persisting before accounting succeeds would orphan user text on
retries (fresh message ids / idempotency keys under the same outage).
"""
ai_msg = Message(
id=str(uuid.uuid4()),
text=("Usage accounting is temporarily unavailable. Please retry in a moment — " "your message was not saved."),
created_at=datetime.now(timezone.utc),
sender='ai',
type='text',
app_id=compat_app_id,
)
return ResponseMessage(**ai_msg.model_dump(), ask_for_nps=False)
def _record_chat_quota_question(
uid: str,
*,
idempotency_key: str,
source: str,
message_id: Optional[str] = None,
chat_session_id: Optional[str] = None,
platform: Optional[str] = None,
) -> None:
"""Persist the free-plan question counter. Callers that are about to invoke a
billable provider must treat failures as request failures (fail-closed)."""
llm_usage_db.record_chat_quota_question(
uid,
idempotency_key=idempotency_key,
source=source,
message_id=message_id,
chat_session_id=chat_session_id,
platform=platform,
)
def _record_chat_quota_question_best_effort(
uid: str,
*,
idempotency_key: str,
source: str,
message_id: Optional[str] = None,
chat_session_id: Optional[str] = None,
platform: Optional[str] = None,
) -> None:
"""Best-effort counter write for paths where the billable work already happened
(e.g. voice stream after a visible ``message:`` frame)."""
try:
_record_chat_quota_question(
uid,
idempotency_key=idempotency_key,
source=source,
message_id=message_id,
chat_session_id=chat_session_id,
platform=platform,
)
except Exception:
logger.exception('Failed to record chat quota question source=%s uid=%s', source, uid)
def _required_chat_quota_provider() -> str | None:
# Direct agent chat consumes managed Anthropic unless an Anthropic BYOK key
# is on the request. Other BYOK providers must stay metered on this path.
return 'anthropic' if get_chat_agent_route() == CHAT_AGENT_ROUTE_DIRECT else None
@router.post('/v2/messages', tags=['chat'], response_model=ResponseMessage)
def send_message(
data: SendMessageRequest,
request: Request,
plugin_id: Optional[str] = None,
app_id: Optional[str] = None,
chat_session_id: Optional[str] = None,
uid: str = Depends(auth.with_rate_limit(auth.get_current_user_uid, "chat:send_message")),
x_app_platform: Optional[str] = Header(None, alias='X-App-Platform'),
):
# Catalog hard-cap exhaustion is returned as a canned AI reply instead of a
# raw 402 (which older mobile clients render as a generic server error).
# Catalog overage plans return normally. Desktop pre-checks via
# /v1/users/me/usage-quota and never reaches this path when over.
try:
enforce_chat_quota(uid, platform=x_app_platform, required_llm_provider=_required_chat_quota_provider())
except HTTPException as exc:
if exc.status_code != 402 or not isinstance(exc.detail, dict):
raise
if exc.detail.get('error') != 'quota_exceeded':
raise
_compat_id = app_id or plugin_id
if _compat_id in ['null', '']:
_compat_id = None
# Resolved here rather than at the happy path's `_resolve_chat_session`
# below: quota enforcement returns before that line is ever reached, and
# the canned reply still belongs in the session the request named.
_quota_target = resolve_chat_target(uid, _compat_id, chat_session_id)
response_msg = _build_quota_exceeded_reply(
uid,
data,
_quota_target.app_id,
exc.detail,
ChatSession(**_quota_target.session) if _quota_target.session else None,
)
def _quota_exceeded_stream():
encoded = base64.b64encode(bytes(response_msg.model_dump_json(), 'utf-8')).decode('utf-8')
yield f"done: {encoded}\n\n"
return StreamingResponse(_quota_exceeded_stream(), media_type="text/event-stream")
compat_app_id = app_id or plugin_id
logger.info(f'send_message {sanitize_pii(data.text)} {compat_app_id} {uid}')
if compat_app_id in ['null', '']:
compat_app_id = None
# get chat session — a named session also decides which app this turn runs as
target = resolve_chat_target(uid, compat_app_id, chat_session_id)
compat_app_id = target.app_id
chat_session = ChatSession(**target.session) if target.session else None
message = Message(
id=str(uuid.uuid4()),
text=data.text,
created_at=datetime.now(timezone.utc),
sender='human',
type='text',
app_id=compat_app_id,
)
# Ensure chat session exists when files are attached
if data.file_ids and not chat_session:
chat_session = acquire_chat_session(uid, compat_app_id)
chat_session = ChatSession(**chat_session) if isinstance(chat_session, dict) else chat_session
if data.file_ids is not None and chat_session:
new_file_ids = chat_session.retrieve_new_file(data.file_ids)
chat_session.add_file_ids(data.file_ids)
chat_db.add_files_to_chat_session(uid, chat_session.id, data.file_ids)
if len(new_file_ids) > 0:
message.files_id = new_file_ids
files = chat_db.get_chat_files(uid, new_file_ids)
files = [FileChat(**f) if f else None for f in files]
message.files = files
if chat_session:
message.chat_session_id = chat_session.id
# Fail-closed before persisting the human turn or starting billable work:
# a Firestore outage must not leave Free-plan turns uncounted, orphan
# messages on retry, or return a bare HTTP 503 that mobile SSE silently drops.
try:
_record_chat_quota_question(
uid,
idempotency_key=f'v2_messages:{message.id}',
source='v2_messages',
message_id=message.id,
chat_session_id=message.chat_session_id,
platform=x_app_platform,
)
except Exception:
logger.exception('Failed to record chat quota question source=v2_messages uid=%s', uid)
response_msg = _build_quota_accounting_unavailable_reply(compat_app_id)
def _quota_accounting_unavailable_stream():
encoded = base64.b64encode(bytes(response_msg.model_dump_json(), 'utf-8')).decode('utf-8')
yield f"done: {encoded}\n\n"
return StreamingResponse(_quota_accounting_unavailable_stream(), media_type="text/event-stream")
if chat_session:
chat_db.add_message_to_chat_session(uid, chat_session.id, message.id)
chat_db.add_message(uid, message.model_dump())
# Check for goal progress (background) — rate-limited to one call per user per 5 min
if try_acquire_goal_extraction_lock(uid):
llm_executor.submit(extract_and_update_goal_progress, uid, data.text)
app = get_available_app_by_id(compat_app_id, uid)
app = App(**app) if app else None
app_id_from_app = app.id if app else None
# Skip a malformed/legacy stored message rather than 500 the whole chat send.
messages = list(
reversed(
Message.deserialize_many_safe(
chat_db.get_cache_aligned_messages(uid, app_id=compat_app_id, chat_session_id=message.chat_session_id),
on_error=lambda record, exc: logger.warning(
'Skipping malformed chat message %s for uid=%s: %s',
record.get('id') if isinstance(record, dict) else None,
uid,
type(exc).__name__,
),
)
)
)
def process_message(response: str, callback_data: dict):
memories = callback_data.get('memories_found', [])
ask_for_nps = callback_data.get('ask_for_nps', False)
langsmith_run_id = callback_data.get('langsmith_run_id')
prompt_name = callback_data.get('prompt_name')
prompt_commit = callback_data.get('prompt_commit')
chart_data = callback_data.get('chart_data')
evidence_payload = callback_data.get('evidence')
evidence = None
if evidence_payload is not None:
try:
evidence = ChatEvidenceEnvelope.model_validate(evidence_payload)
except ValueError as evidence_exc:
# Evidence is optional UI chrome. A malformed tool reference must
# never prevent persistence or delivery of the answer text.
logger.warning(
'dropping invalid chat evidence uid=%s error_type=%s',
uid,
type(evidence_exc).__name__,
)
# cited extraction
cited_conversation_idxs = {int(i) for i in re.findall(r'\[(\d+)\]', response)}
if len(cited_conversation_idxs) > 0:
response = re.sub(r'\[\d+\]', '', response)
memories = [memories[i - 1] for i in cited_conversation_idxs if 0 < i and i <= len(memories)]
memories_id = extract_memory_ids(memories) if memories else []
ai_message_id = str(uuid.uuid4())
ai_message = Message(
id=ai_message_id,
text=response,
created_at=datetime.now(timezone.utc),
sender='ai',
app_id=app_id_from_app,
type='text',
memories_id=memories_id,
chart_data=chart_data,
langsmith_run_id=langsmith_run_id, # Store run_id for feedback tracking
prompt_name=prompt_name, # LangSmith prompt name for versioning
prompt_commit=prompt_commit, # LangSmith prompt commit for traceability
evidence=evidence,
# One grounded next question, as a chip the client can tap. Empty for
# any turn that failed or has nothing to go one hop further into.
content_blocks=followup_content_blocks(
ai_message_id,
callback_data.get('followup'),
visible_text=response,
failed=bool(callback_data.get('error')),
),
)
if chat_session:
ai_message.chat_session_id = chat_session.id
chat_db.add_message_to_chat_session(uid, chat_session.id, ai_message.id)
chat_db.add_message(uid, ai_message.model_dump())
ai_message.memories = [MessageConversation(**m) for m in (memories if len(memories) < 5 else memories[:5])]
usage_app_id = app_id_from_app or compat_app_id
if usage_app_id:
try:
record_app_usage(
uid,
usage_app_id,
UsageHistoryType.chat_message_sent,
message_id=ai_message.id,
)
except Exception as analytics_exc:
# Message is already durable; analytics must not change the client-visible id.
logger.error(
'chat stream app usage recording failed for uid=%s message_id=%s: %s',
uid,
ai_message.id,
type(analytics_exc).__name__,
)
return ai_message, ask_for_nps
journey_attempt = JourneyAttempt('chat_response')
mobile_journey_attempt = ClientJourneyAttempt(
'mobile_chat',
resolve_client_kind_from_headers(request.headers),
)
async def generate_stream():
callback_data = {}
answered = False
stream_exhausted = False
streamed_terminal_error = False
# Set usage context for streaming (can't use 'with' across yields)
usage_token = set_usage_context(uid, Features.CHAT)
def emit_done_frame(response: str) -> str:
"""Persist a terminal answer. Typed stream errors stay failed for journey/fallback SLIs.
If Firestore persistence fails, still emit an in-memory ``done:`` frame (same
fail-open contract as ``emit_stream_error_fallback``) so the text client is
not left with only an earlier ``error:`` frame.
"""
persist_outcome = 'degraded'
try:
ai_message, ask_for_nps = process_message(response, callback_data)
except Exception as persist_exc:
logger.error(
'chat stream terminal answer persistence failed for uid=%s: %s',
uid,
type(persist_exc).__name__,
)
persist_outcome = 'exhausted'
ai_message = Message(
id=str(uuid.uuid4()),
text=response,
created_at=datetime.now(timezone.utc),
sender='ai',
app_id=app_id_from_app,
type='text',
)
if chat_session:
ai_message.chat_session_id = chat_session.id
ask_for_nps = False
response_message = ResponseMessage(**ai_message.model_dump())
response_message.ask_for_nps = ask_for_nps
encoded_response = base64.b64encode(bytes(response_message.model_dump_json(), 'utf-8')).decode('utf-8')
if callback_data.get('error'):
journey_attempt.finish('failure')
record_fallback(
component='other',
from_mode='llm_answer',
to_mode='canned_reply',
reason='other',
outcome=persist_outcome,
)
else:
if persist_outcome == 'exhausted':
journey_attempt.finish('failure')
record_fallback(
component='other',
from_mode='llm_answer',
to_mode='canned_reply',
reason='other',
outcome='exhausted',
)
else:
journey_attempt.finish('success')
return f"done: {encoded_response}\n\n"
try:
async for chunk in execute_chat_stream(
uid,
messages,
app,
cited=True,
callback_data=callback_data,
chat_session=chat_session,
context=data.context,
platform=x_app_platform,
client_kind=mobile_journey_attempt.client_kind,
):
if chunk:
if chunk.startswith('error: '):
streamed_terminal_error = True
msg = chunk.replace("\n", "__CRLF__")
yield f'{msg}\n\n'
else:
response = callback_data.get('answer')
if response:
# This is the furthest server-observable client boundary:
# a yielded terminal frame is not a client-render acknowledgement.
yield emit_done_frame(response)
answered = True
if not answered:
# Prefer a staged typed answer (timeout / gateway) even if the producer
# forgot the None sentinel. Only emit the generic canned sorry when no
# typed answer was staged — including persona paths that yield ``error:``
# without setting ``callback_data['answer']`` (those still need ``done:``).
response = callback_data.get('answer')
if response:
yield emit_done_frame(response)
else:
if streamed_terminal_error:
logger.error(
'chat stream ended without an answer uid=%s reason=%s route=%s (error=%s)',
uid,
callback_data.get('error') or 'stream_failure',
callback_data.get('route') or 'unknown',
True,
)
yield await emit_stream_error_fallback(
uid,
app_id_from_app,
chat_session,
label='chat',
error_recorded=bool(callback_data.get('error')),
reason=callback_data.get('error'),
route=callback_data.get('route'),
)
stream_exhausted = True
except asyncio.CancelledError:
journey_attempt.finish('cancelled')
raise
except Exception:
journey_attempt.finish('failure')
raise
finally:
reset_usage_context(usage_token)
if not journey_attempt.finished:
journey_attempt.finish('failure' if stream_exhausted else 'cancelled')
observed_stream = mobile_journey_attempt.observe_stream(
generate_stream(),
success_when=_mobile_chat_stream_succeeded,
failure_when=_mobile_chat_stream_failed,
failure_class='provider_error',
missing_success_class='empty_answer',
)
return StreamingResponse(observed_stream, media_type="text/event-stream")
@router.post('/v2/messages/{message_id}/report', tags=['chat'], response_model=MessageReportResponse)
def report_message(message_id: str, uid: str = Depends(auth.get_current_user_uid)):
result = chat_db.get_message(uid, message_id)
if result is None:
raise HTTPException(status_code=404, detail='Message not found')
message, msg_doc_id = result
if message.sender != 'ai':
raise HTTPException(status_code=400, detail='Only AI messages can be reported')
if message.reported:
raise HTTPException(status_code=400, detail='Message already reported')
chat_db.report_message(uid, msg_doc_id)
return {'message': 'Message reported'}
@router.delete('/v2/messages', tags=['chat'], response_model=Message)
def clear_chat_messages(
app_id: Optional[str] = None,
plugin_id: Optional[str] = None,
chat_session_id: Optional[str] = None,
uid: str = Depends(auth.get_current_user_uid),
):
explicit = bool(chat_session_id)
compat_app_id = app_id or plugin_id
if compat_app_id in ['null', '']:
compat_app_id = None
# get the targeted chat session. Its own app id scopes the delete: the
# message rows carry the session's `plugin_id`, so filtering by the query
# string's app instead deletes the session record and orphans its messages.
target = resolve_chat_target(uid, compat_app_id, chat_session_id)
compat_app_id = target.app_id
chat_session = target.session
chat_session_id = target.session_id
err = chat_db.clear_chat(uid, app_id=compat_app_id, chat_session_id=chat_session_id)
if err:
raise HTTPException(status_code=500, detail='Failed to clear chat')
# clean thread chat file
if chat_session and chat_session.get('id'):
try:
fc_tool = FileChatTool(uid, chat_session['id'])
fc_tool.cleanup()
except ValueError:
# Session not found, continue with cleanup
pass
# clear session
if chat_session_id is not None and not explicit:
chat_db.delete_chat_session(uid, chat_session_id)
return initial_message_util(uid, compat_app_id, chat_session_id=chat_session_id if explicit else None)
@router.post('/v2/initial-message', tags=['chat'], response_model=Message)
def create_initial_message(
app_id: Optional[str] = None,
plugin_id: Optional[str] = None,
uid: str = Depends(auth.with_rate_limit(auth.get_current_user_uid, "chat:initial")),
):
compat_app_id = app_id or plugin_id
return initial_message_util(uid, compat_app_id)
@router.get('/v2/messages', response_model=List[Message], tags=['chat'])
def get_messages(
plugin_id: Optional[str] = None,
app_id: Optional[str] = None,
chat_session_id: Optional[str] = None,
limit: int = Query(100, ge=1, le=1000),
offset: int = Query(0, ge=0),
uid: str = Depends(auth.get_current_user_uid),
):
compat_app_id = app_id or plugin_id
if compat_app_id in ['null', '']:
compat_app_id = None
target = resolve_chat_target(uid, compat_app_id, chat_session_id)
compat_app_id = target.app_id
chat_session_id = target.session_id
messages = chat_db.get_messages(
uid,
limit=limit,
offset=offset,
include_conversations=True,
app_id=compat_app_id,
chat_session_id=chat_session_id,
)
logger.info(f'get_messages {len(messages)} {compat_app_id}')
# Debug: Check for messages with ratings
rated_messages = [m for m in messages if m.get('rating') is not None]
if rated_messages:
logger.info(f'📊 Messages with ratings: {len(rated_messages)}')
for m in rated_messages[:5]: # Show first 5
logger.info(f" - Message {m.get('id')}: rating={m.get('rating')}")
if not messages:
# The greeting belongs to the session that was read, not to whatever
# session `acquire_chat_session` would pick for the app.
return [] if offset > 0 else [initial_message_util(uid, compat_app_id, chat_session_id=chat_session_id)]
return messages
@router.post(
"/v2/voice-messages",
response_class=StreamingResponse,
responses={
200: {
"description": "Server-sent event stream of chat message chunks.",
"content": {"text/event-stream": {"schema": {"type": "string"}}},
}
},
)
@max_part_size(VOICE_MESSAGE_MAX_PART_SIZE)
def create_voice_message_stream(
files: List[UploadFile] = File(...),
language: Optional[str] = Form(None),
uid: str = Depends(auth.with_rate_limit(auth.get_current_user_uid, "voice:message")),
x_app_platform: Optional[str] = Header(None, alias='X-App-Platform'),
):
enforce_chat_quota(uid, platform=x_app_platform, required_llm_provider=_required_chat_quota_provider())
resolved_language = resolve_voice_message_language(uid, language)
stt_provider, _, _stt_model = get_prerecorded_service(resolved_language)
paths: List[str] = []
wav_paths: List[str] = []
def _record_preparation_failure(failure: TranscriptionFailure) -> None:
preparation_attempt = TranscriptionAttempt(
route='voice_chat_sse',
provider=stt_provider,
platform=x_app_platform,
)
preparation_attempt.finish(failure.outcome)
try:
paths = retrieve_file_paths(files, uid)
if not paths:
raise TranscriptionFailure(
TranscriptionOutcome.INVALID_INPUT,
provider=stt_provider,
retryable=False,
)
wav_paths = decode_files_to_wav(paths)
if not wav_paths:
raise TranscriptionFailure(
TranscriptionOutcome.INVALID_INPUT,
provider=stt_provider,
retryable=False,
)
# Daily budget check (first file only — matches actual DG usage).
# A quota rejection is not an STT attempt and therefore is not an
# invalid-input or provider-outcome metric.
# An unreadable duration must not skip the budget check (STT still
# runs on it) — charge the worst case instead of charging nothing.
first_wav = wav_paths[0]
duration_ms = read_wav_duration_ms(first_wav)
budget_duration_ms = duration_ms if duration_ms is not None else MAX_SESSION_DURATION_S * 1000
allowed, used_ms, remaining_ms = try_consume_budget(uid, budget_duration_ms)
if not allowed:
raise HTTPException(status_code=429, detail='Daily transcription budget exhausted')
except TranscriptionFailure as failure:
_record_preparation_failure(failure)
_cleanup_temp_voice_wavs(paths + wav_paths, uid)
raise _transcription_http_error(failure) from failure
except HTTPException as error:
_cleanup_temp_voice_wavs(paths + wav_paths, uid)
if error.status_code == 429:
raise
failure = TranscriptionFailure(
TranscriptionOutcome.INVALID_INPUT,
provider=stt_provider,
retryable=False,
)
_record_preparation_failure(failure)
raise _transcription_http_error(failure) from error
except Exception as error:
failure = failure_from_exception(error, provider=stt_provider)
_record_preparation_failure(failure)
_cleanup_temp_voice_wavs(paths + wav_paths, uid)
raise _transcription_http_error(failure) from error
# process
async def generate_stream():
attempt = TranscriptionAttempt(
route='voice_chat_sse',
provider=stt_provider,
platform=x_app_platform,
# Measured first-wav duration (the only file transcribed); None when
# the WAV header was unreadable, so provider minutes stay measured-only.
audio_seconds=duration_ms / 1000 if duration_ms is not None else None,
)
quota_recorded = False
try:
async for chunk in process_voice_message_segment_stream(
first_wav, uid, language=resolved_language, platform=x_app_platform
):
if chunk.startswith('message: '):
attempt.finish(TranscriptionOutcome.SUCCESS)
if not quota_recorded and chunk.startswith('message: '):
payload = chunk.removeprefix('message: ').strip()
try:
message_data = json.loads(base64.b64decode(payload).decode('utf-8'))
await run_blocking(
db_executor,
_record_chat_quota_question_best_effort,
uid,
idempotency_key=f"v2_voice_messages:{message_data.get('id') or first_wav}",
source='v2_voice_messages',
message_id=message_data.get('id'),
chat_session_id=message_data.get('chat_session_id'),
platform=x_app_platform,
)
quota_recorded = True
except (binascii.Error, UnicodeDecodeError, ValueError, TypeError, json.JSONDecodeError) as exc:
logger.warning('Failed to record voice chat quota question: %s', exc)
yield chunk
if not attempt.finished:
attempt.finish(TranscriptionOutcome.EXPECTED_SILENCE)
except Exception as error:
if attempt.finished:
raise
failure = failure_from_exception(error, provider=stt_provider)
attempt.finish(failure.outcome)
yield f"error: {json.dumps(failure.as_detail(), separators=(',', ':'))}\n\n"
finally:
if not attempt.finished:
attempt.finish(TranscriptionOutcome.UPSTREAM_ERROR)
await run_blocking(storage_executor, _cleanup_temp_voice_wavs, paths + wav_paths, uid)
paths.clear()
wav_paths.clear()
return StreamingResponse(generate_stream(), media_type="text/event-stream")
@router.post(
"/v2/voice-message/transcribe",
response_model=VoiceMessageTranscriptionResponse,
responses={
400: {"model": TranscriptionErrorResponse, "description": "Invalid audio input"},
502: {"model": TranscriptionErrorResponse, "description": "Upstream or unexpected-empty result"},
503: {"model": TranscriptionErrorResponse, "description": "Provider configuration unavailable"},
504: {"model": TranscriptionErrorResponse, "description": "Provider timeout"},
},
)
async def transcribe_voice_message(
request: Request,
uid: str = Depends(auth.with_rate_limit(auth.get_current_user_uid, "voice:transcribe")),
x_app_platform: Optional[str] = Header(None, alias='X-App-Platform'),
):
"""Transcribe audio and return the transcript text.
Accepts two content types:
- multipart/form-data: file upload with optional 'language' form field (mobile)
- application/octet-stream: raw PCM bytes with query params (desktop PTT)
Returns {"transcript": "...", "language": "..."}.
"""
# Trial paywall: reject paywalled desktop PTT before hitting Deepgram.
# Narrow to trial-only on purpose — full enforce_chat_quota here would
# change mobile behavior for users past their existing 30/mo chat cap.
if await run_blocking(db_executor, is_trial_paywalled, uid, x_app_platform):
raise HTTPException(status_code=402, detail={'error': 'quota_exceeded', 'plan_type': 'basic'})
content_type = request.headers.get("content-type", "")
if "application/octet-stream" in content_type:
# Check Content-Length before buffering to reject oversized payloads early
content_length = request.headers.get("content-length")
if content_length:
try:
parsed_content_length = int(content_length)
except ValueError as error:
failure = TranscriptionFailure(