
    gD              	         d dl mZ d dlmZ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mZmZmZmZ d
dlmZm Z  d
dl!m"Z"m#Z# dZ$ ede%      Z&	 ee	e e   e&ge&f   e	e e   e&gee&   f   e	e&ge&f   e	e&gee&   f   f   Z'	  ejP                  d      Z)e G d deee&                Z*e G d de*e&                Z+e G d de*e&   eee&f                Z,	 	 	 	 	 	 	 	 ddZ-y)    )annotations)ABCabstractmethod)AsyncIterator	AwaitableCallable)deepcopy)	dataclassfield)datetime)GenericUnioncastN)TypeVar   )_result_utils
exceptionsmessagesmodels)	AgentDeps
RunContext)UsageUsageLimits)
ResultDataResultValidatorFunc	RunResultStreamedRunResultr   )defaultzpydantic-ai)
otel_scopec                  p    e Zd ZU dZded<   ded<   ddddZdddd	Zdddd
ZddddZe	dd       Z
y)_BaseRunResultzBase type for results.

    You should not import or use this type directly, instead use its subclasses `RunResult` and `StreamedRunResult`.
    list[_messages.ModelMessage]_all_messagesint_new_message_indexNresult_tool_return_contentc               4    |t        d      | j                  S )  Return the history of _messages.

        Args:
            result_tool_return_content: The return content of the tool call to set in the last message.
                This provides a convenient way to modify the content of the result tool call if you want to continue
                the conversation and want to set the response to the result tool call. If `None`, the last message will
                not be modified.

        Returns:
            List of messages.
        zISetting result tool return content is not supported for this result type.)NotImplementedErrorr$   selfr(   s     G/var/www/openai/venv/lib/python3.12/site-packages/pydantic_ai/result.pyall_messagesz_BaseRunResult.all_messages3   s"     &1%&qrr!!!    c               `    t         j                  j                  | j                  |            S )a:  Return all messages from [`all_messages`][pydantic_ai.result._BaseRunResult.all_messages] as JSON bytes.

        Args:
            result_tool_return_content: The return content of the tool call to set in the last message.
                This provides a convenient way to modify the content of the result tool call if you want to continue
                the conversation and want to set the response to the result tool call. If `None`, the last message will
                not be modified.

        Returns:
            JSON bytes representing the messages.
        r'   )	_messagesModelMessagesTypeAdapter	dump_jsonr/   r,   s     r.   all_messages_jsonz _BaseRunResult.all_messages_jsonD   /     11;;9ST
 	
r0   c               @    | j                  |      | j                  d S )a  Return new messages associated with this run.

        Messages from older runs are excluded.

        Args:
            result_tool_return_content: The return content of the tool call to set in the last message.
                This provides a convenient way to modify the content of the result tool call if you want to continue
                the conversation and want to set the response to the result tool call. If `None`, the last message will
                not be modified.

        Returns:
            List of new messages.
        r'   N)r/   r&   r,   s     r.   new_messagesz_BaseRunResult.new_messagesT   s(       <V WX\XoXoXqrrr0   c               `    t         j                  j                  | j                  |            S )a>  Return new messages from [`new_messages`][pydantic_ai.result._BaseRunResult.new_messages] as JSON bytes.

        Args:
            result_tool_return_content: The return content of the tool call to set in the last message.
                This provides a convenient way to modify the content of the result tool call if you want to continue
                the conversation and want to set the response to the result tool call. If `None`, the last message will
                not be modified.

        Returns:
            JSON bytes representing the new messages.
        r'   )r2   r3   r4   r8   r,   s     r.   new_messages_jsonz _BaseRunResult.new_messages_jsond   r6   r0   c                    t               N)r+   r-   s    r.   usagez_BaseRunResult.usaget   s    !##r0   r(   
str | Nonereturnr#   )r(   r@   rA   bytesrA   r   )__name__
__module____qualname____doc____annotations__r/   r5   r8   r:   r   r>    r0   r.   r"   r"   )   sV    
 0/GK "" MQ 
  HL s  MQ 
  $ $r0   r"   c                  P    e Zd ZU dZded<   	 ded<   ded<   ddZd	d
ddZddZy	)r   zResult of a non-streamed run.r   datar@   _result_tool_namer   _usagec                    | j                   S )z"Return the usage of the whole run.)rM   r=   s    r.   r>   zRunResult.usage   s    {{r0   Nr'   c               @    || j                  |      S | j                  S )r*   )_set_result_tool_returnr$   r,   s     r.   r/   zRunResult.all_messages   s(     &1//0JKK%%%r0   c                6   | j                   st        d      t        | j                        }|d   }|j                  D ]A  }t        |t        j                        s|j                  | j                   k(  s8||_	        |c S  t        d| j                   d      )zSet return content for the result tool.

        Useful if you want to continue the conversation and want to set the response to the result tool call.
        zDCannot set result tool return content when the return type is `str`.z"No tool call found with tool name .)rL   
ValueErrorr	   r$   parts
isinstancer2   ToolReturnPart	tool_namecontentLookupError)r-   return_contentr   last_messageparts        r.   rP   z!RunResult._set_result_tool_return   s    
 %%cddD../| &&D$	 8 89dnnPTPfPf>f- ' >t?U?U>XXYZ[[r0   rC   r?   )r[   strrA   r#   )rD   rE   rF   rG   rH   r>   r/   rP   rI   r0   r.   r   r   y   s0    '
2!!M HL &"\r0   r   c                      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ed<    edd      Zded<   	 ddd#dZdddd$dZdd	 	 	 d%dZ	d&dZ
ed'd       Zd(dZd)dZdd	 	 	 	 	 d*dZd+d Zd,d!Zy")-r   zFResult of a streamed run that returns structured data via a tool call.UsageLimits | None_usage_limitszmodels.EitherStreamedResponse_stream_responsez'_result.ResultSchema[ResultData] | None_result_schemazRunContext[AgentDeps]_run_ctxz4list[_result.ResultValidator[AgentDeps, ResultData]]_result_validatorsr@   rL   zCallable[[], Awaitable[None]]_on_completeF)r   initboolis_completeg?debounce_byc              @  K   t        | j                  t        j                        r/| j	                  |      2 3 d{   }t        t        |       | j                  |      2 3 d{   \  }}| j                  ||        d{    ,7 V6 y7 +7 6 yw)am  Stream the response as an async iterable.

        The pydantic validator for structured data will be called in
        [partial mode](https://docs.pydantic.dev/dev/concepts/experimental/#partial-validation)
        on each iteration.

        Args:
            debounce_by: by how much (if at all) to debounce/group the response chunks by. `None` means no debouncing.
                Debouncing is particularly important for long structured responses to reduce the overhead of
                performing validation as each token is received.

        Returns:
            An async iterable of the response data.
        rj   Nallow_partial)	rV   rb   r   StreamTextResponsestream_textr   r   stream_structuredvalidate_structured_result)r-   rk   textstructured_messageis_lasts        r.   streamzStreamedRunResult.stream   s      d++V-F-FG"..;.G -d:t,,595K5KXc5K5d k1(' ;;<Nbi^i;jjj	-Gkj 6es\   7BBBB'B(B,B-B0BBBBBBBB)deltark   c              x  K   t        | j                  | j                  | j                        }t        j                  d      5 }t        | j                  t        j                        rt        j                  d      |rWt        j                  ||      4 d{   }|2 3 d{   }dj                  | j                  j                                6g }d}	t        j                  ||      4 d{   }|2 3 d{   }d}
| j                  j                         D ]  }|j                  |       d}
 |
s@| j!                  dj                  |             d{   }	|	 n7 7 6 ddd      d{  7   n# 1 d{  7  sw Y   nxY wdj                  | j                  j                  d            }|r| n7 7 7 m6 ddd      d{  7   n# 1 d{  7  sw Y   nxY wd}
| j                  j                  d      D ]  }|j                  |       d}
 |
r.| j!                  dj                  |             d{  7  }	|	 |j#                  d|	       | j%                  t&        j(                  j+                  |	             d{  7   ddd       y# 1 sw Y   yxY ww)	a*  Stream the text result as an async iterable.

        !!! note
            This method will fail if the response is structured,
            e.g. if [`is_structured`][pydantic_ai.result.StreamedRunResult.is_structured] returns `True`.

        !!! note
            Result validators will NOT be called on the text result if `delta=True`.

        Args:
            delta: if `True`, yield each chunk of text as it is received, if `False` (default), yield the full text
                up to the current point.
            debounce_by: by how much (if at all) to debounce/group the response chunks by. `None` means no debouncing.
                Debouncing is particularly important for long structured responses to reduce the overhead of
                performing validation as each token is received.
        zresponse stream textz2stream_text() can only be used with text responsesN TfinalFcombined_text)#_get_usage_checking_stream_responserb   ra   r>   _logfirespanrV   r   StreamStructuredResponser   	UserErrorr   group_by_temporaljoingetappend_validate_text_resultset_attribute_marked_completedr2   ModelResponse	from_text)r-   rw   rk   usage_checking_streamlf_span
group_iter_final_deltachunkscombinednewchunks               r.   rp   zStreamedRunResult.stream_text   sF    " !D!!4#5#5tzz!
 ]]12g$//1P1PQ **+_``!334I;WW[e#- Ca ggd&;&;&?&?&ABB %'!334I;WW[e#- +a#%)%:%:%>%>%@E"MM%0"&C &A -1-G-GPV-X'XH"*N' XC: XWWWW !ggd&;&;&?&?d&?&KL%% X+ (Y $. XWWWW !2266T6BEMM%(C C %)%?%?%PPPH"N%%ox@,,Y-D-D-N-Nx-XYYYC 322s  AJ:AJ.E)J.F  E-$E+
%E-(.F J.4G5J.8G!;G?G

 G7G!;#G!G

G!)J.+E--F .J.9E<:J. F	F	F	;J.
GG!G!J.GJ.!G3	'G*(G3	/A"J.IAJ.J" J.%	J:.J73J:c                K   t        | j                  | j                  | j                        }t        j                  d      5 }t        | j                  t        j                        rt        j                  d      | j                  j                         }|j                  D ]6  }t        |t        j                        s|j                         s/|df  n t!        j"                  ||      4 d{   }|2 3 d{   }| j                  j                         }|j                  D ]6  }t        |t        j                        s|j                         s/|df  g i7 o7 f6 ddd      d{  7   n# 1 d{  7  sw Y   nxY w| j                  j                  d      }|df |j%                  d|       | j'                  |       d{  7   	 ddd       y# 1 sw Y   yxY ww)a  Stream the response as an async iterable of Structured LLM Messages.

        !!! note
            This method will fail if the response is text,
            e.g. if [`is_structured`][pydantic_ai.result.StreamedRunResult.is_structured] returns `False`.

        Args:
            debounce_by: by how much (if at all) to debounce/group the response chunks by. `None` means no debouncing.
                Debouncing is particularly important for long structured responses to reduce the overhead of
                performing validation as each token is received.

        Returns:
            An async iterable of the structured response message and whether that is the last message.
        zresponse stream structuredz>stream_structured() can only be used with structured responsesFNTrz   structured_response)r}   rb   ra   r>   r~   r   rV   r   ro   r   r   r   rU   r2   ToolCallParthas_contentr   r   r   r   )r-   rk   r   r   msgitemr   r   s           r.   rq   z#StreamedRunResult.stream_structured
  s    " !D!!4#5#5tzz!
 ]]78G$//1J1JK **+kll ++//1IID!$	(>(>?DDTDTDV!5j( & "334I;WW[e#- &a"33779$'IID)$	0F0FGDL\L\L^&)5j 0 % %. X&: XWWWW ++//d/;4i%%&;SA,,S111) 988s   AG7A=G+G+$G+6E&7G+:E==E*E(
E*AE=
E=E=&G+(E**E=+G+6E97G+=F	FF	AG+GG+"	G7+G40G7c                ~  K   t        | j                  | j                  | j                        }|2 3 d{   }
7 6 t	        | j                  t
        j                        rdj                  | j                  j                  d            }| j                  |       d{  7  }| j                  t        j                  j                  |             d{  7   t        t        |      S | j                  j                  d      }| j                  |       d{  7   | j!                  |       d{  7  S w)z2Stream the whole response, validate and return it.Nry   Trz   )r}   rb   ra   r>   rV   r   ro   r   r   r   r   r2   r   r   r   r   rr   )r-   r   r   rs   messages        r.   get_datazStreamedRunResult.get_data5  s     C!!4#5#5tzz!
 - 	!	, d++V-F-FG774004444@AD33D999D(()@)@)J)J4)PQQQ
D))++//d/;G((11188AAAAsQ   .D=<:<D=<A$D= B#!6D=CAD=D D=7D:8D=c                J    t        | j                  t        j                        S )zQReturn whether the stream response contains structured data (as opposed to text).)rV   rb   r   r   r=   s    r.   is_structuredzStreamedRunResult.is_structuredH  s     $//1P1PQQr0   c                d    | j                   j                  | j                  j                         z   S )zReturn the usage of the whole run.

        !!! note
            This won't return the full usage until the stream is finished.
        )rd   r>   rb   r=   s    r.   r>   zStreamedRunResult.usageM  s(     }}""T%:%:%@%@%BBBr0   c                6    | j                   j                         S )z"Get the timestamp of the response.)rb   	timestampr=   s    r.   r   zStreamedRunResult.timestampU  s    $$..00r0   rm   c                 K   | j                   J d       | j                  J d       | j                   j                  |j                  | j                        }|0t	        j
                  d| j                   j                                |\  }}|j                  ||d      }| j                  D ]'  }|j                  ||| j                         d{   }) |S 7 w)z%Validate a structured result message.Nz&Expected _result_schema to not be Nonez)Expected _result_tool_name to not be Nonez&Invalid message, unable to find tool: F)rn   wrap_validation_errors)
rc   rL   find_named_toolrU   r   UnexpectedModelBehavior
tool_namesvalidatere   rd   )r-   r   rn   matchcallresult_toolresult_data	validators           r.   rr   z,StreamedRunResult.validate_structured_resultY  s      "".X0XX.%%1^3^^1##33GMM4CYCYZ=4489L9L9W9W9Y8Z[  "k!**4}ej*k00I ) 2 2;dmm TTK 1 Us   CCC	Cc                ~   K   | j                   D ]'  }|j                  |d | j                         d {   }) |S 7 wr<   )re   r   rd   )r-   rs   r   s      r.   r   z'StreamedRunResult._validate_text_resultl  sD     00I"++ D 1 s   0=;	=c                   K   d| _         | j                  j                  |       | j                          d {    y 7 w)NT)ri   r$   r   rf   )r-   r   s     r.   r   z#StreamedRunResult._marked_completedu  s4     !!'*!!!s   6A >A N)rk   float | NonerA   AsyncIterator[ResultData])rw   rh   rk   r   rA   zAsyncIterator[str])rk   r   rA   z3AsyncIterator[tuple[_messages.ModelResponse, bool]])rA   r   )rA   rh   rC   )rA   r   )r   _messages.ModelResponsern   rh   rA   r   )rs   r^   rA   r^   )r   r   rA   None)rD   rE   rF   rG   rH   r   ri   rv   rp   rq   r   propertyr   r>   r   rr   r   r   rI   r0   r.   r   r      s    P%%33;;##LL!!//e%8K8 ;> k, 27TW 6Zr .1)2*)2	<)2VB& R RC1
 JO.BF	&"r0   r   c                L     j                         r fd} |       S  S )Nc                b   K   2 3 d {   } j                                 |  %7  6 y wr<   )check_tokens)r   	get_usagelimitsstream_responses    r.   _usage_checking_iteratorzE_get_usage_checking_stream_response.<locals>._usage_checking_iterator  s.     - d##IK0
os   /-+-/-/)has_token_limits)r   r   r   r   s   ``` r.   r}   r}   {  s,     f557	
 ())r0   )r   r   r   r`   r   zCallable[[], Usage]rA   r   ).
__future__r   _annotationsabcr   r   collections.abcr   r   r   copyr	   dataclassesr
   r   r   typingr   r   r   logfire_apityping_extensionsr   ry   r   r   r   r   r2   r   toolsr   r   r>   r   r   __all__r^   r   r   Logfirer~   r"   r   r   r}   rI   r0   r.   <module>r      sf   2 # > >  (  ' '  % H H ( %
O \3/
 1j#Z0*<=j#Z0)J2GGHj\:%&j\9Z0013  ;-8 L$S'*- L$ L$^ *\z* *\ *\Z P"z2GIz<Q4R P" P"f.8JWjr0   