
    gM)                    t   U d dl mZ d dlZd dl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 d dlmZmZmZ d d	lmZ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' d
dl(m)Z) d
dl*m+Z+ ddlm,Z,m-Z-m.Z.m/Z/m0Z0  ed       G d de.             Z1 ed       G d d             Z2e G d d             Z3e4e5e3f   Z6de7d<   	 ee8e   e2gee ee    f   f   Z9de7d<   	 ee8e   e2geee:e6f      f   Z;de7d<   	 e G d d e,             Z<e G d! d"e0             Z=e G d# d$e/             Z>d'd%Z?d(d&Z@y))    )annotationsN)AsyncIterator	AwaitableIterable)asynccontextmanager)	dataclassfieldreplace)datetime)chain)CallableUnioncast)	TypeAliasassert_neveroverload   )_utilsresult)
ModelMessageModelRequestModelResponseModelResponsePartRetryPromptPartSystemPromptPartTextPartToolCallPartToolReturnPartUserPromptPart)ModelSettings)ToolDefinition   )
AgentModelEitherStreamedResponseModelStreamStructuredResponseStreamTextResponseF)initc                      e Zd ZU dZdZded<   dZded<   edd       Zedd       Zedd	       Zddd
ddZ	 	 	 	 	 	 	 	 ddZ	ddZ
y)FunctionModelzA model controlled by a local function.

    Apart from `__init__`, all methods are private or match those of the base class.
    NFunctionDef | NonefunctionStreamFunctionDef | Nonestream_functionc                     y N )selfr,   s     P/var/www/openai/venv/lib/python3.12/site-packages/pydantic_ai/models/function.py__init__zFunctionModel.__init__*   s    7:    c                    y r0   r1   )r2   r.   s     r3   r4   zFunctionModel.__init__-   s    GJr5   c                    y r0   r1   r2   r,   r.   s      r3   r4   zFunctionModel.__init__0   s    ^ar5   )r.   c               >    ||t        d      || _        || _        y)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.
        Nz7Either `function` or `stream_function` must be provided)	TypeErrorr,   r.   r8   s      r3   r4   zFunctionModel.__init__3   s*      7UVV .r5   c          
     d   K   t        | j                  | j                  t        |||d             S wr0   )FunctionAgentModelr,   r.   	AgentInfo)r2   function_toolsallow_text_resultresult_toolss       r3   agent_modelzFunctionModel.agent_modelA   s4      "MM4//>K\^jlp1q
 	
s   .0c                    g }| j                   %|j                  | j                   j                         | j                  (|j                  d| j                  j                          ddj	                  |       S )Nzstream-z	function:,)r,   append__name__r.   join)r2   labelss     r3   namezFunctionModel.nameL   sj    ==$MM$--001+MMGD$8$8$A$A#BCD388F+,--r5   )r,   FunctionDefreturnNone)r.   StreamFunctionDefrJ   rK   )r,   rI   r.   rL   rJ   rK   r0   )r,   r+   r.   r-   )r>   list[ToolDefinition]r?   boolr@   rM   rJ   r#   )rJ   str)rE   
__module____qualname____doc__r,   __annotations__r.   r   r4   rA   rH   r1   r5   r3   r*   r*       s    
 $(H '04O-4: :J Ja a/ko /	
 -	
  		

 +	
 
	
.r5   r*   T)frozenc                  @    e Zd ZU dZded<   	 ded<   	 ded<   	 ded<   y	)
r=   zInformation about an agent.

    This is passed as the second to functions used within [`FunctionModel`][pydantic_ai.models.function.FunctionModel].
    rM   r>   rN   r?   r@   ModelSettings | Nonemodel_settingsN)rE   rP   rQ   rR   rS   r1   r5   r3   r=   r=   U   s1    
 )(
 1&&C((4r5   r=   c                  0    e Zd ZU dZdZded<   	 dZded<   y)DeltaToolCallzjIncremental change to a tool call.

    Used to describe a chunk when streaming structured responses.
    N
str | NonerH   	json_args)rE   rP   rQ   rR   rH   rS   r[   r1   r5   r3   rY   rY   j   s#    
 D*5 Iz 5r5   rY   r   DeltaToolCallsrI   rL   c                  b    e Zd ZU dZded<   ded<   ded<   	 	 	 	 	 	 ddZe	 	 	 	 	 	 dd	       Zy
)r<   z^Implementation of `AgentModel` for [FunctionModel][pydantic_ai.models.function.FunctionModel].r+   r,   r-   r.   r=   
agent_infoc                  K   t        | j                  |      }| j                  J d       t        j                  | j                        r| j                  ||       d {   }nBt        j                  | j                  ||       d {   }t        |t              sJ |       |}|t        t        ||g            fS 7 _7 7w)N)rW   zHFunctionModel must receive a `function` to support non-streamed requests)r
   r^   r,   inspectiscoroutinefunctionr   run_in_executor
isinstancer   _estimate_usager   )r2   messagesrW   r^   response	response_s         r3   requestzFunctionAgentModel.request   s      T__^L
}}(t*tt(&&t}}5!]]8Z@@H$44T]]HjYYIi7BB7 Hx()DEEE AYs$   AC!C")CC6CCc                 K   | j                   J d       | j                  || j                        }	 |j                          d {   }t        |t              r't        t        t           |      }t        ||       y t        t        t           |      }t        ||       y 7 b# t        $ r}t	        d      |d }~ww xY ww)NzKFunctionModel must receive a `stream_function` to support streamed requestsz-Stream function must return at least one item)r.   r^   	__anext__StopAsyncIteration
ValueErrorrc   rO   r   r   FunctionStreamTextResponser\    FunctionStreamStructuredResponse)r2   re   rW   response_streamfirstetext_streamstructured_streams           r3   request_streamz!FunctionAgentModel.request_stream   s     
   ,	YX	Y,..xI	U)3355E eS!}S1?CK,UK@@ $]>%BO T25:KLL 6! 	ULMSTT	Us;   0CB+ B)B+ AC)B+ +	C4C  CCN)re   list[ModelMessage]rW   rV   rJ   z"tuple[ModelResponse, result.Usage])re   ru   rW   rV   rJ   z%AsyncIterator[EitherStreamedResponse])rE   rP   rQ   rR   rS   rh   r   rt   r1   r5   r3   r<   r<      si    h  --F*F<PF	+F M*M<PM	.M Mr5   r<   c                      e Zd ZU dZded<   ded<    eej                  d      Zded	<    ee	d      Z
d
ed<   ddZddddZddZddZy)rm   zfImplementation of `StreamTextResponse` for [FunctionModel][pydantic_ai.models.function.FunctionModel].rZ   _nextzAsyncIterator[str]_iterF)default_factoryr(   r   
_timestampz	list[str]_bufferc                   K   | j                   -| j                  j                  | j                          d | _         y | j                  j                  | j                  j	                          d {          y 7 	wr0   )rw   r{   rD   rx   rj   r2   s    r3   rj   z$FunctionStreamTextResponse.__anext__   sR     ::!LL

+DJLLdjj&:&:&< <= <s   A,A:.A8/
A:finalc             #  l   K   | j                   E d {    | j                   j                          y 7 wr0   )r{   clear)r2   r   s     r3   getzFunctionStreamTextResponse.get   s(     << 	 s   42 4c                *    t        j                         S r0   )r   Usager}   s    r3   usagez FunctionStreamTextResponse.usage   s    ||~r5   c                    | j                   S r0   rz   r}   s    r3   	timestampz$FunctionStreamTextResponse.timestamp       r5   NrJ   rK   )r   rN   rJ   zIterable[str]rJ   result.UsagerJ   r   )rE   rP   rQ   rR   rS   r	   r   now_utcrz   listr{   rj   r   r   r   r1   r5   r3   rm   rm      sP    p eLJLt%@GY@> $) r5   rm   c                      e Zd ZU dZded<   ded<    ee      Zded<    eej                        Z
d	ed
<   ddZddddZddZddZy)rn   zlImplementation of `StreamStructuredResponse` for [FunctionModel][pydantic_ai.models.function.FunctionModel].zDeltaToolCalls | Nonerw   zAsyncIterator[DeltaToolCalls]rx   )ry   zdict[int, DeltaToolCall]_delta_tool_callsr   rz   c                  K   | j                   | j                   }d | _         n"| j                  j                          d {   }|j                         D ]  \  }}| j                  j                  |      x}r_t        j                  |j                  |j                        |_        t        j                  |j                  |j                        |_	        || j                  |<    y 7 wr0   )
rw   rx   rj   itemsr   r   r   add_optionalrH   r[   )r2   	tool_callkeynewcurrents        r3   rj   z*FunctionStreamStructuredResponse.__anext__   s     ::!

IDJ"jj2244I!)HC0044S99w9%227<<J$*$7$78I8I3==$Y!.1&&s+ * 5s   >C+ C)B)C+Fr~   c                  g }| j                   j                         D ]U  }|j                  |j                  |j	                  t        j                  |j                  |j                               W t        || j                        S )N)r   )	r   valuesrH   r[   rD   r   from_raw_argsr   rz   )r2   r   callscs       r3   r   z$FunctionStreamStructuredResponse.get   sg    )+''..0Avv!akk&=\77LM 1 Udoo>>r5   c                6    t        | j                         g      S r0   )rd   r   r}   s    r3   r   z&FunctionStreamStructuredResponse.usage   s    
|,,r5   c                    | j                   S r0   r   r}   s    r3   r   z*FunctionStreamStructuredResponse.timestamp   r   r5   Nr   )r   rN   rJ   r   r   r   )rE   rP   rQ   rR   rS   r	   dictr   r   r   rz   rj   r   r   r   r1   r5   r3   rn   rn      sN    v  ((272M/M @J@2 $) ?-r5   rn   c                   d}d}| D ]M  }t        |t              r|j                  D ]  }t        |t        t        f      r|t        |j                        z  }2t        |t              r|t        |j                               z  }_t        |t              r|t        |j                               z  }t        |        t        |t              ry|j                  D ]h  }t        |t              r|t        |j                        z  },t        |t              r"|}|dt        |j                               z   z  }^t        |       j Ct        |       P t!        j"                  ||||z         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"   )request_tokensresponse_tokenstotal_tokens)rc   r   partsr   r   _estimate_string_usagecontentr   model_response_strr   model_responser   r   r   r   args_as_json_strr   r   )re   r   r   messagepartcalls         r3   rd   rd      s:    NOg|,d%5~$FG"&<T\\&JJNn5"&<T=T=T=V&WWNo6"&<T=P=P=R&SSN & & /dH-#'=dll'KKOl3D#q+A$BWBWBY+Z'ZZO & & !+ , <<%UcfuUu r5   c                @    t        t        j                  d|             S )Nz	[\s",.:]+)lenresplit)r   s    r3   r   r     s    rxxg.//r5   )re   zIterable[ModelMessage]rJ   r   )r   rO   rJ   int)A
__future__r   _annotationsr`   r   collections.abcr   r   r   
contextlibr   dataclassesr   r	   r
   r   	itertoolsr   typingr   r   r   typing_extensionsr   r   r    r   r   re   r   r   r   r   r   r   r   r   r   r   settingsr    toolsr!   r#   r$   r%   r&   r'   r*   r=   rY   r   r   r\   rS   r   rI   rO   rL   r<   rm   rn   rd   r   r1   r5   r3   <module>r      s   2  	 > > * 1 1   ( ( ? ?    % " e e 1.E 1. 1.h $5 5 5( 	6 	6 	6 !m!34	 4 8!4#5y"A5XaboXpIpCq"qrY r :'l);Y(GW\]`bp]pWqIr(rs 9 s (M (M (MV !3  4 "'? " "J F0r5   