o
    i                  
   @  s  U d dl mZ d dlmZmZmZ d dlmZ d dl	m
Z
mZ d dlmZ d dlmZmZmZ d dl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 d
dlmZmZm Z  d
dl!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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 d
dl8m9Z9 d
dl:m;Z;m<Z< d
dl=m>Z> d
dl?m@Z@ d
dlAmBZB ddlmCZCmDZDmEZEmFZFmGZG z^d dlHmIZImJZKmLZMmNZOmPZQmRZSmTZUmVZWmXZXmYZZm[Z\m]Z^m_Z`maZb d dlcmdZemfZgm)ZhmiZjmkZkmlZmmnZo d dlpmqZr d dlsmtZu d dlvmwZx d dlymzZ{ d dl|m}Z~ d dlmZ d dlmZ W n ey) Z zed edZ[ww ed! Z	 eeB Z	 d"d#d#d$d%d&Zd'ed(< G d)d* d*e>d+d,Ze
d+d-G d.d/ d/eCZedB Ze
G d0d1 d1eEZeeeeeeedd2Zd3ed4< d5d6d7d8d9d:d;ZdGd@dAZdHdEdFZdS )I    )annotations)AsyncIterableAsyncIteratorIterable)asynccontextmanager)	dataclassfield)datetime)AnyLiteralcastN)Timeout)assert_never   )ModelHTTPErrorUnexpectedModelBehavior_utils)
RunContext)generate_tool_call_idnow_utcnumber_to_datetime)	UserError)BinaryContentBuiltinToolCallPartBuiltinToolReturnPartDocumentUrlFilePartFinishReasonImageUrlModelMessageModelRequestModelResponseModelResponsePartModelResponseStreamEventRetryPromptPartSystemPromptPartTextPartThinkingPartToolCallPartToolReturnPartUserPromptPartVideoUrl)ModelProfileSpec)Providerinfer_provider)ModelSettings)ToolDefinition)RequestUsage   )ModelModelRequestParametersStreamedResponsecheck_allow_model_requestsget_user_agent)UNSETCompletionChunkContentContentChunkDocumentURLChunkFunctionCallImageURLImageURLChunkMistralOptionalNullableReferenceChunk	TextChunk
ThinkChunkToolChoiceEnum)ChatCompletionResponseCompletionEventr   MessagesSDKErrorToolToolCall)AssistantMessage)Function)SystemMessage)ToolMessage)UserMessage)Unset)EventStreamAsyncu   Please install `mistral` to use the Mistral model, you can use the `mistral` optional group — `pip install "pydantic-ai-slim[mistral]"`)zmistral-large-latestzmistral-small-latestzcodestral-latestzmistral-moderation-lateststoplengtherror	tool_call)rS   rT   model_lengthrU   
tool_callsz'dict[MistralFinishReason, FinishReason]_FINISH_REASON_MAPc                   @  s   e Zd ZdZdS )MistralModelSettingsz*Settings used for a Mistral model request.N)__name__
__module____qualname____doc__ r_   r_   `/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/models/mistral.pyrZ   q   s    rZ   F)total)initc                      sP  e Zd ZU dZeddZded< ded< eddZded	< eddZd
ed< ddddddb fddZ	e
dcddZe
ddddZe
dcddZded&d'Ze	dfdgd+d,Zdhd/d0Zdid2d3Zdjd5d6Zdkd8d9Zdld;d<Zdmd>d?ZedndCdDZedodFdGZdpdKdLZedqdOdPZedrdTdUZdsdYdZZdtd\d]Zdud`daZ   Z!S )vMistralModelzA model that uses Mistral.

    Internally, this uses the [Mistral Python client](https://github.com/mistralai/client-python) to interact with the API.

    [API Documentation](https://docs.mistral.ai/)
    F)reprr@   clientstrjson_mode_schema_promptMistralModelName_model_namezProvider[Mistral]	_providermistralNz<Answer in JSON Object, respect the format:
```
{schema}
```
)providerprofilerg   settings
model_namerl   &Literal['mistral'] | Provider[Mistral]rm   ModelProfileSpec | Nonern   ModelSettings | Nonec                  sF   || _ || _t|trt|}|| _|j| _t j||p|j	d dS )a  Initialize a Mistral model.

        Args:
            model_name: The name of the model to use.
            provider: The provider to use for authentication and API access. Can be either the string
                'mistral' or an instance of `Provider[Mistral]`. If not provided, a new provider will be
                created using the other parameters.
            profile: The model profile to use. Defaults to a profile picked by the provider based on the model name.
            json_mode_schema_prompt: The prompt to show when the model expects a JSON object as input.
            settings: Model-specific settings that will be used as defaults for this model.
        )rn   rm   N)
ri   rg   
isinstancerf   r.   rj   re   super__init__model_profile)selfro   rl   rm   rg   rn   	__class__r_   r`   ru      s   
zMistralModel.__init__returnc                 C     | j jS N)rj   base_urlrw   r_   r_   r`   r}      s   zMistralModel.base_urlc                 C     | j S )zThe model name.ri   r~   r_   r_   r`   ro         zMistralModel.model_namec                 C  r{   )zThe model provider.)rj   namer~   r_   r_   r`   system   s   zMistralModel.systemmessageslist[ModelMessage]model_settingsmodel_request_parametersr4   r!   c                   sD   t   | ||\}}| |tt|pi |I dH }| |}|S )z@Make a non-streaming request to the model from Pydantic AI call.N)r6   prepare_request_completions_creater   rZ   _process_response)rw   r   r   r   responsemodel_responser_   r_   r`   request   s   

zMistralModel.requestrun_contextRunContext[Any] | NoneAsyncIterator[StreamedResponse]c              	   C s   t   | ||\}}| |tt|pi |I dH }|4 I dH  | ||I dH V  W d  I dH  dS 1 I dH s=w   Y  dS )z<Make a streaming request to the model from Pydantic AI call.N)r6   r   _stream_completions_creater   rZ   _process_streamed_response)rw   r   r   r   r   r   r_   r_   r`   request_stream   s   	
.zMistralModel.request_streamrZ   MistralChatCompletionResponsec                   s   |j rtdzE| jjjt| j| ||d| |pt	| 
|d|dt	|dt	|dd| |d|dt	|d	d
dt idI d
H }W n tyk } z|j }dkrft|| j|jd| d
}~ww |srJ d|S )z*Make a non-streaming request to the model.'Mistral does not support built-in toolsr2   F
max_tokenstemperaturetop_ptimeoutseedstop_sequencesN
User-Agent)modelr   ntoolstool_choicestreamr   r   r   
timeout_msrandom_seedrS   http_headersi  )status_codero   body)A unexpected empty response from Mistral.)builtin_toolsr   re   chatcomplete_asyncrf   ri   _map_messages)_map_function_and_output_tools_definitionr8   _get_tool_choiceget_get_timeout_msr7   rI   r   r   ro   r   )rw   r   r   r   r   er   r_   r_   r`   r      s6   	





z MistralModel._completions_create/MistralEventStreamAsync[MistralCompletionEvent]c                   s8  |  ||}|jrtd|jrS| jjjt| j|d| 	|p!t
| ||dt
|dd|dt
| |d|d|d|d	d
dt idI d
H }nA|jrdd |jD }| |}|| | jjjt| j|ddiddt idI d
H }n| jjjt| j|ddt idI d
H }|sJ d|S )z;Create a streaming completion request to the Mistral model.r   r2   r   r   r   r   presence_penaltyfrequency_penaltyr   Nr   )r   r   r   r   r   r   r   r   r   r   r   rS   r   c                 S  s   g | ]}|j qS r_   )parameters_json_schema).0toolr_   r_   r`   
<listcomp>"  s    z;MistralModel._stream_completions_create.<locals>.<listcomp>typejson_objectT)r   r   response_formatr   r   )r   r   r   r   r   )r   r   r   function_toolsre   r   stream_asyncrf   ri   r   r8   r   r   r   r7   output_tools_generate_user_output_formatappend)rw   r   r   r   mistral_messagesr   parameters_json_schemasuser_output_format_messager_   r_   r`   r      sP   





z'MistralModel._stream_completions_createMistralToolChoiceEnum | Nonec                 C  s   |j s|jsdS |jsdS dS )zGet tool choice for the model.

        - "auto": Default mode. Model decides if it uses the tool or not.
        - "any": Select any tool.
        - "none": Prevents tool use.
        - "required": Forces tool use.
        Nrequiredauto)r   r   allow_text_output)rw   r   r_   r_   r`   r   ;  s
   zMistralModel._get_tool_choicelist[MistralTool] | Nonec                 C  s    dd |j  D }|r|S dS )zMap function and output tools to MistralTool format.

        Returns None if both function_tools and output_tools are empty.
        c                 S  s*   g | ]}t t|j|j|jpd ddqS ) )r   
parametersdescription)function)MistralToolMistralFunctionr   r   r   )r   rr_   r_   r`   r   Q  s    zJMistralModel._map_function_and_output_tools_definition.<locals>.<listcomp>N)	tool_defsvalues)rw   r   r   r_   r_   r`   r   J  s   z6MistralModel._map_function_and_output_tools_definitionr   c              
   C  s   |j sJ d|jrt|j}nt }|j d }|jj}|jj}g }t|\}}|D ]
}	|t	|	d q*|r?|t
|d t|trT|D ]}
| j|
d}|| qF|j}d|i}t|}t|t||j||j| jj||dS )zAProcess a non-streamed response, and prepare a message to return.z!Unexpected empty response choice.r   content)rV   finish_reason)partsusagero   	timestampprovider_response_idprovider_namer   provider_details)choicescreatedr   _now_utcmessager   rX   _map_contentr   r'   r&   rs   list"_map_mistral_to_pydantic_tool_callr   rY   r   r!   
_map_usager   idrj   r   )rw   r   r   choicer   rX   r   textthinkingthoughtrV   r   raw_finish_reasonr   r   r_   r_   r`   r   [  s<   


zMistralModel._process_responser5   c                   sd   t |}| I dH }t|t jrtd|jjr"t|jj}nt	 }t
|||jj|| jjdS )zHProcess a streamed response, and prepare a streaming response to return.Nz5Streamed response ended without content or tool calls)r   	_responseri   
_timestamp_provider_name)r   PeekableAsyncStreampeekrs   rQ   r   datar   r   r   MistralStreamedResponser   rj   r   )rw   r   r   peekable_responsefirst_chunkr   r_   r_   r`   r     s"   
z'MistralModel._process_streamed_responserV   MistralToolCallr(   c                 C  s"   | j pt }| j}t|j|j|S )z%Maps a MistralToolCall to a ToolCall.)r   _generate_tool_call_idr   r(   r   	arguments)rV   tool_call_id	func_callr_   r_   r`   r     s   z/MistralModel._map_mistral_to_pydantic_tool_calltc                 C  s&   t tj| ddt| j| jpi ddS )z1Maps a pydantic-ai ToolCall to a MistralToolCall.r   r   )r   r   )r   r   r   )r   r   guard_tool_call_idMistralFunctionCall	tool_nameargsr   r_   r_   r`   _map_tool_call  s
   
zMistralModel._map_tool_callschemaslist[dict[str, Any]]MistralUserMessagec                 C  sp   g }|D ]}i }| di  D ]\}}| |||< q|| qt|dkr,|d n|}t| jj|ddS )z<Get a message with an example of the expected output format.
propertiesr2   r   )schemar   )r   items_get_python_typer   lenr   rg   format)rw   r   examplesr  typed_dict_definitionkeyvalueexample_schemar_   r_   r`   r     s   z)MistralModel._generate_user_output_formatr	  dict[str, Any]c                 C  s
  | d }rd| |d  dS | d}|sdS |tv r+|dkr+|dkr+t| S |dkr>| d	i }d
| | dS |dkr| di }t|trOdS | d}|tv rh|dkrh|dkrhdt|  dS |dkr{| d	i }d| | dS |dkrdS dS dS )zReturn a string representation of the Python type for a single JSON schema property.

        This function handles recursion for nested arrays/objects and `anyOf`.
        anyOfz	Optional[r   ]r   r
   arrayobjectr  zlist[additionalPropertiesboolz
dict[str, zdict[str, list[z]]zdict[str, dict[str, Any]]r  )r   r  SIMPLE_JSON_TYPE_MAPPINGrs   r  )clsr	  any_of
value_typer  additional_propertiesadditional_properties_typearray_itemsr_   r_   r`   r    s4   


zMistralModel._get_python_typer   Timeout | float | None
int | Nonec                 C  s*   | du rdS t | trtd|  S td)z"Convert a timeout to milliseconds.Ni  z5Timeout object is not yet supported for MistralModel.)rs   floatintNotImplementedError)r   r_   r_   r`   r     s
   
zMistralModel._get_timeout_msr   r    Iterable[MistralMessages]c                 c  s    |j D ]M}t|trt|jdV  qt|tr| |V  qt|tr/t|j	|
 dV  qt|trM|jd u rBt| dV  qt|j	| dV  qt| qd S )Nr   )r   r   )r   rs   r%   MistralSystemMessager   r*   _map_user_promptr)   MistralToolMessager   model_response_strr$   r   r   r   r   )rw   r   partr_   r_   r`   _map_user_message  s(   








zMistralModel._map_user_messagelist[MistralMessages]c                 C  s  g }|D ]x}t |tr|| | qt |trxg }g }g }|jD ]@}t |tr3|t|j	d q"t |t
rB|t|j	d q"t |trP|| | q"t |ttB rXq"t |tr^q"t| q"|rn|dt|d |t||d qt| q| || }	r|dt|	d g }
t|D ]-\}}|
| t |tr|d t|k r||d  }t |tr|
ttddgd q|
S )z8Just maps a `pydantic_ai.Message` to a `MistralMessage`.r   r   )r   )r   rX   r   r2   OK)rs   r    extendr$  r!   r   r&   r   MistralTextChunkr   r'   r(   r   r   r   r   r   insertMistralThinkChunkMistralAssistantMessage_get_instructionsr  	enumerater!  r  r   )rw   r   r   r   r   content_chunksthinking_chunksrX   r#  instructionsprocessed_messagesicurrent_messagenext_messager_   r_   r`   r     sF   










zMistralModel._map_messagesr#  r*   c                 C  s  t |jtr
|j}n~g }|jD ]x}t |tr|t|d qt |tr1|tt|jdd qt |t	r]|j
rIt|jd}|t|dd q|jdkrY|t|jdd qtd	t |trv|jdkrr|t|jdd qtd
t |trtdtdt| t|dS )Nr&  )url)	image_urlr7  )r7  r   zapplication/pdfdocument_url)r8  r   zBBinaryContent other than image or PDF is not supported in Mistral.z7DocumentUrl other than PDF is not supported in Mistral.z%VideoUrl is not supported in Mistral.zUnsupported content type: r   )rs   r   rf   r   r)  r   MistralImageURLChunkMistralImageURLr6  r   is_imagedata_uri
media_typeMistralDocumentURLChunkRuntimeErrorr   r+   r   r   )rw   r#  r   itemr7  r_   r_   r`   r   @  s.   








zMistralModel._map_user_prompt)
ro   rh   rl   rp   rm   rq   rg   rf   rn   rr   rz   rf   rz   rh   )r   r   r   rr   r   r4   rz   r!   r|   )
r   r   r   rr   r   r4   r   r   rz   r   )r   r   r   rZ   r   r4   rz   r   )r   r   r   rZ   r   r4   rz   r   )r   r4   rz   r   )r   r4   rz   r   )r   r   rz   r!   )r   r   r   r4   rz   r5   )rV   r   rz   r(   )r   r(   rz   r   )r   r   rz   r   )r	  r  rz   rf   )r   r  rz   r  )r   r    rz   r  )r   r   r   r4   rz   r%  )r#  r*   rz   r   )"r[   r\   r]   r^   r   re   __annotations__ri   rj   ru   propertyr}   ro   r   r   r   r   r   r   r   r   r   r   staticmethodr   r   r   classmethodr  r   r$  r   r   __classcell__r_   r_   rx   r`   rc   y   sN   
 


$
=


(
4

2rc   c                   @  s   e Zd ZU dZded< ded< ded< ded	< ed
ddZded< d%ddZed&ddZ	ed'ddZ
ed(ddZed)ddZed*d"d#Zd$S )+r   z8Implementation of `StreamedResponse` for Mistral models.rh   ri   z%AsyncIterable[MistralCompletionEvent]r   r	   r   rf   r   r   F)defaultrb   _delta_contentrz   'AsyncIterator[ModelResponseStreamEvent]c              	   C sf  | j 2 z3 d H W }|  jt|j7  _|jjr|jj| _z|jjd }W n	 ty.   Y qw |j }r?d|i| _	t
|| _|jj}t|\}}|D ]
}| jjd|d qK|rdd | jjD }|r|  j|7  _| | j|}	|	r| jjd|	j|	 |	jdV  n| jjd	|d}
|
d ur|
V  t|jjpg D ]\}}| jj||jj|jj|jdV  qq6 d S )
Nr   r   r   )vendor_part_idr   c                 S  s   i | ]}|j |qS r_   )r   )r   cr_   r_   r`   
<dictcomp>  s    z?MistralStreamedResponse._get_event_iterator.<locals>.<dictcomp>output)rK  r   r   r   r   )r   _usager   r   r   r   r   
IndexErrorr   r   rY   r   deltar   r   _parts_managerhandle_thinking_deltar   r   rI  _try_get_output_tool_from_texthandle_tool_call_partr   args_as_dictr   handle_text_deltar.  rX   r   r   r   )rw   chunkr   r   r   r   r   r   r   maybe_tool_call_partmaybe_eventindexdtcr_   r_   r`   _get_event_iteratorm  sN   



z+MistralStreamedResponse._get_event_iteratorc                 C  r   )z#Get the model name of the response.r   r~   r_   r_   r`   ro     r   z"MistralStreamedResponse.model_namec                 C  r   )zGet the provider name.)r   r~   r_   r_   r`   r     r   z%MistralStreamedResponse.provider_namec                 C  r   )z"Get the timestamp of the response.)r   r~   r_   r_   r`   r     r   z!MistralStreamedResponse.timestampr   r   dict[str, ToolDefinition]ToolCallPart | Nonec                 C  sH   t j| dd}|r | D ]}t||jsqt|j|d  S d S d S )Nztrailing-strings)allow_partial)r   r   )pydantic_core	from_jsonr   r   _validate_required_json_schemar   r(   r   )r   r   output_jsonoutput_toolr_   r_   r`   rT    s   z6MistralStreamedResponse._try_get_output_tool_from_text	json_dictr  json_schemar  c           
      C  s   | dg }| di }|D ]f}|| vr dS | |i }| d}| di  d}|dkrN|rNt| | ts; dS | | D ]}t|t| sL  dS q?n|r\t| | t| s\ dS t| | trtd|v rt|}	t| | |	st dS qdS )z\Validate that all required parameters in the JSON schema are present in the JSON dictionary.r   r   Fr   r  r  T)r   rs   r   VALID_JSON_TYPE_MAPPINGdictr   rc  )
rf  rg  required_paramsr   paramparam_schema
param_typeparam_items_typer@  nested_schemar_   r_   r`   rc    s0   
z6MistralStreamedResponse._validate_required_json_schemaN)rz   rJ  rB  rA  )rz   r	   )r   rf   r   r^  rz   r_  )rf  r  rg  r  rz   r  )r[   r\   r]   r^   rC  r   rI  r]  rD  ro   r   r   rE  rT  rc  r_   r_   r_   r`   r   b  s$   
 
0r   )stringintegernumberbooleanr  r  nullr  rh  rf   r  r  r  r   None)rp  rq  rr  rs  r  rt  r   6MistralChatCompletionResponse | MistralCompletionChunkrz   r1   c                 C  s(   | j rt| j jp	d| j jpddS t S )zGMaps a Mistral Completion Chunk or Chat Completion Response to a Usage.r   )input_tokensoutput_tokens)r   r1   prompt_tokenscompletion_tokens)r   r_   r_   r`   r     s   

r   r   'MistralOptionalNullable[MistralContent]tuple[str | None, list[str]]c                 C  s   d}g }t | ts| sdg fS t | trF| D ].}t |tr%|p#d|j }qt |tr<|jD ]}|jdkr:||j q-qJ dt| nt | t	rM| }|rWt
|dkrWd}||fS )zKMaps the delta content from a Mistral Completion Chunk to a string or None.Nr   r   FzEOther data types like (Image, Reference) are not yet supported,  got r   )rs   MistralUnsetr   r)  r   r+  r   r   r   rf   r  )r   r   r   rX  r   r_   r_   r`   r     s.   





r   )r   rv  rz   r1   )r   r{  rz   r|  )
__future__r   _annotationscollections.abcr   r   r   
contextlibr   dataclassesr   r   r	   typingr
   r   r   ra  httpxr   typing_extensionsr   r   r   r   r   _run_contextr   r   r   r   r   r   
exceptionsr   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   profilesr,   	providersr-   r.   rn   r/   r   r0   r   r1   r3   r4   r5   r6   r7   	mistralair8   r9   MistralCompletionChunkr:   MistralContentr;   MistralContentChunkr<   r>  r=   r   r>   r:  r?   r9  r@   rA   MistralOptionalNullablerB   MistralReferenceChunkrC   r)  rD   r+  rE   MistralToolChoiceEnummistralai.modelsrF   r   rG   MistralCompletionEventMistralFinishReasonrH   MistralMessagesrI   rJ   r   rK   r   !mistralai.models.assistantmessagerL   r,  mistralai.models.functionrM   r   mistralai.models.systemmessagerN   r  mistralai.models.toolmessagerO   r!  mistralai.models.usermessagerP   r   mistralai.types.basemodelrQ   r}  mistralai.utils.eventstreamingrR   MistralEventStreamAsyncImportErrorr   LatestMistralModelNamesrf   rh   rY   rC  rZ   rc   MistralToolCallIdr   r  r  r  r   ri  r   rh  r  r   r   r_   r_   r_   r`   <module>   s    X@$		   hy

