
    /jvY                       S SK Jr  S SKrS SKrS SKrS SKrS SKJr  S SKJ	r	  S SK
JrJrJrJrJrJrJrJr  S SKrS SKJrJrJr  S SKJrJr  S SKJrJr  S S	KJr  S S
KJ r   SSK!J"r"  SSK#J$r$  SSK%J&r&  SSK'J(r(J)r)  SSK*J+r+J,r,J-r-  \(       a  SSK.J/r/  SSK'J0r0J1r1  SSK2J3r3  SSK*J4r4  Sr5Sr6S8S jr7\	 " S S5      5       r8S9S jr9SS.S:S jjr:\	 " S S 5      5       r;S!S".S;S# jjr<SS$.     S<S% jjr=    S=S& jr>\" S'SS(9r?S>S) jr@    S?S* jrAS@S+ jrBSAS, jrCSS-.       SBS. jjrDSCS/ jrESS0.SDS1 jjrFSES2 jrGSFS3 jrH\	 " S4 S55      5       rI        SGS6 jrJSS-.       SHS7 jjrKg)I    )annotationsN)Callable)	dataclass)TYPE_CHECKING	AnnotatedAnyUnioncastget_args
get_originget_type_hints)	BaseModelTypeAdaptercreate_model)Field	FieldInfo)PydanticUndefined	from_json)TypeVar)rtc   )logger)images   )_strict)ChatContextImageContent)FunctionToolRawFunctionTool	ToolError
RunContextFunctionCallFunctionCallOutput)FunctionToolCall)ToolContextz<think>z</think>c                p   [        U 5      [        U5      p2[        US-   5       Vs/ s H  nS/US-   -  PM     nn[        SUS-   5       Ha  n[        SUS-   5       HK  nXS-
     XS-
     :X  a  XVS-
     US-
     S-   XV   U'   M*  [        XVS-
     U   XV   US-
     5      XV   U'   MM     Mc     / nX#pvUS:  af  US:  a`  XS-
     XS-
     :X  a!  UR                  XS-
     5        US-  nUS-  nO!XVS-
     U   XV   US-
     :  a  US-  nOUS-  nUS:  a  US:  a  M`  [	        [        U5      5      $ s  snf )z{
Standard dynamic-programming LCS to get the common subsequence
of IDs (in order) that appear in both old_ids and new_ids.
r   r   )lenrangemaxappendlistreversed)	old_idsnew_idsnm_dpijlcs_idss	            I/app/agent/.venv/lib/python3.13/site-packages/livekit/agents/llm/utils.py_compute_lcsr9   ,   sa   
 w<Wq!&q1u	.A1#Q-B	. 1a!e_q!a%A1u~Q/!e9QU+a/ara%y|RU1q5\:a	 !  Gq
a%AEq5>WU^+NN7q5>*FAFAAYq\BE!a%L(FAFA a%AE !""/ 
/s   D3c                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg)	DiffOpsL   	list[str]	to_removezlist[tuple[str | None, str]]	to_create	to_update N__name__
__module____qualname____firstlineno____annotations____static_attributes__rA       r8   r;   r;   L   s      rI   r;   c                    U R                    Vs/ s H  o"R                  PM     nnUR                    Vs/ s H  o"R                  PM     nn[        [        X45      5      nU R                    Vs0 s H  ofR                  U_M     nnU R                    Vs/ s H   oR                  U;  d  M  UR                  PM"     n	n/ n
/ nSnUR                    H  nUR                  U;  a  U
R	                  XR                  45        OdX}R                     nUR
                  S:X  aF  UR
                  S:X  a6  UR                  UR                  :w  a  UR	                  XR                  45        UR                  nM     [        XUS9$ s  snf s  snf s  snf s  snf )zXComputes the minimal list of create/remove operations to transform old_ctx into new_ctx.Nmessage)r>   r?   r@   )itemsidsetr9   r,   typetext_contentr;   )old_ctxnew_ctxr2   r/   r0   r7   itemold_ctx_by_idmsgr>   r?   r@   prev_idnew_msgold_msgs                  r8   compute_chat_ctx_diffrY   W   sB    %]]+]tt]G+$]]+]tt]G+,w01G/6}}=}tWWd]}M=#*==J=CFF'4I=IJ.0I.0IG==::W$gzz23 $JJ/G||y(W\\Y-F''7+?+??$$gzz%:; ** ! YyQQ1 ,+ >Js   E<F-FF*FFallow_subclassesc                   SSK Jn  [        U 5      nU(       d  XL =(       d    X2L $ Ub   [        X25      $  [        X5      $ ! [         a     gf = f! [         a     gf = f)Nr   r!   F)voice.eventsr"   r   
issubclass	TypeError)tyr[   r"   origins       r8   is_context_typerb   v   so    )^F76#77	f11"))	  		
  s"   
A 
A 
AA
AAc                  F    \ rS rSr% S\S'   S\S'   SrS\S'   SrS\S	'   S
rg)SerializedImage   strinference_detail
str | None	mime_typeNzbytes | None
data_bytesexternal_urlrA   )rC   rD   rE   rF   rG   rj   rk   rH   rA   rI   r8   rd   rd      s"    #J##L*#rI   rd   T)	use_cachec                  SnU(       a,  X R                   ;   a  [        [        U R                   U   5      $ [        U R                  [
        5      (       Ga)  U R                  R                  S5      (       a  U R                  R                  SS5      u  p4[        R                  " U5      nUR                  S5      S   R                  S5      S   nU R                  (       aD  U R                  U:w  a4  [        R                  " SU R                   S	U S
35        U R                  nOUn1 SknXx;  a  [        SU S35      e[        UUU R                  S9n	O[        U R                  U R                  U R                  S9n	O[        U R                  [        R                   5      (       a  ["        R$                  " 5       n
U R&                  (       a@  U R(                  (       a/  ["        R*                  " U R&                  U R(                  SS9U
l        ["        R.                  " U R                  U
5      n[        USU R                  S9n	O[        S5      eU(       a  XR                   U'   U	$ )Nserialized_imagezdata:,r   ;r   :zProvided mime_type 'z9' does not match data URL mime type
                    'z'. Using provided mime_type.>   	image/gif	image/png
image/jpeg
image/webpzUnsupported mime_type z!. Must be jpeg, png, webp, or gif)rj   ri   rg   )ri   rg   rk   scale_aspect_fit)widthheightstrategyrt   zUnsupported image type)_cacher
   rd   
isinstanceimagerf   
startswithsplitbase64	b64decoderi   r   warning
ValueErrorrg   r   
VideoFramer   EncodeOptionsinference_widthinference_heightResizeOptionsresize_optionsencode)r|   rl   	cache_keyheaderb64_dataencoded_dataheader_mimeri   supported_typesrn   optss              r8   serialize_imager      s    "IY,,.OU\\)%<== %++s##;;!!'**${{00a8F!++H5L ,,s+A.44S9!<K5??k#A,U__,= >!]">B "OO	'	TO/ ,YK7XY   /'#!&!7!7   ///!&!7!7"[[  
EKK	0	0##%  U%;%;"("6"6++--+#D
 }}U[[$7*#""33
 122"2YrI   )internally_taggedc                   [        U 5      nU R                  nUR                  5       nU(       a$  UR                  UR                  =(       d    SUSS.$ SUR                  UR                  =(       d    SUS.S.$ )zxnon-strict mode tool description
see https://serde.rs/enum-representations.html for the internally tagged representation function)namedescription
parametersrO   )r   r   r   rO   r   )$function_arguments_to_pydantic_modelinfomodel_json_schemar   r   )function_toolr   modelr   schemas        r8   build_legacy_openai_schemar      s{    
 1?ED$$&FII++1r 	
 	
 		#//52$
 	
rI   c                    [        U 5      nU R                  n[        R                  " U5      nSUR                  SUR
                  =(       d    SUS.S.$ )zstrict mode tool descriptionr   Tr   )r   strictr   r   r   )r   r   r   to_strict_json_schemar   r   )r   r   r   r   s       r8   build_strict_openai_schemar      sX     1?ED**51F II++1r 	
 rI   ResponseFormatT)defaultc                v    [        U [        5      =(       a#    [        U [        5      =(       a    [	        U S5      $ )NrG   )r{   rO   r^   dicthasattr)clss    r8   is_typed_dictr      s(    c4 ^ZT%:^wsL]?^^rI   c                h   [        U [        5      (       a,  U R                  SS5      S;  a  [        S5      e[        S5      e[	        U 5      (       aE  [        U R                  40 U R                  R                  5        VVs0 s H	  u  pXS4_M     snnD6n S n[        R                  " U 5      (       a&  [        U [        5      (       a  U R                  nU nXC4$ [        R                  " U 5      (       a+  [        U S5      (       a  U R                  n[        U 5      nXC4$ [        SU  35      es  snnf )NrO   r   )textjson_schemajson_objectz Unsupported response_format type.__pydantic_config__z#Unsupported response_format type - )r{   r   getr_   r   r   rC   rG   rL   inspectisclassr^   r   r   r   )response_formatkvjson_schema_typer   s        r8   to_response_format_paramr     s4    /4((vr*2XX>?? :;; _%%&$$
'6'F'F'L'L'NO'Ntqqc({'NO
 CG''J	,R,R''* !! 
	)	)g./ / ''&7 !! =o=NOPP Ps   D.c                Z    [        U 5      u  p[        R                  " U5      nSUUSS.S.$ )Nr   T)r   r   r   )rO   r   )r   r   r   )r   r   r   r   s       r8   to_openai_response_formatr   (  s;    5oFD**+;<F
 rI   c                N   SSK Jn  U R                  R                  S5      nSR	                  S U 5       5      nUS-   nU" U 5      nUR
                   Vs0 s H  ofR                  UR                  _M     nn[        R                  " U 5      n[        U SS9n	0 n
UR                  R                  5        GH^  u  pX   n[        USS	9(       a  M  UR                  UR                  La  UR                  OS
nSn0 n[!        U5      ["        L ay  [%        U5      nUS   n['        S USS  5       S5      nU(       a%  [)        US5      (       a  UR+                  5       S   nO'U(       a   UR                  US'   UR                  US'   UnUS
La"  UR-                  S[.        5      [.        L a  UUS'   UR-                  S5      c  UR-                  US5      US'   U(       d  [1        S0 UD6nO'UR                  5        H  u  nn[3        UUU5        M     X4X'   GMa     [5        U40 U
D6$ s  snf )zNCreate a Pydantic model from a function's signature. (excluding context types)r   )parse_from_objectr3   r   c              3  @   #    U  H  oR                  5       v   M     g 7fN)
capitalize.0xs     r8   	<genexpr>7function_arguments_to_pydantic_model.<locals>.<genexpr><  s     9y!||~~ys   ArgsTinclude_extrasrZ   .Nc              3  T   #    U  H  n[        U[        5      (       d  M  Uv   M      g 7fr   )r{   r   r   s     r8   r   r   W  s     K.q*Q	2J.s   (	(r   asdict
attributesr   r   rA   )docstring_parserr   rC   r~   joinparamsarg_namer   r   	signaturer   r   rL   rb   r   emptyr   r   r   nextr   r   r   r   r   setattrr   )funcr   	fnc_namesfnc_name
model_name	docstringp
param_docsr   
type_hintsfields
param_nameparam	type_hintdefault_value
field_infofield_attrsannotated_argsannotated_fieldr   r   s                        r8   r   r   6  s    3##C(Iww9y99HF"J!$'I5>5E5EF5E**amm+5EJF!!$'IT:J  F&11779
*	9t<).ekk)Is'+
&( i I-%i0N&q)I"KN12.KTO 7?H#E#E-446|D )8)@)@I&-<-H-HM*,
 $	+<=ARR%2K	"??=)1)3
D)IK&--J#))+1
Aq) , (4Q :T 
-f--e Gs    H")call_ctxc                p   [         R                  " U 5      n[        U SS9n[        U[        5      (       a  [        U5      n[        U[        5      (       a#   [        U5      n[        U[        5      (       a  M#  Uc  0 nO?[        U[        5      (       d'  [        S[        U5      R                   SUSS  35      eOUn[        U [        5      (       a  [        U 5      nUR                  R                  5        Hm  u  pxXG   n	Xu;   d  M  XW   b  M  [        U	5      (       a  M)  UR                   [         R"                  R$                  La  UR                   XW'   M`  [        SU S	35      e   UR'                  U5      n
[)        U
5      nO1[        U [*        5      (       a  S
U0nO[        S[        U 5       35      e0 nUR                  R                  5        H  u  p}XG   n	[-        U	SS9(       a  Uc  M  [/        U	5      =(       d    U	n[        X.5      (       a  X,U'   MG  [0        R2                  " SU SUR                   S[        U5      R                   35        M     UR4                  " S0 0 UEUED6nUR7                  5         UR8                  UR:                  4$ ! [         a    [        SUSS  35      Sef = f)zp
Create the positional and keyword arguments to call a function tool from
the raw function output from the LLM.
Tr   z1function arguments decoded to a non-JSON string: N   z+expected dict from function arguments, got z: z&Received None for required parameter 'z; ;this argument cannot be None and no default is available.raw_argumentsz Unsupported function tool type: rZ   z%context type mismatch for parameter 'z': expected z, got rA   )r   r   r   r{   rf   r   	Exceptionr   r   rO   rC   r   r   r   rL   _is_optional_typer   	Parameterr   model_validate_shallow_model_dumpr   rb   r   r   errorbindapply_defaultsargskwargs)fncjson_argumentsr   r   r   	args_dict
model_typer   r   r   r   
raw_fieldscontext_dictr3   expected_typebounds                   r8   prepare_function_argumentsr   u  s    !!#&ID9J.#&&n-	 C((%i0	 C(( IIt,,I//0>$33G2HJ  - #	#|$$9#>
 "+!5!5!;!;!=J".I&9+@+H(33}}G,=,=,C,CC05	-(DZL QX X  "> )))4(/
	C	)	) Y

 ;DI;GHH L"--335
*	y4@HDT"9-:h..'/$LL7
| D)2236$x.:Q:Q9RT 6 NN<;
;l;<E	::u||##A   G	RVSVGXYs   J J5c                    [        U 5      [        L a  [        U 5      S   n [        U 5      nU[        L nU=(       d    U[        R
                  L nU=(       a    [        S 5      [        U 5      ;   $ Nr   )r   r   r   r	   types	UnionTyperO   )hintra   is_unions      r8   r   r     s[    $9$~a FH46U__4H4T
htn44rI   )by_aliasc                   0 nU R                   R                  R                  5        H8  u  p4U(       a  UR                  (       a  UR                  OUn[	        X5      X%'   M:     U$ r   )	__class__model_fieldsrL   aliasgetattr)r   r  resultr   fieldkeys         r8   r   r     sL    F3399;%%++ekk4e* < MrI   c                B   U c  g UR                  5       (       aF  U R                  [        5      nUS:  a&  UR                  5         X[	        [        5      -   S  n U $ S n  U $ U R                  [
        5      nUS:  a$  UR                  5         X[	        [
        5      -   S  n U $ r   )is_setfindTHINK_TAG_ENDclearr)   THINK_TAG_STARTrN   )contentthinkingidxs      r8   strip_thinking_tokensr    s    ll=)!8NNC$6689G N G N ll?+!8LLNC$88:;GNrI   c                  ^ [         [        [        [        [        [        S 5      4m[        U T5      (       a  g[        U [        5      (       d?  [        U [        5      (       d*  [        U [        5      (       d  [        U [        5      (       a  [        S U  5       5      $ [        U [        5      (       a#  [        U4S jU R                  5        5       5      $ g)NTc              3  8   #    U  H  n[        U5      v   M     g 7fr   )_is_valid_function_output)r   rS   s     r8   r   ,_is_valid_function_output.<locals>.<genexpr>   s     Eut,T22us   c              3  d   >#    U  H%  u  p[        UT5      =(       a    [        U5      v   M'     g 7fr   )r{   r  )r   r	  valVALID_TYPESs      r8   r   r    s/      
) sK(K-Fs-KK)s   -0F)rf   intfloatboolcomplexrO   r{   r-   rN   	frozensettupleallr   rL   )valuer  s    @r8   r  r    s    UD'4:>K%%%5$eS!!eY''eU##EuEEE	E4	 	  
!KKM
 
 	
 rI   c                  >    \ rS rSr% S\S'   S\S'   S\S'   S\S	'   S
rg)FunctionCallResulti	  r$   fnc_callzFunctionCallOutput | Nonefnc_call_outr   
raw_outputBaseException | Noneraw_exceptionrA   NrB   rA   rI   r8   r$  r$  	  s    ++O''rI   r$  c                h   SSK Jn  SSKJnJn  [        U[        5      (       a  UnSn[        X%5      (       a1  [        U U" U R                  U R                  UR                  SS9UUS9$ [        X$5      (       a  [        U SUUS9$ Ub'  [        U U" U R                  U R                  SSS9UUS9$ [        U5      (       d<  [        R                  " S	U R                   S
3U R                  US.S9  [        U SUSS9$ [        U U" U R                  U R                  [        U=(       d    S5      SS9USS9$ )zNCreate a FunctionCallResult, handling ToolError, StopResponse, and validation.r   )r%   )StopResponser    NTr   call_idoutputis_errorr%  r&  r'  r)  zAn internal error occurredzAI function `z` returned an invalid output)r-  r.  extrar   F)chat_contextr%   tool_contextr+  r    r{   BaseExceptionr$  r   r-  rK   r  r   r   rf   )r%  r.  	exceptionr%   r+  r    s         r8   make_function_call_outputr7    s`    15&-((	)''!+]] (( ((	 #

 
	
 )**!#	
 	
 !+]] ((3	 #

 
	
 %V,,HMM?*FG&..&A	
 "	
 	
 '$$v|$	
 
 
rI   c          
       #    SSK JnJn  U" U R                  U R                  U R
                  =(       d    SU R                  =(       d    0 S9nUR                  R                  U R                  5      nUcn  [        R                  " SU R                   S35        [        UU" U R                  U R                  SU R                   3S	S
9S[        SU R                   35      S9$  [        UU R
                  =(       d    SUS9u  px U" U0 UD6n[(        R*                  " U5      (       a
  UI Sh  vN n[#        X[SS9$ ! [        R                  [        4 al  n	[        R                  " SU R                   SU	 3U R                  U R
                  S.S9  [!        SU R                   SU	 35      n
[#        USU
S9s Sn	A	$ Sn	A	f[$         aO  n	[        R&                  " SU R                   S3U R                  U R
                  S.S9  [#        USU	S9s Sn	A	$ Sn	A	ff = f N! [$         aO  n	[        R&                  " SU R                   S3U R                  U R
                  S.S9  [#        USU	S9s Sn	A	$ Sn	A	ff = f7f)z3Execute a function tool call and return the result.r   r#   z{})r-  r   	argumentsr2  Nzunknown AI function ``zUnknown function: Tr,  r0  )r   r   r   z#invalid arguments for AI function `z`: )r-  r9  r1  zError parsing arguments for `)r%  r.  r6  z/exception preparing arguments for AI function `z!exception executing AI function `)r3  r$   r%   r-  r   r9  r2  function_toolsr   r   r   r$  r   r   pydanticValidationErrorr    r7  r   r6  asyncioiscoroutine)	tool_calltool_ctxr   r$   r%   r%  r   fnc_args
fnc_kwargse
tool_errorr  s               r8   execute_function_callrF  Z  sd     ?!!^^%%-oo#	H ++//	?M.y~~.>a@A!+^^!))+INN+;<	 $'9)..9I%JK

 
	
V9$..6$ 
,V7J7v&&!\F((UYZZ- $$j1 	_ 	1)..1AQCH'//i>Q>QR	
 !>y~~>NcRSQTUV
((4S]^^ V=inn=MQO'//i>Q>QR	
 )(4STUUV "  V/	/?qA'//i>Q>QR	
 )(4STUUVs   C"I;% D= (H .H/H <I;=HA!F>8H9I;>HAHHI;HI;H 
I8)AI3-I8.I;3I88I;)r/   r=   r0   r=   returnr=   )rQ   r   rR   r   rG  r;   )r`   rO   r[   r  rG  r  )r|   r   rl   r  rG  rd   )r   r   r   r  rG  dict[str, Any])r   r   rG  rH  )r   z
type | AnyrG  r  )r   type | dict[str, Any]rG  z.tuple[str, type[BaseModel] | TypeAdapter[Any]])r   rI  rG  rH  )r   zCallable[..., Any]rG  ztype[BaseModel])r   zFunctionTool | RawFunctionToolr   zstr | dict[str, Any]r   RunContext[Any] | NonerG  z&tuple[tuple[Any, ...], dict[str, Any]])r   r   rG  r  )r   r   r  r  rG  rH  )r  rh   r  zasyncio.EventrG  rh   )r"  r   rG  r  )r%  r$   r.  r   r6  r(  rG  r$  )r@  r&   rA  r'   r   rJ  rG  r$  )L
__future__r   r>  r   r   r   collections.abcr   dataclassesr   typingr   r   r   r	   r
   r   r   r   r<  r   r   r   pydantic.fieldsr   r   pydantic_corer   r   typing_extensionsr   livekitr   logr   utilsr   r   r   r3  r   r   r4  r   r   r    r]   r"   r$   r%   llmr&   r'   r  r  r9   r;   rY   rb   rd   r   r   r   r   r   r   r   r   r   r   r   r  r  r$  r7  rF  rA   rI   r8   <module>rV     s    "     $ !	 	 	  9 9 , 6 %     3 B B)>%)#@   R> ;@ ( $ $ $ ?C 9z ?D

7;

6& +T:_"*"3"B<.F (,	U$	'U$ )U$ %	U$
 ,U$p	5 ?D (( ( ( (FF F $	F
 FZ (,	BVBVBV %	BV
 BVrI   