+
    iS                        ^ RI t ^ RIt^ RIt^ RIt^ RIt^ RIt^ RIt^ RIHt ^ RI	H
t
 ^ RIt^ RItR R lt]! 4        ^ RIHtHt ^ RIHt ^ RIHtHt ^R	IHt ^R
IHt ^RIHt ^RIHtHtHtH t H!t!H"t"H#t#H$t$ ]PJ                  ! R4      t&]! 4        Rs'R R lt(R R lt)]! RR7       ! R R4      4       t*R R lt+R R lt,R R lt-RR/R R llt.R R  lt/R! R" lt0]1R#8X  d   ] Pd                  ! ]0! 4       4       R# R# )$    N)	dataclass)Anyc                    V ^8  d   QhRR/#    returnN )formats   "[E:\live-kit-agent\livekit_voicebot\backend\agent_runtime\src\mcube_integration\ai_worker.py__annotate__r      s     $ $ $    c                     Rp V \         P                  9   d   R#  ! R R4      p\        P                  ! V 4      pVP                  P                  RR.RV/4       V\         P                  V &   R# )z
Work around Windows WDAC/App Control blocking `lk_blingfire` native extension.
`livekit.agents` imports `livekit.agents.tokenize.blingfire` unconditionally; we stub it.
z!livekit.agents.tokenize.blingfireNc                   v   a  ] tR t^t o R^R^
RR/V 3R lR lltRR/V 3R	 lR
 lltRR/V 3R lR lltRtV tR# ):_install_livekit_blingfire_stub.<locals>.SentenceTokenizermin_sentence_lenstream_context_lenretain_formatFc                0   < V ^8  d   QhRS[ RS[ RS[RR/# )r   r   r   r   r   N)intbool)r
   __classdict__s   "r   r   G_install_livekit_blingfire_stub.<locals>.SentenceTokenizer.__annotate__   s5     	; 	; "	; !$		;
  	; 	;r   c               &    \        V4      V n        R # )N)r   _min_sentence_len)selfr   r   r   s   &$$$r   __init__C_install_livekit_blingfire_stub.<locals>.SentenceTokenizer.__init__   s     &))9%:D"r   languageNc                J   < V ^8  d   QhRS[ RS[ R,          RS[S[ ,          /# )r   textr   Nr   )strlist)r
   r   s   "r   r   r   "   s/     	J 	J 	J3: 	Jc 	Jr   c                  \         P                  ! R T;'       g    R4       Uu. uF*  q3P                  4       '       g   K  VP                  4       NK,  	  ppV Uu. uF!  p\        V4      V P                  8  g   K  VNK#  	  up# u upi u upi )z(?<=[.!?])\s+ )resplitstriplenr   )r   r    r   ppartss   &&$  r   tokenizeC_install_livekit_blingfire_stub.<locals>.SentenceTokenizer.tokenize"   sl    (*1A4::2(N\(N1RYRYR[YQWWY(NE\$Iu!A$2H2H(HAAuII ]Is   B BB	;B	c                .   < V ^8  d   QhRS[ R,          /# )r   r   Nr!   )r
   r   s   "r   r   r   &   s     	\ 	\cDj 	\r   c                   \        R 4      h)z2Streaming tokenizer not supported in fallback stub)NotImplementedError)r   r   s   &$r   streamA_install_livekit_blingfire_stub.<locals>.SentenceTokenizer.stream&   s    %&Z[[r   )r   )	__name__
__module____qualname____firstlineno__r   r+   r1   __static_attributes____classdictcell__r   s   @r   SentenceTokenizerr      s[     	; %'	; ')		;
 #(	; 	;	J 	J 	J	\4 	\ 	\ 	\r   r:   __all__)sysmodulestypes
ModuleType__dict__update)module_namer:   stubs      r   _install_livekit_blingfire_stubrD      se     6Kckk!\ \" K(DMM)&9%:<OQbcd#CKKr   )	inferencefunction_tool)ChatContext)cartesia
elevenlabs)load_agent_runtime_dotenv)'get_runtime_overrides_from_agents_table)get_default_mcube_call_config)AI_UTTERANCES_QUEUERABBITMQ_URLcontrol_queue_namedeclare_durable_queueconnectget_channelpublish_jsontts_queue_namezmcube.ai_workerc                F    V ^8  d   QhR\         \        \        3,          /# )r   r   )dictr!   )r
   s   "r   r   r   I   s      tCH~ r   c                     \        4       p RV R,          RV R,          RV R,          RV R,          RV P                  R4      ;'       g    RRV R,          RV R,          R	V P                  R	4      ;'       g    R
/# )zSFallback only when DB + queue payload do not supply values (see process_utterance).system_prompt	llm_modelllm_provider	tts_modeltts_providerrI   tts_voice_idtts_encodingtts_chunk_ms200)rL   get)ds    r   _env_fallback_runtimerc   I   sz    %'A?+Q{^.)Q{^n-==.).)n-66	 	r   c                t    V ^8  d   QhR\         \        \        3,          R\         \        \        3,          /# )r   payloadr   )rV   r!   r   )r
   s   "r   r   r   X   s*     4 4c3h 4DcN 4r   c           
       "   \        4       pV P                  R4      pVe   \        P                  ! \        TV P                  R4      V P                  R4      V P                  R4      ;'       g    V P                  R4      V P                  R4      ;'       g    V P                  R4      R	7      G Rj  xL
 pVP                  V4       Rp\        V4      pV F  pW`9  d   K  V P                  V4      pVf   K"  \        V\        4      '       d    VR8w  d   VP                  4       '       g   KW  VR
8X  d-   \        V\        4      '       d   VP                  RR4      WV&   K  \        V\        4      '       d   \        V4      P                  4       MTWV&   K  	  VP                  RR4       VP                  RVP                  RR4      4       VP                  RVP                  RR4      4       VP                  RVP                  RR4      4       VP                  RVP                  RR4      4       VP                  R
VP                  R
R4      4       VP                  RVP                  RR4      4       V#  EL5i)z
Merge precedence (later wins):
1) `.env` defaults (MCUBE_* via mcube_defaults)
2) `business_id_agents` row (+ JSON config) when `business_id` is present
3) Explicit fields on the RabbitMQ payload (Redis call config / ws_bridge)
business_idNagent_iduser_idagent_emailemail
agent_namename)rh   ri   rk   rm   rX   rY   rZ   r[   r\   r]   r^   r_   z\n
rI   r$   r`   )rX   rY   rZ   r[   r\   r]   r^   r_   )rc   ra   asyncio	to_threadrK   rA   rV   
isinstancer!   r'   replace
setdefault)re   basebiddb_ovoverride_keysoutkvs   &       r   _resolve_runtime_from_payloadr{   X   s     !"D
++m
$C
''3[[,KK	*++m,DDG0D\*AAgkk&.A
 
 	E	M t*CKKN9a!~"5aggiiJq#$6$6YYud+CF'1!S'9'9SV\\^qCF  NN><0NN;b 9:NN;b 9:NN>488NB#?@NN>488NB#?@NN?DHH_b$ABNN>488NE#BCJS
s&   A-I<0(I<I<3I94A8I<-EI<T)frozenc                   ,   a  ] tR t^t o V 3R ltRtV tR# )PublishTtsChunkc                J   < V ^8  d   Qh/ S[ ;R&   S[;R&   S[;R&   S[;R&   # )r   call_idsequence_id	chunk_seqpcm16_8k_bytes)r!   r   bytes)r
   r   s   "r   r   PublishTtsChunk.__annotate__   s5     L    N	 
  r   r	   N)r3   r4   r5   r6   __annotate_func__r7   r8   r9   s   @r   r~   r~      s      r   r~   c                0    V ^8  d   QhR\         R\        /# )r   pcm16_bytesr   )r   r!   )r
   s   "r   r   r      s     9 9u 9 9r   c                 L    \         P                  ! V 4      P                  R 4      # )ascii)base64	b64encodedecode)r   s   &r   _pcm16_to_b64r      s    K(//88r   c                v    V ^8  d   QhR\         R\        R\        R\        R\        \         \        3,          /# )r   r   	from_rateto_ratestater   )r   r   objecttuple)r
   s   "r   r   r      s=          c  C  PV  [`afhnan[o  r   c               @    ^ RI pVP                  V ^^VVV4      w  rVWV3# )zN
audioop.ratecv works on raw int16 PCM.
Returns (converted_bytes, new_state).
N)audioopratecv)r   r   r   r   r   	converted	new_states   &$$$   r   _resample_pcm16r      s5    
 ">>		I r   c                H    V ^8  d   QhR\         R\         R\         R\         /# )r   rX   rY   	user_textr   r.   )r
   s   "r   r   r      s(     	! 	!# 	!# 	!# 	!# 	!r   c                 t  "   \         P                  ! VR 7      p\        P                  ! 4       pVP	                  RV R7       VP	                  RVR7       VP                  VR7      p. pVP                  4         Rj  xL
  pVP                  V4       K   LDRP                  T4      P                  4       # 5i)modelsystemrolecontentuser)chat_ctxNr$   )
rE   LLMrG   emptyadd_messagechatto_str_iterableappendjoinr'   )rX   rY   r   llmr   r1   r    tokens   &&&     r   _run_llmr      s     
--i
(C  "Hh>fi8XXxX(FD--/  eE/774=  s*   A7B89B=B>BB8B B8chunk_msc                    V ^8  d   QhR\         R\         R\         R\         R\         R\        R,          R\        \        ,          /# )	r   r    r\   r[   r]   r^   r   Nr   )r!   r   r"   r   )r
   s   "r   r   r      sa     D" D"
D" D" 	D"
 D" D" DjD" 
%[D"r   c          
     
  "   ^ RI p^ RIp^ RIp^ RIp	Rp
 VP	                  4       p
VR8X  dJ   \
        P                  ! R4      ;'       g    Rp\        P                  ! T;'       g    RVRVRRV
R	7      pEM\
        P                  ! R
4      ;'       g!    \
        P                  ! R4      ;'       g    RpV'       g   \        R4      hRV R2pRVRRRR/pRV RVRV/pV
P                  WVR7      ;_uu_4       GRj  xL
 pVP                  4       G Rj  xL
 pVP                  ^8w  d7   VR,          P                  RRR7      p\        RVP                   RV: 24      hRRR4      GRj  xL
  RpV	P                  P                  P!                  RR VR!7      p\#        4       pV	P%                  VP'                  X4      4      ;_uu_ 4       p\)        R" VP*                   4       R4      pVf   \        R#4      hVP                  V4       FX  pVP-                  V4      ;'       g    .  F6  pVP.                  ^ ,          p VP1                  VP3                  4       4       K8  	  KZ  	  RRR4       Ve   TM\9        \
        P                  ! R$R%4      4      p\9        VR&,          V,          4      ^,          p. p\;        V4      p\=        ^ \?        V4      V4       FP  p VV V V,            p!\?        V!4      V8  d!   V!R'V\?        V!4      ,
          ,          ,           p!VPA                  V!4       KR  	  TV
e   V
PC                  4       G Rj  xL
  # # RpVe   TM\9        \
        P                  ! R$R%4      4      p\9        VR&,          V,          4      p"V"^,          p\#        4       p#. pRp$VPE                  V 4        Rj  xL
  p%V%PF                  pVPH                  PK                  4       p&VPL                  p'VPO                  V&^^V'VV$4      w  p(p$V#P1                  V(4       \?        V#4      V8  g   Kx  \;        V#RV 4      p!V#RV1 VPA                  V!4       K8   ELU EL@ EL  + GRj  xL 
 '       g   i     EL; i  \4         d     TP1                  \7        T4      4        EKx  i ; i  + '       g   i     ELG; i ELu ELEDT#'       dV   \?        T#4      T8  d)   T#P1                  R'T\?        T#4      ,
          ,          4       TPA                  \;        T#RT 4      4       TT
e   T
PC                  4       G Rj  xL 
  # #   T
e   T
PC                  4       G Rj  xL 
  i i ; i5i)(zK
Synthesizes TTS to PCM16 at 8k, then returns a list of fixed-size chunks.
NrH   CARTESIA_API_KEYr$   zsonic-2en	pcm_s16lei]  )r   voicer   api_keyencodingsample_ratehttp_sessionELEVENLABS_API_KEYELEVEN_API_KEYzELEVENLABS_API_KEY not setz,https://api.elevenlabs.io/v1/text-to-speech/z/streamz
xi-api-keyzcontent-typezapplication/jsonacceptz
audio/mpegr    model_idoutput_format)headersjson:Ni,  Nutf-8rr   )errorszelevenlabs_tts_failed status=z body_head=i@  s16mono)r
   layoutratec              3   J   "   T F  qP                   R 8X  g   K  Vx  K  	  R# 5i)audioN)type).0ss   & r   	<genexpr>+_synthesize_tts_pcm16_8k.<locals>.<genexpr>   s     $W0A1VVwEVQQ0As   #
#z)elevenlabs_decode_failed: no audio streamMCUBE_TTS_CHUNK_MSr`   g     @@    )(r   aiohttpioavClientSessionosgetenvrH   TTSRuntimeErrorpostreadstatusr   r   	resamplerAudioResampler	bytearrayopenBytesIOnextstreamsresampleplanesextendto_bytes	Exception
memoryviewr   r   ranger(   r   close
synthesizeframedatatobytesr   r   ))r    r\   r[   r]   r^   r   r   r   r   r   sessioncartesia_keyttselevenlabs_keyurlr   bodyresp	mp3_bytesheadtarget_rater   pcm16_8k	containeraudio_streamr   rx   planechunk_ms_effchunk_byteschunksbufichunkchunk_samplesbufferresample_statesynth_audio
pcm16_fromr   r   s)   &$$$$$                                   r   _synthesize_tts_pcm16_8kr     s      -1Gq"''):%99%78>>BL,,,,9"$$!$C  YY';<aa		JZ@[aa_aN!"#?@@@gVCn 2,G I	D ||Ct|DDD"&))+-	;;#%$T?11')1LD&)Ft{{mS^_c^f'ghh	 ED K**99v\g9hI {HI.//9#$W	0A0A$WY]^'&'RSS&--l;E(11%8>>B> #

1?$OOENN,<=	  ? <	 0 (0';8RYYOcejEkAlL|f4CDqHK"$F/C1c#h4AK0u:+!Wc%j0H%IJEe$	 5
 V --/!! Q #+#7xSK_afAg=h\F2kAB#a'  !$!5 	% 	%+%%E++-J))I(/)%I~ MM)$f+,f\k23<K<(e$G E- EDDD*  ) ?$OOJu,=>>? 0//H ";	%!5&  6{[(gs6{)BCDMM%| 456--/!! 7--/!! sD  U 3T= 
T= &,T= T= 1
T= <A T= <Q=T=  QQAQ T= +Q,A T= AR$%R$?Q7R$&CT= ,U R8U 
A)T= 3R>7R;8R>;A+T= +'T= QT= Q4	 Q#!
Q4	,Q4	.	T= 7%R!R$ R!!R$$R5	/	T= 8U ;R>>	T= AT= U 5T86U =UUUU c                    V ^8  d   QhRR/# r   r	   )r
   s   "r   r   r   @  s     b
 b
 b
r   c                   "   V P                  R R7      ;_uu_4       GRj  xL
  \        P                  ! V P                  P	                  R4      4      p\        VR,          4      p\        VP                  R^ 4      4      pVP                  R4      ;'       g    RpVP                  R4      ;'       g    RP                  4       p\        V4      G Rj  xL
 pVR	,          pVR
,          p\        VP                  R4      ;'       g    R4      p	VR,          p
\        VP                  R4      ;'       g    R4      pVR,          pVR,          p \        ^\        R\        \        \        VP                  R4      ;'       g    R4      4      4      4      4      p\        P                  ! 4       p\        P!                  RTTT;'       g    T;'       g    RR,          VVV
V4        V'       d   Tp\#        VVV
VVVR7      G Rj  xL
 pEMRRRRRRRRRR/ R . R!R //pRRRR"RR#RRRRR$RR%RR&/R'RR%RR(/R)RR%RR*//R!R //pR+ R, lpR- R. lp\%        VVR/7      \%        VVR/7      .pR0pV V 2pV	'       d"   \&        P(                  ! Y;'       g    RR17      M\&        P(                  ! VR27      p\*        P,                  ! 4       pVP/                  R3VR47       VP/                  R5VR47       VP1                  VVR R67      p. p. pV  Rj  xL
  pVP2                  '       g   K  VP2                  P4                  '       d&   VP7                  VP2                  P4                  4       VP2                  P8                  '       g   K}  VP;                  VP2                  P8                  4       K  \M        V4      p$\>        p V f   \A        R74      h\O        V4       F/  w  p%p&\G        V V$RVRVR?V%R@\Q        V&4      RRA/R:7      G Rj  xL
  K1  	  \G        V V$RVRVRRBRC\        ^ \S        V4      ^,
          4      RD\        \        P                  ! 4       V,
          RE,          4      /R:7      G Rj  xL
  \        P!                  RFVV\S        V4      \        \        P                  ! 4       V,
          RE,          4      4       RRR4      GRj  xL
  R#  EL EL  \         d    ^p ELCi ; i EL ELEDT'       Ed3   \=        T4      p\>        p T f   \A        R74      hT EF  p! \        P                  ! T!PB                  ;'       g    R84      p"M  \         d    / p" Mi ; iT!PD                  R8X  d2   \G        T TRR9RTRT/R:7      G Rj  xL 
   RRR4      GRj  xL 
  R# T!PD                  R"8X  g   K  T"P                  R$4      ;'       g+    T"P                  R'4      ;'       g    T"P                  R)4      p#\G        T TRR;RTRTR<T#/R:7      G Rj  xL 
   RRR4      GRj  xL 
  R# 	  RPI                  T4      P                  4       pT'       g   R=p\#        TTT
TTTR7      G Rj  xL 
 pEL  \         d,    \        PK                  R>Y#4        RRR4      GRj  xL 
  R# i ; i EL ELA EL  + GRj  xL 
 '       g   i     R# ; i5i)GF)requeueNr   r   r   
transcriptr$   bot_say_textrX   rY   rZ   r[   r\   rI   r]   r^   i  r_   r`   zjutterance_received call_id=%s seq=%s stt_text=%r llm_model=%s tts_provider=%s tts_model=%s tts_voice_id=%s:Nx   N)r\   r[   r]   r^   r   r   functionrm   end_calldescriptionz-Terminate the current phone call immediately.
parametersr   
propertiesrequiredadditionalPropertiestransfer_to_numberz*Transfer the call to another phone number.phone_numberstringz0Target phone number in E.164 format (preferred).transfer_numberzAlias for phone_number.sip_uriz'Optional SIP URI like sip:+918...@host.c                R    V ^8  d   QhR\         \        \        3,          R\        /# r   raw_argumentsr   rV   r!   r   )r
   s   "r   r   'process_utterance.<locals>.__annotate__  s#        S&[8I  c  r   c                    "   R # 5iokr	   r  s   &r   _end_call_tool)process_utterance.<locals>._end_call_tool          c                R    V ^8  d   QhR\         \        \        3,          R\        /# r  r  )r
   s   "r   r   r    s$        $sF{BS  X[  r   c                    "   R # 5ir!  r	   r#  s   &r   _transfer_to_number_tool3process_utterance.<locals>._transfer_to_number_tool  r&  r'  )
raw_schemaa	  

Tool-use rules for MCube phone calls:
- Call `end_call` to terminate the current call.
- Call `transfer_to_number` to transfer; provide phone_number or sip_uri.
- When calling a tool, do not include additional spoken content; the caller side will act on the tool.)r   providerr   r   r   r   )r   toolsparallel_tool_callszpublish channel not initializedz{}mcube_terminate)channel
queue_namere   mcube_transfertransfer_tozOkay.z-utterance_processing_failed call_id=%s seq=%sr   audio_pcm_b64tts_audio_chunktts_donefinal_chunk_seqtts_generation_msi  z>tts_published call_id=%s seq=%s chunks=%s tts_generation_ms=%s)*processr   loadsr   r   r!   r   ra   r'   r{   maxminfloatr   timeloginfor  rF   rE   r   rG   r   r   r   deltar   r   
tool_callsr   rO   _PUBLISH_CHANNELr   	argumentsrm   rS   r   	exceptionrT   	enumerater   r(   )'messagere   r   r   r   r  rtrX   rY   rZ   r[   r\   r]   r^   r_   start_tresponse_text	chunks_8kend_call_schematransfer_to_number_schemar$  r*  r.  tool_instructionssystem_prompt_with_toolsr   r   r1   rC  
text_partsr  control_queuer1  tc	tool_argsr4  connection_queuer   r   s'   &                                      r   process_utterancerV  @  s    u---**W\\009:gi()'++mQ78KK-33	N399r@@B099?+{O	266.177R8{O	266.1AA\B.).)	q#c3uS9O9X9XSX5Y/Z+["\]L ))+x,,Y,,"d3		
W	 ,":!!-'!-!-)# 	 JJ!#R $b"B.	#	
# J0!#O $* & -/a- . & -/H0 & & -/X(' /!#	-)0   "._M!":G`a} " /<_=N<O+P( $ MM	<P<PDQ"Y7 
 ',,.$$(<T$U$$&)$D%(- "  )+
(*
#) F F%{{{ ;;...&--ekk.A.AB ;;111&--ekk.D.DE| *'2 #?@AA)29)=%I~+w!;#]>%B-
 
 
 *> '7{
!3q#i.1*<#=#S$))+*?4)G%H

 
	
 
	
 	L	Nw&$./	
w .-- :  	L	$fF6 :$6w$?M.G*+LMM(+(,

2<<3G3G4(HI( +(*I+ 77j0".(/+8$*,=$-w$1;)"#   #k .--n 77&:: )n = !< !<#,==1B#C!< !<#,==#; (
 #/(/+8$*,<$-w$1;$1;	)"	# 	 	 #O .--J )H !#
 3 9 9 ;$$+M":!!-'!-!-)#  	  	MMI7`o .--j	

	
a .---s  [S[BZ*5Z*S	2Z*,Z*5Z*A
S/Z*		Z*Z*&Y(.Y(S Y(	Z*BY(A4Y(S&S#
S&
Y( Y(<>Y(?'Y(&AZ*;Z!
<A'Z*#Z$$AZ*4[?Z' [	Z*SZ*SZ* Y(#S&&
Y(1&Y("U;UY(U	Y(U	+Y(>V
?Y([V[Y(+Y(Y(+Y(X

Y([X[!(Y(
Y( Y#!Y(&Z*(!Z	Z*
[Z[ZZ*$Z*'[*[	0Z31
[	<[	>	[c                    V ^8  d   QhRR/# r   r	   )r
   s   "r   r   r   %  s      D r   c                    "   \         P                  ! \         P                  R 7       \        4       G Rj  xL
 p \	        V 4      G Rj  xL
 pVs\        V\        4      G Rj  xL
  \        P                  R\        \        4       VP                  \        RR7      G Rj  xL
 pVP                  \        RR7      G Rj  xL
  \        P                  ! 4       G Rj  xL
  R#  L L L LH L+ L5i))levelNzai_worker: consuming %s on %sT)durableF)no_ack)loggingbasicConfigINFOrQ   rR   rD  rP   rM   r@  rA  rN   declare_queueconsumerV  ro   Future)
connectionr1  queues      r   mainrd  %  s     gll+yJ
++G
)<
===HH,.A<P''(;T'JJE
--)%-
888
..
 !+ > K8si   3C/C#C/C%	C/"C'#=C/ C)!C/?C+ C/C-C/%C/'C/)C/+C/-C/__main__)3ro   r   r   r\  r   r<   r?  dataclassesr   typingr   r>   r%   rD   livekit.agentsrE   rF   livekit.agents.llm.chat_contextrG   livekit.pluginsrH   rI   env_loadrJ   business_id_agentsrK   mcube_defaultsrL   mqrM   rN   rO   rP   rQ   rR   rS   rT   	getLoggerr@  rD  rc   r{   r~   r   r   r   r  rV  rd  r3   runr	   r   r   <module>rq     s        	 
  !   	$@   ! 3 7 0 / G 9	 	 	 )*   4n $  9 $	!D"  D"Nb
J$ zKK r   