o
    i?                     @  sj  U d dl mZ d dlZd dlZd dlmZmZ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 d dlmZ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"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/m0Z0 d
dl1m2Z2m3Z3 d
dl4m5Z5 d
dl6m7Z7 ddlm8Z8m9Z9m:Z: eddG dd de8Z;edddG dd dZ<eG dd dZ=eddG dd  d Z>e?e@e=f ZAd!eBd"< 	 e?e@e>f ZCd!eBd#< 	 e?e@e"e#B f ZDd!eBd$< eeEe% e<ge'ee' B f ZFd!eBd%< 	 eeEe% e<geeGeAB eCB eDB  f ZHd!eBd&< 	 eG d'd( d(e:ZId5d-d.ZJd6d2d3ZKeLd4ZMdS )7    )annotationsN)AsyncIterator	AwaitableCallableIterableSequence)asynccontextmanager)KW_ONLY	dataclassfield)datetime)chain)Any	TypeAlias)assert_neveroverload   )_utilsusage)
RunContext)PeekableAsyncStream)BinaryContentBuiltinToolCallPartBuiltinToolReturnPartFilePartModelMessageModelRequestModelResponseModelResponseStreamEventRetryPromptPartSystemPromptPartTextPartThinkingPartToolCallPartToolReturnPartUserContentUserPromptPart)ModelProfileModelProfileSpec)ModelSettings)ToolDefinition   )ModelModelRequestParametersStreamedResponseF)initc                      s   e Zd ZU dZded< ded< eddZded	< eddd
Zded< eddddd/ddZ	eddddd0ddZ	eddddd1ddZ		d2dddddd3 fddZ	d4d$d%Z
e	d2d5d)d*Zed6d+d,Zed6d-d.Z  ZS )7FunctionModelzA model controlled by a local function.

    Apart from `__init__`, all methods are private or match those of the base class.
    FunctionDef | NonefunctionStreamFunctionDef | Nonestream_functionF)reprstr_model_name)defaultr5   _systemN)
model_nameprofilesettingsFunctionDefr:   
str | Noner;   ModelProfileSpec | Noner<   ModelSettings | NonereturnNonec                C     d S N )selfr2   r:   r;   r<   rE   rE   a/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/models/function.py__init__6      zFunctionModel.__init__StreamFunctionDefc                C  rC   rD   rE   )rF   r4   r:   r;   r<   rE   rE   rG   rH   @   rI   c                C  rC   rD   rE   )rF   r2   r4   r:   r;   r<   rE   rE   rG   rH   J   s   	)r4   r:   r;   r<   c                  s   |du r|du rt d|| _|| _| jdur| jjnd}| jdur&| jjnd}|p1d| d| | _|du r=tddd}t j||d dS )	a  Initialize a `FunctionModel`.

        Either `function` or `stream_function` must be provided, providing both is allowed.

        Args:
            function: The function to call for non-streamed requests.
            stream_function: The function to call for streamed requests.
            model_name: The name of the model. If not provided, a name is generated from the function names.
            profile: The model profile to use.
            settings: Model-specific settings that will be used as defaults for this model.
        Nz7Either `function` or `stream_function` must be provided z	function::T)supports_json_schema_outputsupports_json_object_output)r<   r;   )	TypeErrorr2   r4   __name__r7   r'   superrH   )rF   r2   r4   r:   r;   r<   function_namestream_function_name	__class__rE   rG   rH   U   s   messageslist[ModelMessage]model_settingsmodel_request_parametersr-   r   c              
     s   |  ||\}}t|j|j|j||| ||d}| jd us#J dt| jr3| ||I d H }nt	
| j||I d H }t|tsGJ ||}| j|_|j s[tt||g|_|S )Nfunction_toolsallow_text_outputoutput_toolsrX   rY   instructionszHFunctionModel must receive a `function` to support non-streamed requests)prepare_request	AgentInfor[   r\   r]   _get_instructionsr2   inspectiscoroutinefunctionr   run_in_executor
isinstancer   r7   r:   r   
has_values_estimate_usager   )rF   rV   rX   rY   
agent_inforesponse	response_rE   rE   rG   request{   s.   
	
zFunctionModel.requestrun_contextRunContext[Any] | NoneAsyncIterator[StreamedResponse]c              
   C s   |  ||\}}t|j|j|j||| ||d}| jd us#J dt| ||}| I d H }t	|t
jr<tdt|| j|dV  d S )NrZ   zKFunctionModel must receive a `stream_function` to support streamed requestsz-Stream function must return at least one item)rY   r7   _iter)r_   r`   r[   r\   r]   ra   r4   r   peekre   r   Unset
ValueErrorFunctionStreamedResponser7   )rF   rV   rX   rY   rl   rh   response_streamfirstrE   rE   rG   request_stream   s2   
	zFunctionModel.request_streamc                 C     | j S )zThe model name.r7   rF   rE   rE   rG   r:         zFunctionModel.model_namec                 C  rw   )zThe system / model provider.)r9   ry   rE   rE   rG   system   rz   zFunctionModel.system)
r2   r=   r:   r>   r;   r?   r<   r@   rA   rB   )
r4   rJ   r:   r>   r;   r?   r<   r@   rA   rB   )r2   r=   r4   rJ   r:   r>   r;   r?   r<   r@   rA   rB   rD   )
r2   r1   r4   r3   r:   r>   r;   r?   r<   r@   )rV   rW   rX   r@   rY   r-   rA   r   )
rV   rW   rX   r@   rY   r-   rl   rm   rA   rn   rA   r6   )rP   
__module____qualname____doc____annotations__r   r7   r9   r   rH   rk   r   rv   propertyr:   r{   __classcell__rE   rE   rT   rG   r0   )   sH   
 		
&!$r0   T)frozenkw_onlyc                   @  sL   e Zd ZU dZded< 	 ded< 	 ded< 	 ded< 	 d	ed
< 	 ded< dS )r`   zInformation about an agent.

    This is passed as the second to functions used within [`FunctionModel`][pydantic_ai.models.function.FunctionModel].
    zlist[ToolDefinition]r[   boolr\   r]   r@   rX   r-   rY   r>   r^   N)rP   r}   r~   r   r   rE   rE   rE   rG   r`      s   
 r`   c                   @  sB   e Zd ZU dZdZded< 	 dZded< 	 ded< dZded< dS )	DeltaToolCallzjIncremental change to a tool call.

    Used to describe a chunk when streaming structured responses.
    Nr>   name	json_argsr	   _tool_call_id)rP   r}   r~   r   r   r   r   r   rE   rE   rE   rG   r      s   
 r   )r   c                   @  s,   e Zd ZU dZdZded< 	 dZded< dS )DeltaThinkingPartzlIncremental change to a thinking part.

    Used to describe a chunk when streaming thinking responses.
    Nr>   content	signature)rP   r}   r~   r   r   r   r   rE   rE   rE   rG   r      s   
 r   r   DeltaToolCallsDeltaThinkingCallsBuiltinToolCallsReturnsr=   rJ   c                   @  sr   e Zd ZU dZded< ded< eejdZded< d	d
 Z	dddZ
edddZedddZedddZdS )rs   zdImplementation of `StreamedResponse` for [FunctionModel][pydantic_ai.models.function.FunctionModel].r6   r7   zRAsyncIterator[str | DeltaToolCalls | DeltaThinkingCalls | BuiltinToolCallsReturns]ro   )default_factoryr   
_timestampc                 C  s   |  j tg 7  _ d S rD   )_usagerg   ry   rE   rE   rG   __post_init__$  s   z&FunctionStreamedResponse.__post_init__rA   'AsyncIterator[ModelResponseStreamEvent]c                 C s  | j 2 z3 d H W }t|tr.t|}|  jtj|d7  _| jjd|d}|d ur-|V  qt|t	r|r|
 D ]\}}t|trh|jrUt|j}|  jtj|d7  _| jj||j|j|jrbdnd dV  q9t|tr|jrt|j}|  jtj|d7  _| jj||j|j|jd}|d ur|V  q9t|tr|  }rt|}|  jtj|d7  _| jj||dV  q9t|tr|  }rt|}|  jtj|d7  _| jj||dV  q9t| q9q6 d S )N)output_tokensr   )vendor_part_idr   r2   )r   r   r   provider_name)r   	tool_nameargsr   )r   part)ro   re   r6   _estimate_string_tokensr   r   RequestUsage_parts_managerhandle_text_deltadictitemsr   r   handle_thinking_deltar   r   r   handle_tool_call_deltar   r   r   args_as_json_strhandle_partr   model_response_strr   )rF   itemresponse_tokensmaybe_event	dtc_indexdeltar   rE   rE   rG   _get_event_iterator'  s^   








z,FunctionStreamedResponse._get_event_iteratorc                 C  rw   )z#Get the model name of the response.rx   ry   rE   rE   rG   r:   T  rz   z#FunctionStreamedResponse.model_namerB   c                 C  s   dS )zGet the provider name.NrE   ry   rE   rE   rG   r   Y  s   z&FunctionStreamedResponse.provider_namec                 C  rw   )z"Get the timestamp of the response.)r   ry   rE   rE   rG   	timestamp^  rz   z"FunctionStreamedResponse.timestampN)rA   r   r|   )rA   rB   )rA   r   )rP   r}   r~   r   r   r   r   now_utcr   r   r   r   r:   r   r   rE   rE   rE   rG   rs     s   
 
-rs   rV   Iterable[ModelMessage]rA   usage.RequestUsagec                 C  sj  d}d}| D ]}t |trC|jD ]1}t |ttB r!|t|j7 }qt |tr/|t| 7 }qt |t	r=|t|
 7 }qt| qqt |tr|jD ]\}t |trZ|t|j7 }qKt |trg|t|j7 }qKt |trw|dt|  7 }qKt |tr|dt|  7 }qKt |tr|t| 7 }qKt |tr|t|jg7 }qKt| qKqt| qtj||dS )zVery rough guesstimate of the token usage associated with a series of messages.

    This is designed to be used solely to give plausible numbers for testing!
    2   r   r+   )input_tokensr   )re   r   partsr    r&   r   r   r$   r   r   model_responser   r   r!   r"   r#   r   r   r   r   r   r   )rV   request_tokensr   messager   rE   rE   rG   rg   d  sD   





	








rg   r   str | Sequence[UserContent]intc                 C  sp   | sdS t | trtt|  S d}| D ]}t |tr)|tt| 7 }qt |tr5|t|j7 }q|S )Nr   )re   r6   len_TOKEN_SPLIT_REsplitstripr   data)r   tokensr   rE   rE   rG   r     s   


r   z	[\s",.:]+)rV   r   rA   r   )r   r   rA   r   )N
__future__r   _annotationsrb   recollections.abcr   r   r   r   r   
contextlibr   dataclassesr	   r
   r   r   	itertoolsr   typingr   r   typing_extensionsr   r   rK   r   r   _run_contextr   r   rV   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   profilesr'   r(   r<   r)   toolsr*   r,   r-   r.   r0   r`   r   r   r   r   r   r   r   r   listr=   r6   rJ   rs   rg   r   compiler   rE   rE   rE   rG   <module>   sV    H 
#$	
G
+