o
    if+                     @   s  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j1rd dl2m3Z3mZ e)e4Z5G dd dej6Z7G dd dej6Z8e
G d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d Z=dS )!    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                   @   s   e Zd ZU eed< dS )AgentRequestKwargsagent_idN)__name__
__module____qualname__str__annotations__ r+   r+   a/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/mistralai/extra/run/context.pyr$   4   s   
 r$   c                   @   sR   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< dS )ModelRequestKwargsmodelinstructionstoolscompletion_argsN)r&   r'   r(   r)   r*   r   r   listr   r   r   r   r+   r+   r+   r,   r-   8   s
   
 r-   c                	   @   s  e Zd ZU dZeddZeed< ededZ	ee
ef ed< ededZee ed< edd	Zee
 ed
< edd	Zee
 ed< edd	Zee
 ed< edd	Zeee  ed< edd	Zeed< edd	Zeed< dd Zdd Zdd ZdefddZdee ddfddZdeddfdd Z d!ee! dee" fd"d#Z#dee$ fd$d%Z%d&d'de&fd(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-d.Z0e1de2fd/d0Z3dS )1
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)r4   default_factory_callable_tools_mcp_clientsN)defaultconversation_idr.   r%   output_formatr   request_countcontinue_on_fn_errorc                 C   s    | j r
| jr
tdt | _d S )Nz,Only one for model or agent_id should be set)r.   r%   r
   r   r5   selfr+   r+   r,   __post_init__]   s   zRunContext.__post_init__c                    s   | S Nr+   r>   r+   r+   r,   
__aenter__b   s   zRunContext.__aenter__c                    s0   | j  I d H  | jD ]	}| I d H  qd S rA   )r5   acloser8   )r?   exc_typeexc_valexc_tb
mcp_clientr+   r+   r,   	__aexit__e   s
   
zRunContext.__aexit__funcc                    sn   t  s	tdt  rt j t d| j j< nt j t d| j j< t	  fdd}|S )zAdd a function to the context.z=Only object of type function can be registered at the moment.)name	awaitabletool)rJ   callablerL   c                     s    t d j   | i |S )Nz
Executing )loggerinfor&   )argskwargsrI   r+   r,   wrapper~   s   z)RunContext.register_func.<locals>.wrapper)
inspect
isfunctionr
   iscoroutinefunctionr"   r&   r   r7   r   r   )r?   rI   rS   r+   rR   r,   register_funcj   s$   

zRunContext.register_funcmcp_clientsreturnc                    s    |D ]
}|  |I dH  qdS )zKRegistering multiple MCP clients at the same time in the same asyncio.Task.N)register_mcp_client)r?   rX   rG   r+   r+   r,   register_mcp_clients   s   zRunContext.register_mcp_clientsrG   c                    sz   |j | jdI dH  | I dH }|D ] }td|jj d|jp"d  t|jj||d| j	|jj< q| j
| dS )z Add a MCP client to the context.)
exit_stackNzAdding tool z from z
mcp client)rJ   rL   rG   )
initializer5   	get_toolsrN   rO   functionrJ   _namer!   r7   r8   append)r?   rG   r0   rL   r+   r+   r,   rZ      s   zRunContext.register_mcp_clientfunction_callsc              
      sv   t  fdd|D std g S g }|D ]}|tt| j|j  j	d qtj
| I dH  dd |D S )z=Execute function calls and create function results from them.c                 3   s    | ]	}|j  jv V  qd S rA   )rJ   r7   ).0function_callr>   r+   r,   	<genexpr>   s
    

z4RunContext.execute_function_calls.<locals>.<genexpr>z.Can't execute all functions, stopping run here)rd   run_toolr=   Nc                 S   s   g | ]}|  qS r+   )result)rc   taskr+   r+   r,   
<listcomp>   s    z5RunContext.execute_function_calls.<locals>.<listcomp>)allrN   warningra   asynciocreate_taskr   r7   rJ   r=   gather)r?   rb   function_result_tasksrd   r+   r>   r,   execute_function_calls   s&   

	z!RunContext.execute_function_callsc                 C   s   dd | j  D }|S )z+Get the tools that are part of the context.c                 S   s   g | ]}|j qS r+   )rL   )rc   run_functionsr+   r+   r,   ri      s    z(RunContext.get_tools.<locals>.<listcomp>)r7   values)r?   callable_toolsr+   r+   r,   r^      s   zRunContext.get_toolsbeta_clientr#   c                    s   | j du r
td|jj| j dI dH }|jpg }g }tt|D ]}|| }|jdkr3|| q"|j	j
| jv r;q"|| q"||  7 }| jrPt| jdnd}|jj| j ||d t| j dS )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%   r_   response_format)r%   r0   r1   )r%   r
   agents	get_asyncr0   rangelentypera   r_   rJ   r7   r^   r;   r   rv   updater$   )r?   rt   agentagent_toolsupdated_toolsirL   r1   r+   r+   r,   prepare_agent_request   s0   


z RunContext.prepare_agent_requestr0   r1   r/   c                    s   | j d u r
td|s| jrt| jd}nt|tr#| jr#| j|_nt|tr4| jr4t|}| j|_g }t|trI|D ]}|	t
t| q=|  D ]}|	| qMt| j |||dS )Nz6Can't prepare a model request, if no model is providedru   )r.   r0   r/   r1   )r.   r
   r;   r   rv   
isinstancedictmodel_validater2   ra   typingcastr   r^   r-   )r?   r0   r1   r/   request_toolsrL   r+   r+   r,   prepare_model_request   s,   




z RunContext.prepare_model_requestc                 C   s   | j stdt| j S )Nz4No response format exist for the current RunContext.)r;   r
   r	   r>   r+   r+   r,   rv      s   
zRunContext.response_format)4r&   r'   r(   __doc__r   r5   r   r*   r   r7   r)   r    r2   r8   r   r:   r   r.   r%   r;   r{   r   r<   intr=   boolr@   rB   rH   r   rW   r[   rZ   r   r   rp   r   r^   r$   r   r   r   r   r   r   r   r   r-   r   propertyr   rv   r+   r+   r+   r,   r3   ?   sP   
 
"

r3   r/   r0   r1   rt   r#   run_ctxinputsr/   r0   r1   rY   c           
         s   g }t |tr|td|d n|D ]}t |tr&|tt| qt	||j
|jd}|jrE|s7|r;td|j| dI d H }	n|jrT|j|||dI d H }	ntd|	||fS )Nuser)rolecontent)input_entriesoutput_modelr:   z6Can't set tools or completion_args when using an agent)rt   r   z7Either agent_id or model must be set in the run context)r   r)   ra   r   r   pydanticTypeAdapterr   validate_pythonr   r;   r:   r%   r
   r   r.   r   )
rt   r   r   r/   r0   r1   r   input
run_resultreqr+   r+   r,   _validate_run   s6   


r   )>rl   rT   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&   rN   	TypedDictr$   r-   r3   r)   r2   tupler   r+   r+   r+   r,   <module>   s^    8 	 C


