
    if+                     @   d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZ d dl	m
Z
mZ d dlmZmZ d dlZd dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZmZmZ d dlmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' d dl(m)Z) d dl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 ejb                  rd dl2m3Z3mZ  e)e4      Z5 G d dejl                        Z7 G d dejl                        Z8e
 G d d             Z9eeedddde9dee#e$f   dee:   deee;e   e;e   f      deee e!f      de<ee7e8f   ee;e'   f   fdZ=y)     N)AsyncExitStack)wraps)Callable)	dataclassfield)UnionOptional)#response_format_from_pydantic_model)RunException)MCPClientProtocol)	RunResult)OptionalNullable	BaseModelUNSET)ResponseFormatFunctionCallEntryToolsToolsTypedDictCompletionArgsCompletionArgsTypedDictFunctionResultEntryConversationInputsConversationInputsTypedDictFunctionToolMessageInputEntryInputEntries)	getLogger)create_function_resultRunFunctioncreate_tool_callRunTool
RunMCPToolRunCoroutine)Betar   c                       e Zd ZU eed<   y)AgentRequestKwargsagent_idN)__name__
__module____qualname__str__annotations__     Y/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/mistralai/extra/run/context.pyr&   r&   4   s    Mr.   r&   c                   h    e Zd ZU eed<   ee   ed<   eeee   ee	   f      ed<   eee
ef      ed<   y)ModelRequestKwargsmodelinstructionstoolscompletion_argsN)r(   r)   r*   r+   r,   r   r   listr   r   r   r   r-   r.   r/   r1   r1   8   sF    J"3''E$u+tN/C"CDEE%eN<S,S&TUUr.   r1   c            	       *   e Zd ZU dZ ed      Zeed<    ede      Z	ee
ef   ed<    ede      Zee   ed<    ed	      Zee
   ed
<    ed	      Zee
   ed<    ed	      Zee
   ed<    ed	      Zeee      ed<    ed	      Zeed<    ed	      Zeed<   d Zd Zd ZdefdZdee   ddfdZdeddfdZ dee!   dee"   fdZ#dee$   fdZ%ddde&fd Z'e(e(dfd!e)e*ee+   ee,   f      d"e)e*e-e.f      d#e)e
   de/fd$Z0e1de2fd%       Z3y)&
RunContexta  A context for running a conversation with an agent or a model.

    The context can be used to execute function calls, connect to MCP server, and keep track of information about
    the run.

    Args:
        conversation_id (Options[str]): The unique identifier for the conversation. This is
          passed if the user wants to continue an existing conversation.
        model (Options[str]): The model name to be used for the conversation. Can't be used along with 'agent_id'.
        agent_id (Options[str]): The agent id to be used for the conversation. Can't be used along with 'model'.
        output_format (Optional[type[BaseModel]]): The output format expected from the conversation. It represents
          the `response_format` which is part of the `CompletionArgs`.
        request_count (int): The number of requests made in the current `RunContext`.
        continue_on_fn_error (bool): Flag to determine if the conversation should continue when function execution
          resulted in an error.
    F)init_exit_stack)r9   default_factory_callable_tools_mcp_clientsN)defaultconversation_idr2   r'   output_formatr   request_countcontinue_on_fn_errorc                 h    | j                   r| j                  rt        d      t               | _        y )Nz,Only one for model or agent_id should be set)r2   r'   r   r   r:   selfs    r/   __post_init__zRunContext.__post_init__]   s&    ::$--MNN)+r.   c                    K   | S wNr-   rD   s    r/   
__aenter__zRunContext.__aenter__b   s     s   c                    K   | j                   j                          d {    | j                  D ]  }|j                          d {     y 7 .7 	wrH   )r:   acloser=   )rE   exc_typeexc_valexc_tb
mcp_clients        r/   	__aexit__zRunContext.__aexit__e   sN     %%'''++ 	&J##%%%	& 	(%s!   AA&AAAAfuncc                 z   t        j                        st        d      t        j                        r9t	        j
                  t                    | j                  j
                  <   n8t        j
                  t                    | j                  j
                  <   t              fd       }|S )zAdd a function to the context.z=Only object of type function can be registered at the moment.)name	awaitabletool)rS   callablerU   c                  X    t         j                  dj                           | i |S )Nz
Executing )loggerinfor(   )argskwargsrQ   s     r/   wrapperz)RunContext.register_func.<locals>.wrapper~   s*    KK*T]]O45(((r.   )
inspect
isfunctionr   iscoroutinefunctionr#   r(   r    r<   r   r   )rE   rQ   r\   s    ` r/   register_funczRunContext.register_funcj   s    !!$'O  &&t,2>]]%d+3D  / 3>]]%d+3D  / 
t	) 
	) r.   mcp_clientsreturnc                 P   K   |D ]  }| j                  |       d{     y7 w)zKRegistering multiple MCP clients at the same time in the same asyncio.Task.N)register_mcp_client)rE   ra   rO   s      r/   register_mcp_clientszRunContext.register_mcp_clients   s,     % 	7J**:666	76s   &$&rO   c                   K   |j                  | j                         d{    |j                          d{   }|D ]  }t        j	                  d|j
                  j                   d|j                  xs d        t        |j
                  j                  ||      | j                  |j
                  j                  <    | j                  j                  |       y7 7 w)z Add a MCP client to the context.)
exit_stackNzAdding tool z from z
mcp client)rS   rU   rO   )
initializer:   	get_toolsrX   rY   functionrS   _namer"   r<   r=   append)rE   rO   r4   rU   s       r/   rd   zRunContext.register_mcp_client   s     ##t/?/?#@@@ **,, 	DKKt}}112&9I9I9Y\8Z[ 8B]]''%8D  !3!34		 	  , 	A,s     C&C"C&C$B(C&$C&function_callsc           
         K   t         fd|D              st        j                  d       g S g }|D ]S  }|j                  t	        j
                  t        | j                  |j                      j                                     U t	        j                  |  d{    |D cg c]  }|j                          c}S 7 "c c}w w)z=Execute function calls and create function results from them.c              3   N   K   | ]  }|j                   j                  v   y wrH   )rS   r<   ).0function_callrE   s     r/   	<genexpr>z4RunContext.execute_function_calls.<locals>.<genexpr>   s*      
 $"6"66
s   "%z.Can't execute all functions, stopping run here)rq   run_toolrB   N)allrX   warningrl   asynciocreate_taskr   r<   rS   rB   gatherresult)rE   rm   function_result_tasksrq   tasks   `    r/   execute_function_callsz!RunContext.execute_function_calls   s       
!/
 
 NNKLI "+ 		M!((##*&3!%!5!5m6H6H!I-1-F-F		 nn3444*?@$@@ 	5@s$   BCCC'C>CCc                 r    | j                   j                         D cg c]  }|j                   }}|S c c}w )z+Get the tools that are part of the context.)r<   valuesrU   )rE   run_functionscallable_toolss      r/   ri   zRunContext.get_tools   s@     594H4H4O4O4Q
#0M
 
 
s   4beta_clientr$   c                   K   | j                   t        d      |j                  j                  | j                          d{   }|j                  xs g }g }t        t        |            D ]\  }||   }|j                  dk7  r|j                  |       )|j                  j                  | j                  v rL|j                  |       ^ || j                         z  }| j                  rt        | j                        nd}|j                  j!                  | j                   ||       t#        | j                         S 7 w)zPrepare an agent request with the functions added to the context.

        Update the agent definition before making the request.
        Nz:Can't prepare an agent request, if no agent_id is provided)r'   rj   response_format)r'   r4   r5   )r'   r   agents	get_asyncr4   rangelentyperl   rj   rS   r<   ri   r@   r   r   updater&   )rE   r   agentagent_toolsupdated_toolsirU   r5   s           r/   prepare_agent_requestz RunContext.prepare_agent_request   s/    
 == L  "((22DMM2JJkk'Rs;'( 	+Aq>DyyJ&$$T*##t';';;$$T*	+ 	)) !! 4+?+?@ 	
 	!!]]- 	" 	
 "4==99+ Ks   AEEC?Er4   r5   r3   c                 d  K   | j                   t        d      |s#| j                  rt        | j                        }npt        |t              r| j                  r| j                  |_        nBt        |t              r2| j                  r&t        j                  |      }| j                  |_        g }t        |t              r0|D ]+  }|j                  t        j                  t        |             - | j                         D ]  }|j                  |        t        | j                   |||      S w)Nz6Can't prepare a model request, if no model is providedr   )r2   r4   r3   r5   )r2   r   r@   r   r   
isinstancedictmodel_validater6   rl   typingcastr   ri   r1   )rE   r4   r5   r3   request_toolsrU   s         r/   prepare_model_requestz RunContext.prepare_model_request   s     ::WXX4#5#5,T=Q=QRO8T=O=O.2.B.BO+.43E3E,;;OLO.2.B.BO+eT" ?$$V[[%=>?NN$ 	'D  &	'!**%+	
 	
s   D.D0c                 Z    | j                   st        d      t        | j                         S )Nz4No response format exist for the current RunContext.)r@   r   r
   rD   s    r/   r   zRunContext.response_format   s(    !!UVV243E3EFFr.   )4r(   r)   r*   __doc__r   r:   r   r,   r   r<   r+   r!   r6   r=   r   r?   r	   r2   r'   r@   r   r   rA   intrB   boolrF   rI   rP   r   r`   re   rd   r   r   r|   r   ri   r&   r   r   r   r   r   r   r   r   r1   r   propertyr   r   r-   r.   r/   r8   r8   ?   s   " #(U"3K3*/UD*QOT#w,'Q,1ud,SL$()S%*4%8OXc]8 .E8C=.#D1Hhsm1/4T/BM8DO,Bq)M3)!&u!5$5,
&
( 67d;L6M 7RV 7
-4E -$ -A"#45A	!	"A04- :v :BT :D MR .2
d5k43G&G HI
 *."99:

 's+
 

< G G Gr.   r8   r3   r4   r5   r   r$   run_ctxinputsr3   r4   r5   rb   c                 0  K   g }t        |t              r|j                  t        d|             nO|D ]J  }t        |t              s|j                  t        j                  t              j                  |             L t        ||j                  |j                        }|j                  r*|s|rt        d      |j                  |        d {   }	n4|j                  r|j!                  |||       d {   }	nt        d      |	||fS 7 >7 w)Nuser)rolecontent)input_entriesoutput_modelr?   z6Can't set tools or completion_args when using an agent)r   r   z7Either agent_id or model must be set in the run context)r   r+   rl   r   r   pydanticTypeAdapterr   validate_pythonr   r@   r?   r'   r   r   r2   r   )
r   r   r   r3   r4   r5   r   input
run_resultreqs
             r/   _validate_runr      s     )+M&#.FFKL 	E%&$$((6FFuM	
 #**//J OWXX11k1JJ	11%+ 2 
 
 TUU
M)) K
s+   ADBDD(D<D=DD)>rv   r]   r   
contextlibr   	functoolsr   collections.abcr   dataclassesr   r   r   r	   r   mistralai.extrar
   mistralai.extra.exceptionsr   mistralai.extra.mcp.baser   mistralai.extra.run.resultr   mistralai.types.basemodelr   r   r   mistralai.modelsr   r   r   r   r   r   r   r   r   r   r   r   loggingr   mistralai.extra.run.toolsr   r   r    r!   r"   r#   TYPE_CHECKING	mistralair$   r(   rX   	TypedDictr&   r1   r8   r+   r6   tupler   r-   r.   r/   <module>r      si      %  $ ( "  4 6 0 H H      
0	8	)) V)) V zG zG zGD +0HM 	(*(* (* $&AAB	(*
 #3'(* E$u+tN/C"CDE(* &n556(* 	
0
019d<>PP(*r.   