o
    i6                  
   @  s  U 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mZ d dlmZ ddlmZmZ dd	l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%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m0Z0m1Z1m2Z2 z0d dl3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZB d dlCmDZD d dlEmFZF W n eGy ZH zeGdeHdZH[Hww e	d ZI	 eJeIB ZK	 ddddddZLdeMd< G dd de-d d!ZNed d"G d#d$ d$e0ZOd+d)d*ZPdS ),    )annotations)Iterable)	dataclassfield)Literalcast)assert_never)	UserError   )ModelHTTPErrorusage)generate_tool_call_idguard_tool_call_id)BuiltinToolCallPartBuiltinToolReturnPartFilePartFinishReasonModelMessageModelRequestModelResponseModelResponsePartRetryPromptPartSystemPromptPartTextPartThinkingPartToolCallPartToolReturnPartUserPromptPart)ModelProfileSpec)Providerinfer_provider)ModelSettings)ToolDefinition   )ModelModelRequestParameterscheck_allow_model_requests)AssistantChatMessageV2AssistantMessageV2ContentItemAsyncClientV2ChatFinishReasonChatMessageV2SystemChatMessageV2!TextAssistantMessageV2ContentItem%ThinkingAssistantMessageV2ContentItem
ToolCallV2ToolCallV2FunctionToolChatMessageV2ToolV2ToolV2FunctionUserChatMessageV2V2ChatResponse)ApiError)OMITu   Please install `cohere` to use the Cohere model, you can use the `cohere` optional group — `pip install "pydantic-ai-slim[cohere]"`N)zc4ai-aya-expanse-32bzc4ai-aya-expanse-8bzcommand-nightlyzcommand-r-08-2024zcommand-r-plus-08-2024zcommand-r7b-12-2024stoplength	tool_callerror)COMPLETESTOP_SEQUENCE
MAX_TOKENS	TOOL_CALLERRORz$dict[ChatFinishReason, FinishReason]_FINISH_REASON_MAPc                   @  s   e Zd ZdZdS )CohereModelSettingsz)Settings used for a Cohere model request.N)__name__
__module____qualname____doc__ rG   rG   _/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/models/cohere.pyrB   Y   s    rB   F)total)initc                      s   e Zd ZU dZeddZded< eddZded< eddZde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dFd(d)ZdGd+d,ZdHd.d/ZdId1d2ZedJd6d7ZedKd;d<ZedLd@dAZ  ZS )MCohereModelzA model that uses the Cohere API.

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

    Apart from `__init__`, all methods are private or match those of the base class.
    F)reprr)   clientCohereModelName_model_namezProvider[AsyncClientV2]	_providercohereN)providerprofilesettings
model_namerR   +Literal['cohere'] | Provider[AsyncClientV2]rS   ModelProfileSpec | NonerT   ModelSettings | Nonec                  s@   || _ t|trt|}|| _|j| _t j||p|jd dS )a  Initialize an Cohere model.

        Args:
            model_name: The name of the Cohere model to use. List of model names
                available [here](https://docs.cohere.com/docs/models#command).
            provider: The provider to use for authentication and API access. Can be either the string
                'cohere' or an instance of `Provider[AsyncClientV2]`. 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.
            settings: Model-specific settings that will be used as defaults for this model.
        )rT   rS   N)	rO   
isinstancestrr    rP   rM   super__init__model_profile)selfrU   rR   rS   rT   	__class__rG   rH   r\   p   s   
zCohereModel.__init__returnrZ   c                 C  s   | j j}t| S N)rM   _client_wrapperrZ   get_base_url)r^   client_wrapperrG   rG   rH   base_url   s   zCohereModel.base_urlc                 C  s   | j S )zThe model name.)rO   r^   rG   rG   rH   rU      s   zCohereModel.model_namec                 C  s   | j jS )zThe model provider.)rP   namerg   rG   rG   rH   system   s   zCohereModel.systemmessageslist[ModelMessage]model_settingsmodel_request_parametersr%   r   c                   sD   t   | ||\}}| |tt|pi |I d H }| |}|S rb   )r&   prepare_request_chatr   rB   _process_response)r^   rj   rl   rm   responsemodel_responserG   rG   rH   request   s   
zCohereModel.requestrB   r5   c                   s   |  |}|jrtd| ||}z3| jj| j||pt|dt|dt|dt|dt|dt|dt|dtd	
I d H W S  t	yf } z|j
 }ra|d
krat|| j|jd| d }~ww )Nz&Cohere does not support built-in tools
max_tokensstop_sequencestemperaturetop_pseedpresence_penaltyfrequency_penalty)
modelrj   toolsrt   ru   rv   prx   ry   rz   i  )status_coderU   body)
_get_toolsbuiltin_toolsr	   _map_messagesrM   chatrO   r7   getr6   r~   r   rU   r   )r^   rj   rl   rm   r|   cohere_messageser~   rG   rG   rH   ro      s0   







zCohereModel._chatrq   c                 C  s   g }|j jdur,|j jD ]}|jdkr|t|jd q|jdkr+|t|jd q|j jp1g D ]}|j	rQ|j	j
rQ|j	jrQ|t|j	j
|j	j|jpMt d q2|j}d|i}t|}t|t|| j| jj
||dS )zAProcess a non-streamed response, and prepare a message to return.Ntext)contentthinking)	tool_nameargstool_call_idfinish_reason)partsr   rU   provider_namer   provider_details)messager   typeappendr   r   r   r   
tool_callsfunctionrh   	argumentsr   id_generate_tool_call_idr   rA   r   r   
_map_usagerO   rP   )r^   rq   r   r   craw_finish_reasonr   r   rG   rG   rH   rp      s:   



zCohereModel._process_responselist[ChatMessageV2]c                 C  sR  g }|D ]}t |tr|| | qt |trg }g }g }|jD ]:}t |tr0||j q"t |t	r<||j q"t |t
rJ|| | q"t |ttB rRq"t |trXq"t| q"tdd}	|sf|rg }
|ru|
td|d |r|
td|d |
|	_|r||	_||	 qt| q| || }r|dtd|d |S )	z>Just maps a `pydantic_ai.Message` to a `cohere.ChatMessageV2`.	assistant)rolez

)r   )r   r   ri   r   r   )rY   r   extend_map_user_messager   r   r   r   r   r   r   _map_tool_callr   r   r   r   r'   r.   joinr-   r   _get_instructionsinsertr,   )r^   rj   rm   r   r   textsr   r   itemmessage_paramcontentsinstructionsrG   rG   rH   r      sF   









zCohereModel._map_messageslist[ToolV2]c                   s    fdd|j  D S )Nc                   s   g | ]}  |qS rG   )_map_tool_definition).0rrg   rG   rH   
<listcomp>  s    z*CohereModel._get_tools.<locals>.<listcomp>)	tool_defsvalues)r^   rm   rG   rg   rH   r     s   zCohereModel._get_toolstr   r/   c                 C  s"   t t| ddt| j|  ddS )Nr   r   )rh   r   )r   r   r   )r/   _guard_tool_call_idr0   r   args_as_json_strr   rG   rG   rH   r     s   zCohereModel._map_tool_callfr"   r2   c                 C  s   t dt| j| j| jddS )Nr   )rh   description
parameters)r   r   )r2   r3   rh   r   parameters_json_schema)r   rG   rG   rH   r   #  s   z CohereModel._map_tool_definitionr   r   Iterable[ChatMessageV2]c                 c  s    |j D ]a}t|trtd|jdV  qt|tr,t|jtr(td|jdV  qtdt|t	r?t
dt|d| dV  qt|tra|jd u rStd| dV  qt
dt|d| dV  qt| qd S )Nri   r   userz/Cohere does not yet support multi-modal inputs.toolr   )r   r   r   )r   rY   r   r,   r   r   rZ   r4   RuntimeErrorr   r1   r   model_response_strr   r   rr   r   )clsr   partrG   rG   rH   r   .  s0   








zCohereModel._map_user_message)rU   rN   rR   rV   rS   rW   rT   rX   )ra   rZ   )ra   rN   )rj   rk   rl   rX   rm   r%   ra   r   )rj   rk   rl   rB   rm   r%   ra   r5   )rq   r5   ra   r   )rj   rk   rm   r%   ra   r   )rm   r%   ra   r   )r   r   ra   r/   )r   r"   ra   r2   )r   r   ra   r   )rC   rD   rE   rF   r   rM   __annotations__rO   rP   r\   propertyrf   rU   ri   rs   ro   rp   r   r   staticmethodr   r   classmethodr   __classcell__rG   rG   r_   rH   rK   a   s4   
 



 
-

rK   rq   r5   ra   usage.RequestUsagec                 C  s   | j }|d u rt  S i }|jd urB|jjrt|jj|d< |jjr*t|jj|d< |jjr6t|jj|d< |jjrBt|jj|d< |jrO|jjrOt|jjnd}|jr^|jjr^t|jjnd}t j|||dS )Ninput_tokensoutput_tokenssearch_unitsclassificationsr   )r   r   details)	r   RequestUsagebilled_unitsr   intr   r   r   tokens)rq   ur   request_tokensresponse_tokensrG   rG   rH   r   K  s(   
r   )rq   r5   ra   r   )Q
__future__r   _annotationscollections.abcr   dataclassesr   r   typingr   r   typing_extensionsr   pydantic_ai.exceptionsr	    r   r   _utilsr   r   r   r   rj   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   profilesr   	providersr   r    rT   r!   r|   r"   r$   r%   r&   rQ   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   cohere.core.api_errorr6   cohere.v2.clientr7   ImportError_import_errorLatestCohereModelNamesrZ   rN   rA   r   rB   rK   r   rG   rG   rG   rH   <module>   sV    DD	 j