o
    iB                     @  s  U d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dl	m
Z
mZmZmZmZmZ d dl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 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% d d
l&m'Z' d dl(m)Z)m*Z* d dl+m,Z, d dl-m.Z.m/Z/m0Z0 d dl1m2Z2 d dl3m4Z4 d dl5m6Z6 ddl7m8Z8 e6Z6erd dl9m:Z:m;Z; d dl<m=Z=m>Z> ddl7m?Z@ ddlAmBZB e.dZCe"dZDdd d!ZEdd%d&ZFdd*d+ZGdd.d/ZHe"d0ZIeG d1d2 d2eeI ZJeJeI dB ZKd3eLd4< 	 G d5d6 d6ZMeM ZNdd:d;ZOeddAdBZPddEdFZQddIdJZRddLdMZSddQdRZTddSdTZUG dUdV dVeeI ZVddYdZZWdd\d]ZXe*eZYdd_d`ZZedaeeI f Z[e%ddddeZ\e%ddgdeZ\ddhdeZ\ddndoZ]ddsdtZ^ddvdwZ_ddydzZ`dd|d}ZadddZbdd ZcdS )    )annotationsN)AsyncIterableAsyncIterator	AwaitableCallableIterableIterator)asynccontextmanagersuppress)	dataclassfieldsis_dataclass)datetimetimezone)partial)GenericAlias)	TYPE_CHECKINGAnyGeneric	TypeAlias	TypeGuardTypeVarget_args
get_originoverload)run_sync)	BaseModelTypeAdapter)JsonSchemaValue)	ParamSpecTypeIsis_typeddict)typing_objects)is_union_origin)AbstractSpan   )
exceptions)AgentRunAgentRunResult)GraphRunGraphRunResult)messages)ObjectJsonSchema_P_RfuncCallable[_P, _R]args_P.argskwargs	_P.kwargsreturnc                   s&   t | g|R i |}t|I d H S N)r   r   )r/   r1   r3   wrapped_func r8   X/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/_utils.pyrun_in_executor-   s   r:   type_r   boolc                 C  s<   t | tot | t ot| tpt| pt| pt| ddS )zCheck if something is a pydantic model, dataclass or typedict.

    These should all generate a JSON Schema with `{"type": "object"}` and therefore be usable directly as
    function parameters.
    __is_model_like__F)
isinstancetyper   
issubclassr   r   r!   getattr)r;   r8   r8   r9   is_model_like2   s   



rB   schemar   r,   c                 C  s   ddl m} | ddkr| S | d }r=d}||r;| di |t|d   }r;|ddkr;t|s;|S | S |d)	Nr%   )	UserErrorr?   object$ref#/$defs/$defszSchema must be an object)r&   rD   get
startswithlen_contains_ref)rC   rD   refprefixresolvedr8   r8   r9   check_object_json_schemaD   s    rP   obj'JsonSchemaValue | list[JsonSchemaValue]c                 C  s6   t | trd| v rdS |  }n| }tdd |D S )z6Recursively check if an object contains any $ref keys.rF   Tc                 s  s&    | ]}t |ttB ot|V  qd S r6   )r>   dictlistrL   ).0itemr8   r8   r9   	<genexpr>a   s   $ z _contains_ref.<locals>.<genexpr>)r>   rS   valuesany)rQ   itemsr8   r8   r9   rL   X   s   

rL   Tc                   @  s   e Zd ZU dZded< dS )Somez(Analogous to Rust's `Option::Some` type.r[   valueN)__name__
__module____qualname____doc____annotations__r8   r8   r8   r9   r\   g   s   
 r\   r   Optionc                   @  s   e Zd ZdZdS )Unsetz(A singleton to represent an unset value.N)r^   r_   r`   ra   r8   r8   r8   r9   rd   r   s    rd   
t_or_unset	T | UnsetTypeGuard[T]c                 C  s   | t uS r6   )UNSET)re   r8   r8   r9   is_set{   s   ri   	aiterableAsyncIterable[T]soft_max_intervalfloat | None%AsyncIterator[AsyncIterable[list[T]]]c                  s   du rd	 fdd}| V  dS dd	 fdd}z+| V  W rG d ttj I dH  W d   dS 1 s@w   Y  dS dS rj d ttj I dH  W d   w 1 sew   Y  w )
a  Group items from an async iterable into lists based on time interval between them.

    Effectively, this debounces the iterator.

    This returns a context manager usable as an iterator so any pending tasks can be cancelled if an error occurs
    during iteration.

    Usage:

    ```python
    async with group_by_temporal(yield_groups(), 0.1) as groups_iter:
        async for groups in groups_iter:
            print(groups)
    ```

    Args:
        aiterable: The async iterable to group.
        soft_max_interval: Maximum interval over which to group items, this should avoid a trickle of items causing
            a group to never be yielded. It's a soft max in the sense that once we're over this time, we yield items
            as soon as `anext(aiter)` returns. If `None`, no grouping/debouncing is performed

    Returns:
        A context manager usable as an async iterable of lists of items produced by the input async iterable.
    Nr5   AsyncIterator[list[T]]c                   s"    2 z
3 d H W } | gV  q6 d S r6   r8   )rV   )rj   r8   r9   async_iter_groups_noop   s   
z1group_by_temporal.<locals>.async_iter_groups_noopc                   s   d ur	dksJ dg } t  }t }	 |d u r}nt  |  }d u r2tt|tjf|dI d H \}}|rkz|  }W n t	yZ   | rU| V  d Y d S w | 
| d |d u rjt  }n	| rt| V  g } d }q)Nr   z+soft_max_interval must be a positive numberT)timeout)time	monotonicaiterasynciocreate_taskanextwaitpopresultStopAsyncIterationappend)buffergroup_start_time	aiterator	wait_timedone_rV   rj   rl   taskr8   r9   async_iter_groups   s>   
z,group_by_temporal.<locals>.async_iter_groupsz#Cancelling due to error in iterator)r5   ro   )cancelr
   ru   CancelledError)rj   rl   rp   r   r8   r   r9   group_by_temporal   s&   1

"
r   iteratorIterator[T]c              
   C  s,   zt | W S  ty } zt |d}~ww )zGet the next item from a sync iterator, raising `StopAsyncIteration` if it's exhausted.

    Useful when iterating over a sync iterator in an async context.
    N)nextStopIterationr{   )r   er8   r8   r9   
sync_anext   s   
r   
async_iterAsyncIterator[T]c                 c  s6    t  }	 z
|t| V  W n
 ty   Y d S w qr6   )get_event_looprun_until_completerw   r{   )r   loopr8   r8   r9   sync_async_iterator   s   r   r   c                   C  s   t jtjdS )N)tz)r   nowr   utcr8   r8   r8   r9   now_utc   s   r   t_messages.ToolCallPart | _messages.ToolReturnPart | _messages.RetryPromptPart | _messages.BuiltinToolCallPart | _messages.BuiltinToolReturnPartstrc                 C  s   | j pt S )zTType guard that either returns the tool call id or generates a new one if it's None.)tool_call_idgenerate_tool_call_id)r   r8   r8   r9   guard_tool_call_id   s   r   c                   C  s   dt  j S )zJGenerate a tool call id.

    Ensure that the tool call id is unique.
    pyd_ai_)uuiduuid4hexr8   r8   r8   r9   r     s   r   c                   @  sB   e Zd ZdZdddZddd	ZdddZdddZdddZdS )PeekableAsyncStreamzWraps an async iterable of type T and allows peeking at the *next* item without consuming it.

    We only buffer one item at a time (the next item). Once that item is yielded, it is discarded.
    This is a single-pass stream.
    sourcerk   c                 C  s   || _ d | _t| _d| _d S )NF)_source_source_iterrh   _buffer
_exhausted)selfr   r8   r8   r9   __init__  s   
zPeekableAsyncStream.__init__r5   rf   c                   sl   | j rtS t| jts| jS | jdu rt| j| _zt| jI dH | _W | jS  t	y5   d| _ t Y S w )z|Returns the next item that would be yielded without consuming it.

        Returns None if the stream is exhausted.
        NT)
r   rh   r>   r   rd   r   rt   r   rw   r{   r   r8   r8   r9   peek  s   
zPeekableAsyncStream.peekr<   c                   s   t |  I dH tS )z9Returns True if the stream is exhausted, False otherwise.N)r>   r   rd   r   r8   r8   r9   is_exhausted2  s   z PeekableAsyncStream.is_exhaustedr   c                 C  s   | S r6   r8   r   r8   r8   r9   	__aiter__6  s   zPeekableAsyncStream.__aiter__r[   c                   sh   | j rtt| jts| j}t| _|S | jdu rt| j| _z	t	| jI dH W S  ty3   d| _  w )zYields the buffered item if present, otherwise fetches the next item from the underlying source.

        Raises StopAsyncIteration if the stream is exhausted.
        NT)
r   r{   r>   r   rd   rh   r   rt   r   rw   )r   rV   r8   r8   r9   	__anext__:  s   
zPeekableAsyncStream.__anext__N)r   rk   )r5   rf   )r5   r<   )r5   r   )r5   r[   )	r^   r_   r`   ra   r   r   r   r   r   r8   r8   r8   r9   r     s    



r   x5AgentRun | AgentRunResult | GraphRun | GraphRunResultc                 C  s   | j ddpdS )NF)required )_traceparentr   r8   r8   r9   get_traceparentS  s   r   r   c                   s0    fddt  D } jj dd| dS )z6Exclude fields with values equal to the field default.c                 3  s@    | ]}|j rt |j|jkr|j d t |jV  qdS )=N)reprrA   namedefault)rU   fr   r8   r9   rW   Y  s    .z/dataclasses_no_defaults_repr.<locals>.<genexpr>(, ))r   	__class__r`   join)r   kv_pairsr8   r   r9   dataclasses_no_defaults_reprW  s   
r   int | floatc                 C  s
   t | S r6   )_datetime_tavalidate_pythonr   r8   r8   r9   number_to_datetimeb  s   
r   .AwaitableCallable[T]TypeIs[AwaitableCallable[T]]c                 C     d S r6   r8   rQ   r8   r8   r9   is_async_callablei     r   TypeIs[AwaitableCallable[Any]]c                 C  r   r6   r8   r   r8   r8   r9   r   m  r   c                 C  s<   t | tjr| j} t | tjst| pt| ot| jS )zCorrectly check if a callable is async.

    This function was copied from Starlette:
    https://github.com/encode/starlette/blob/78da9b9e218ab289117df7d62aee200ed4c59617/starlette/_utils.py#L36-L40
    )r>   	functoolsr   r/   inspectiscoroutinefunctioncallable__call__r   r8   r8   r9   r   q  s   sdict[str, Any]name_mappingdict[str, str]Nonec                 C  s   d| v r | d }| dr |dd }|||}d| | d< d| v r4| d }| D ]}t|| q,d| v rHt| d trH| d }t|| d| v rZ| d }|D ]}	t|	| qRdD ]}
|
| v rp| |
 }|D ]}	t|	| qhq\dS )	z@Update $refs in a schema to use the new names from name_mapping.rF   rG      N
propertiesrZ   prefixItems)anyOfoneOf)rJ   rI   rX   _update_mapped_json_schema_refsr>   rS   )r   r   rM   original_namenew_namepropsproprZ   prefix_itemsrV   
union_typeunion_itemsr8   r8   r9   r   }  s0   

r   schemaslist[dict[str, Any]]6tuple[list[dict[str, Any]], dict[str, dict[str, Any]]]c                 C  s   i }g }| D ]t}d|vr| | q| }|dd}i }| D ]M\}}||vr3|||< |||< q"||| kro|}|d }	rI|	 d| }d}
|}| d|
 }||v rg|
d7 }
| d|
 }||v sX|||< |||< q"t|| | | q||fS )a  Merges the `$defs` from different JSON schemas into a single deduplicated `$defs`, handling name collisions of `$defs` that are not the same, and rewrites `$ref`s to point to the new `$defs`.

    Returns a tuple of the rewritten schemas and a dictionary of the new `$defs`.
    rH   Ntitler   r%   )r|   copyry   rZ   rI   r   )r   all_defsrewritten_schemasrC   defsschema_name_mappingr   
def_schemar   r   ioriginal_new_namer8   r8   r9   merge_json_schema_defs  s<   


r   _kwargsc                 C  s0   | rd dd |  D }td| dS )zValidate that no unknown kwargs remain after processing.

    Args:
        _kwargs: Dictionary of remaining kwargs after specific ones have been processed.

    Raises:
        UserError: If any unknown kwargs remain.
    r   c                 s  s    | ]	}d | d V  qdS )`Nr8   )rU   kr8   r8   r9   rW     s    z(validate_empty_kwargs.<locals>.<genexpr>zUnknown keyword arguments: N)r   keysr&   rD   )r   unknown_kwargsr8   r8   r9   validate_empty_kwargs  s   	r   textc                 C  s4   |  dr| S d}t|| tj}|r|dS | S )N{z```(?:\w+)?\n(\{.*\})\n```r%   )rJ   researchDOTALLgroup)r   regexmatchr8   r8   r9   strip_markdown_fences  s   

r   tpc                 C  s.   t | }t|r| j} t | }t|s	| S r6   )r   r"   is_annotated
__origin__r  originr8   r8   r9   _unwrap_annotated  s   

r  tuple[Any, ...]c                 C  sB   t | r| j} t| } t| }t|rtdd t| D S dS )zZExtract the arguments of a Union type if `tp` is a union, otherwise return an empty tuple.c                 s  s    | ]}t |V  qd S r6   )r  )rU   argr8   r8   r9   rW     s    z!get_union_args.<locals>.<genexpr>r8   )r"   is_typealiastype	__value__r  r   r#   tupler   r  r8   r8   r9   get_union_args  s   
r  c                  C  s6   zt  } W | S  ty   t  } t |  Y | S w r6   )ru   r   RuntimeErrornew_event_loopset_event_loop)
event_loopr8   r8   r9   r     s   
r   )r/   r0   r1   r2   r3   r4   r5   r.   )r;   r   r5   r<   )rC   r   r5   r,   )rQ   rR   r5   r<   )re   rf   r5   rg   )rj   rk   rl   rm   r5   rn   )r   r   r5   r[   )r   r   r5   r   )r5   r   )r   r   r5   r   )r5   r   )r   r   r5   r   )r   r   r5   r   )r   r   r5   r   )rQ   r   r5   r   )rQ   r   r5   r   )rQ   r   r5   r   )r   r   r   r   r5   r   )r   r   r5   r   )r   r   r5   r   )r   r   r5   r   )r  r   r5   r   )r  r   r5   r  )d
__future__r   _annotationsru   r   r   r   rr   r   collections.abcr   r   r   r   r   r   
contextlibr	   r
   dataclassesr   r   r   r   r   r   typesr   typingr   r   r   r   r   r   r   r   r   anyio.to_threadr   pydanticr   r   pydantic.json_schemar   typing_extensionsr   r    r!   typing_inspectionr"   typing_inspection.introspectionr#   pydantic_graph._utilsr$   r   r&   pydantic_ai.agentr'   r(   pydantic_graphr)   r*   r+   	_messagestoolsr,   r-   r.   r:   rB   rP   rL   r[   r\   rc   rb   rd   rh   ri   r   r   r   r   r   r   r   r   r   r   r   AwaitableCallabler   r   r   r   r   r  r  r   r8   r8   r8   r9   <module>   s     ,





b

	


F




 
+


