
    wi,                     (   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m	Z	 d dl
mZ d dl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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*m+Z+m,Z, d dl-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             Z9e0e0e0dddde9de!e"z  de/e:   de/e;e#   e;e$   z     de/ee z     de<e7e8z  ee;e(   f   fdZ=y)    N)Callable)AsyncExitStack)	dataclassfield)wraps)	getLogger)#response_format_from_pydantic_model)RunException)MCPClientProtocol)	RunResult)RunCoroutineRunFunction
RunMCPToolRunToolcreate_function_resultcreate_tool_call)CompletionArgsCompletionArgsTypedDictConversationInputsConversationInputsTypedDictConversationRequestTool ConversationRequestToolTypedDictFunctionCallEntryFunctionResultEntryFunctionToolInputEntriesMessageInputEntryResponseFormatUnknownAgentToolUpdateAgentRequestTool)	BaseModelOptionalNullableUNSET)Betar"   c                       e Zd ZU eed<   y)AgentRequestKwargsagent_idN)__name__
__module____qualname__str__annotations__     ]/home/ubuntu/bibliothek-app/.venv/lib/python3.12/site-packages/mistralai/extra/run/context.pyr&   r&   0   s    Mr.   r&   c                   `    e Zd ZU eed<   ee   ed<   eee   ee   z     ed<   ee	e
z     ed<   y)ModelRequestKwargsmodelinstructionstoolscompletion_argsN)r(   r)   r*   r+   r,   r"   listr   r   r   r   r-   r.   r/   r1   r1   4   s?    J"3''D!89DAa<bbcc%n7N&NOOr.   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
dz  ed
<    ed	      Ze
dz  ed<    ed	      Ze
dz  ed<    ed	      Zee   dz  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*   z     d"e(e+e,z     d#e(e
   de-fd$Z.e/de0fd%       Z1y)&
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 (type[BaseModel] | None): 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__Y   s&    ::$--MNN)+r.   c                    K   | S wNr-   rD   s    r/   
__aenter__zRunContext.__aenter__^   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__a   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>.wrapperz   s*    KK*T]]O45(((r.   )
inspect
isfunctionr
   iscoroutinefunctionr   r(   r   r<   r   r   )rE   rQ   r\   s    ` r/   register_funczRunContext.register_funcf   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 }|D ]i  }t        |t              rt        |t              s|j                  |       6|j                  j                  | j                  v rY|j                  |       k || 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'   response_format)r'   r4   r5   )r'   r
   agents	get_asyncr4   
isinstancer   r   rl   rj   rS   r<   ri   r@   r   r   updater&   )rE   r   agentagent_toolsupdated_toolsrU   r5   s          r/   prepare_agent_requestz RunContext.prepare_agent_request   s(    
 == L  "((22DMM2JJkk'R68 
	+D$ 01dL1$$T*##t';';;$$T*
	+ 	)) !! 4+?+?@ 	
 	!!]]- 	" 	
 "4==99/ Ks   AD?D=C:D?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   r   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" Q$$V[[1H$%OPQNN$ 	'D  &	'!**%+	
 	
s   D.D0c                     | j                   st        d      t        j                  t	        | j                               S )Nz4No response format exist for the current RunContext.)r@   r
   r   r   r	   rD   s    r/   r   zRunContext.response_format   s8    !!UVV,,/0B0BC
 	
r.   )2r(   r)   r*   __doc__r   r:   r   r,   r   r<   r+   r   r6   r=   r   r?   r2   r'   r@   typer!   rA   intrB   boolrF   rI   rP   r   r`   re   rd   r   r   r|   r   ri   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"'"5OS4Z5d+E3:+ .HcDj.,1$,?M4	?T)?q)M3)!&u!5$5,
&
( 67d;L6M 7RV 7
-4E -$ -A"#45A	!	"A04-  :v  :BT  :H kpV[.2	
%< =Ee@f fg
 *.;R*RS
 's+	

 

8 
 
 
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   collections.abcr   
contextlibr   dataclassesr   r   	functoolsr   loggingr   r   mistralai.extrar	   mistralai.extra.exceptionsr
   mistralai.extra.mcp.baser   mistralai.extra.run.resultr   mistralai.extra.run.toolsr   r   r   r   r   r   mistralai.client.modelsr   r   r   r   r   r   r   r   r   r   r   r   r   r     mistralai.client.types.basemodelr!   r"   r#   TYPE_CHECKINGmistralai.clientr$   r(   rX   	TypedDictr&   r1   r8   r+   r6   tupler   r-   r.   r/   <module>r      sF      $ % (    ? 3 6 0      P O	7	8	)) P)) P |
 |
 |
H +0fkRW&*&* &* !<<	&*
 #3'&* D!89DAa<bbc&* &n7N&NO&* ++Y\8JJ&*r.   