o
    i<                     @  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mZ d dlm	Z	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 d dlmZ d d	lmZmZ d d
l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+m,Z, d dl-m.Z.m/Z/m0Z0m1Z1 d dl2m3Z3 d dl4m5Z5m6Z6 d dl7m8Z8m9Z9 d dl:m;Z;m<Z< ddl=m>Z>m?Z?m@Z@mAZBmCZCmDZDmEZF ddl@mGZG ddlHmIZImJZJ ddlKmLZL ddlMmNZNmOZOmPZPmQZQmRZRmSZSmTZTmUZU erddlVmWZW dZXe$dZYe$dZZe[dZ\ed Z]	 e$d Z^e$d!Z_ee`eBja ge`eBja f Zbee`eBja gee`eBja  f ZceeQe^ e`eBja ge`eBja f ZdeeQe^ e`eBja gee`eBja  f ZeebecB ede^ B eee^ B Zf	 ejgd"d#G d$d% d%Zhejgd"d#G d&d' d'ee^eIf ZiG d(d) d)e5eheie^ef eDjje< f Zkdd.d/ZlejgG d0d1 d1eke^e<f Zmdd5d6ZnejgG d7d8 d8eke^e<f ZoejgG d9d: d:eke^e<f ZpejgG d;d< d<eke^e<f Zqdd?d@Zre
ddAfddOdPZsddZd[ZtddadbZuejgG dcdd ddZvedeZwdfexdg< eddidjZyddkdlZzddtduZ{dd{d|Z|dd}d~Z}dS )    )annotationsN)Task)defaultdictdeque)AsyncIterator	AwaitableCallableIteratorSequence)asynccontextmanagercontextmanager)
ContextVar)deepcopy)fieldreplace)TYPE_CHECKINGAnyGenericLiteral	TypeGuardcast)Tracer)TypeVarassert_never)
_takes_ctx)DEFAULT_INSTRUMENTATION_VERSION)ToolManager)dataclasses_no_defaults_reprget_union_argsis_async_callablerun_in_executor)AbstractBuiltinTool)BaseNodeGraphRunContext)GraphGraphBuilder)EndNodeRunEndT   )_output_system_prompt
exceptionsmessagesmodelsresultusage)ToolRetryError)OutputDataT
OutputSpec)ModelSettings)DeferredToolCallResultDeferredToolResultDeferredToolResults
RunContextToolApprovedToolDefinition
ToolDeniedToolKind)InstrumentationSettings)GraphAgentStateGraphAgentDepsUserPromptNodeModelRequestNodeCallToolsNodebuild_run_contextcapture_run_messagesHistoryProcessorTS)early
exhaustiveDepsTOutputTT)kw_onlyc                   @  s|   e Zd ZU dZejedZded< eje	j
dZded< dZded	< dZded
< ejdd dZded< 		ddddZdS )r=   z3State kept across the execution of the agent graph.default_factorylist[_messages.ModelMessage]message_history_usage.RunUsager/   r   intretriesrun_stepc                   C  s   t t S N)struuiduuid4 rX   rX   ^/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/_agent_graph.py<lambda>`   s    zGraphAgentState.<lambda>rU   run_idNmax_result_retrieserrorBaseException | Nonemodel_settingsModelSettings | NonereturnNonec                 C  s   |  j d7  _ | j |krv| jrUt| jd  }tjrU|jdkrU|jrUt|jd  }tjrUz|  W n! t	yT   |rC|p?i 
dnd }td|d urN|nd dw d| d	}|rqt|tjrk|jd urk|j}t||t|d S )
Nr(   length
max_tokenszModel token limit (zprovider defaultz) exceeded while emitting a tool call, resulting in incomplete arguments. Increase max tokens or simplify tool call arguments to fit within limit.zExceeded maximum retries (z) for output validation)rR   rO   
isinstance	_messagesModelResponsefinish_reasonpartsToolCallPartargs_as_dict	Exceptiongetr+   IncompleteToolCallUnexpectedModelBehavior	__cause__)selfr\   r]   r_   model_response	tool_callre   messagerX   rX   rY   increment_retriesb   s4   


z!GraphAgentState.increment_retries)NN)r\   rQ   r]   r^   r_   r`   ra   rb   )__name__
__module____qualname____doc__dataclassesr   listrO   __annotations___usageRunUsager/   rR   rS   r[   rv   rX   rX   rX   rY   r=   X   s   
 r=   c                   @  s   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< ded< ded< ded< ded< ded< ejddZded< ded< ded < d!ed"< d#S )$r>   z.Dependencies/config passed to the agent graph.rI   	user_deps,str | Sequence[_messages.UserContent] | NonepromptrQ   new_message_indexzmodels.Modelmodelr`   r_   _usage.UsageLimitsusage_limitsr\   EndStrategyend_strategyz4Callable[[RunContext[DepsT]], Awaitable[str | None]]get_instructionsz!_output.OutputSchema[OutputDataT]output_schemaz1list[_output.OutputValidator[DepsT, OutputDataT]]output_validators!Sequence[HistoryProcessor[DepsT]]history_processorsF)reprzlist[AbstractBuiltinTool]builtin_toolsToolManager[DepsT]tool_managerr   tracerzInstrumentationSettings | Noneinstrumentation_settingsN)rw   rx   ry   rz   r}   r{   r   r   rX   rX   rX   rY   r>      s$   
 r>   c                   @  s   e Zd ZdZdS )	AgentNodezThe base class for all agent nodes.

    Using subclass of `BaseNode` for all nodes reduces the amount of boilerplate of generics everywhere
    N)rw   rx   ry   rz   rX   rX   rX   rY   r      s    r   nodeeBaseNode[GraphAgentState, GraphAgentDeps[T, Any], result.FinalResult[S]] | End[result.FinalResult[S]]ra   TypeGuard[AgentNode[T, S]]c                 C  s
   t | tS )a  Check if the provided node is an instance of `AgentNode`.

    Usage:

        if is_agent_node(node):
            # `node` is an AgentNode
            ...

    This method preserves the generic parameters on the narrowed type, unlike `isinstance(node, AgentNode)`.
    )rf   r   )r   rX   rX   rY   is_agent_node   s   
r   c                   @  s   e Zd ZU dZded< ded< dZded< dZd	ed
< eje	dZ
ded< ejedZded< eje	dZded< ejedZded< d'ddZd(ddZd)d"d#Zd*d%d&ZeZdS )+r?   z7The node that handles the user prompt and instructions.r   user_promptzdataclasses.KW_ONLY_NzDeferredToolResults | Nonedeferred_tool_results
str | NoneinstructionsrL   z.list[_system_prompt.SystemPromptRunner[DepsT]]instructions_functionsztuple[str, ...]system_promptssystem_prompt_functionsz3dict[str, _system_prompt.SystemPromptRunner[DepsT]]system_prompt_dynamic_functionsctxDGraphRunContext[GraphAgentState, GraphAgentDeps[DepsT, NodeRunEndT]]ra   HModelRequestNode[DepsT, NodeRunEndT] | CallToolsNode[DepsT, NodeRunEndT]c                   s,  zt  }W n ty   g }Y nw |jrg }n|j}d|_t|jj|d d < ||j_t||j_	| j
d urB| | j
||I d H S d }|r|d  }rt|tjr| jd u r|  tj|jd}dd |jD }|rt|dkrz|d j|j_n:g }|D ]}t|jtr||j q~||j q~||j_nt|tjr| jd u rtttf |S |jrtdt|}	|r| ||	I d H  |r| |g|	I d H  n#g }
|s|
|  |	I d H  | jd ur|
t!| j tj|
d}|j"|	I d H |_#|s|js|j#std	t$ttf |d
S )NTrc   rj   c                 S  s   g | ]
}t |tjr|qS rX   )rf   rg   UserPromptPart).0partrX   rX   rY   
<listcomp>   s    z&UserPromptNode.run.<locals>.<listcomp>r(   r   ZCannot provide a new user prompt when the message history contains unprocessed tool calls.z9No message history, user prompt, or instructions provided)request)%get_captured_run_messagesLookupErrorusedr,   _clean_message_historystaterO   lendepsr   r   _handle_deferred_tool_resultsrf   rg   ModelRequestr   poprj   contentr   rU   appendextendrh   rA   rI   r'   
tool_callsr+   	UserErrorrB   _reevaluate_dynamic_prompts
_sys_partsr   r   r   r@   )rr   r   ctx_messagesr,   next_messagelast_messageuser_prompt_partscombined_contentr   run_contextrj   rX   rX   rY   run   sj   




zUserPromptNode.runr6   r,   rN   !CallToolsNode[DepsT, NodeRunEndT]c                   s^  |st dd }d }t|D ]}t|tjr|}qt|tjr%|} nq|s-t d|js5t d| jd ur?t dd }i }|j	
 D ]\}}	|	du rTt }	n|	du r[t }	|	||< qH|j }
rtt}|

 D ]\}}t||s{t|}|||< qm|r|jD ]}t|tjtjB r|j|v rt d|jdd	||j< qtttf ||d
S )NzBTool call results were provided, but the message history is empty.z\Tool call results were provided, but the message history does not contain a `ModelResponse`.zeTool call results were provided, but the message history does not contain any unprocessed tool calls.r   TFz
Tool call z: was already executed and its result cannot be overridden.skip)tool_call_results)r+   r   reversedrf   rg   r   rh   r   r   	approvalsitemsr8   r:   callsr   r4   
ToolReturnrj   ToolReturnPartRetryPromptParttool_call_idrA   rI   r'   )rr   r   r,   r   last_model_requestlast_model_responseru   r   r   approvalr   call_result_typesr.   r   rX   rX   rY   r     s`   









z,UserPromptNode._handle_deferred_tool_resultsr   RunContext[DepsT]rb   c                   s   | j rF|D ]A}t|tjrEg }|jD ])}t|tjr7|jr7| j |j }r7||I dH }tj||jd}|	| q||jkrE||_qdS dS )zvReevaluate any `SystemPromptPart` with dynamic_ref in the provided messages by running the associated runner function.Ndynamic_ref)
r   rf   rg   r   rj   SystemPromptPartr   rn   r   r   )rr   r,   r   msgreevaluated_message_partsr   runnerupdated_part_contentrX   rX   rY   r   P  s$   

z*UserPromptNode._reevaluate_dynamic_prompts list[_messages.ModelRequestPart]c                   sb   dd | j D }| jD ]"}||I dH }|jr&|tj||jjd q|t| q|S )z0Build the initial messages for the conversation.c                 S  s   g | ]}t |qS rX   )rg   r   )r   prX   rX   rY   r   j  s    z-UserPromptNode._sys_parts.<locals>.<listcomp>Nr   )	r   r   r   dynamicr   rg   r   functionry   )rr   r   r,   sys_prompt_runnerr   rX   rX   rY   r   h  s   
zUserPromptNode._sys_parts)r   r   ra   r   )r   r6   r,   rN   r   r   ra   r   )r,   rN   r   r   ra   rb   )r   r   ra   r   )rw   rx   ry   rz   r}   r   r   r{   r   r|   r   tupler   r   dictr   r   r   r   r   r   __repr__rX   rX   rX   rY   r?      s"   
 

N
;
r?   r   r   models.ModelRequestParametersc              
     s~   | j j}t|tjr|jnd}g }g }| j jjD ]}|jdkr&|	| q|	| qt
j|| j j|j||j||j|jdS )z&Build tools and create an agent model.Noutput)function_toolsr   output_modeoutput_toolsoutput_objectprompted_output_templateallow_text_outputallow_image_output)r   r   rf   r)   PromptedOutputSchematemplater   	tool_defskindr   r-   ModelRequestParametersr   mode
object_defallows_textallows_image)r   r   r   r   r   tool_defrX   rX   rY   _prepare_request_parametersv  s(   
r   c                   @  s   e Zd ZU dZded< eddddZded< eddddZd	ed
< dddZe	dddZ
dddZd ddZd!ddZeZdS )"r@   z[The node that makes a request to the model using the last message in state.message_history.z_messages.ModelRequestr   FN)r   initdefaultz(CallToolsNode[DepsT, NodeRunEndT] | None_resultbool_did_streamr   r   ra   r   c                   s2   | j d ur	| j S | jrtd| |I d H S )Nz.You must finish streaming before calling run())r   r   r+   AgentRunError_make_requestrr   r   rX   rX   rY   r     s   

zModelRequestNode.run:GraphRunContext[GraphAgentState, GraphAgentDeps[DepsT, T]]+AsyncIterator[result.AgentStream[DepsT, T]]c           
   
   C s   | j rJ d| |I d H \}}}}|jj||||4 I d H >}d| _ |jj jd7  _tj	t
tf ||jj||jjt||jj|jjd}|V  |2 z3 d H W }qN6 W d   I d H  n1 I d H sfw   Y  | }	| ||	 | jd us|J d S )Nz,stream() should only be called once per nodeTr(   )_raw_stream_response_output_schema_model_request_parameters_output_validators_run_ctx_usage_limits_tool_manager)r   _prepare_requestr   r   request_streamr   r/   requestsr.   AgentStreamrI   rE   r   r   rB   r   r   rn   _finish_handlingr   )
rr   r   r_   model_request_parametersrO   r   streamed_responseagent_streamr   rs   rX   rX   rY   stream  s4   	(zModelRequestNode.streamc                   s`   | j d ur	| j S | |I d H \}}}}|jj|||I d H }|jj jd7  _| ||S Nr(   )	r   r  r   r   r   r   r/   r
  r  )rr   r   r_   r  rO   r   rs   rX   rX   rY   r     s   
zModelRequestNode._make_requestktuple[ModelSettings | None, models.ModelRequestParameters, list[_messages.ModelMessage], RunContext[DepsT]]c           	        s  | j jp|jj| j _|jj| j  |j jd7  _t|}|jj	|I d H |j_|jjd d  }t
||jj|I d H }||jjd d < |j jt|t| 8  _t|}t|I d H }|jj}|jj}|jjjrt|}|jj|||I d H }|| |jj| ||||fS r  )r   r[   r   rO   r   rS   rB   r   r   for_run_step_process_message_historyr   r   r   r   r   r_   r/   r   count_tokens_before_requestr   r   count_tokensincrcheck_before_request)	rr   r   r   original_historyrO   r  r_   r/   counted_usagerX   rX   rY   r    s(   

z!ModelRequestNode._prepare_requestresponse_messages.ModelResponsec                 C  sX   |j p|jj |_ |jj|j |jjr|jj|jj |jj| t	|| _
| j
S rT   )r[   r   r/   r  r   r   check_tokensrO   r   rA   r   )rr   r   r  rX   rX   rY   r    s   
z!ModelRequestNode._finish_handling)r   r   ra   r   )r   r   ra   r   )r   r   ra   r  )r   r   r  r  ra   r   )rw   rx   ry   rz   r}   r   r   r   r   r   r  r   r  r  r   r   rX   rX   rX   rY   r@     s   
 

 

(r@   c                   @  s   e Zd ZU dZded< dZded< eddddZd	ed
< eddddZded< d.ddZ	e
d/ddZd0ddZd1ddZd2d!d"Zd3d%d&Zd4d,d-ZeZdS )5rA   zcThe node that processes a model response, and decides whether to end the run or make a new request.r  rs   N6dict[str, DeferredToolResult | Literal['skip']] | Noner   F)r   r   r   z3AsyncIterator[_messages.HandleResponseEvent] | None_events_iteratorzRModelRequestNode[DepsT, NodeRunEndT] | End[result.FinalResult[NodeRunEndT]] | None
_next_noder   r   ra   KModelRequestNode[DepsT, NodeRunEndT] | End[result.FinalResult[NodeRunEndT]]c              	     sX   |  |4 I d H  W d   I d H  n1 I d H sw   Y  | jd us)J d| jS )Nz6the stream should set `self._next_node` before it ends)r  r   r   rX   rX   rY   r   !  s   (zCallToolsNode.run;AsyncIterator[AsyncIterator[_messages.HandleResponseEvent]]c                 C s*   |  |}|V  |2 z3 dH W }q6 dS )z]Process the model response and yield events for the start and end of each function tool call.N)_run_stream)rr   r   r  _eventrX   rX   rY   r  )  s   
zCallToolsNode.stream,AsyncIterator[_messages.HandleResponseEvent]c                  sN   j d u r jjd fdd}| _ j 2 z	3 d H W }|V  q6 d S )Nra   r%  c               
    s  j jsyj } rPt jjD ]?}t|tjrOd}|jD ]}t|tj	r+||j
7 }qt|tjr3d}q|rOz || I d H _W  d S  tyN   Y qw q jj jj jjd t } j|I d H }tttf tjg |d_d S d}g }g }j jD ]N}t|tj	r||j
7 }qt|tjr|| qt|tjr||j
 qt|tjrd}t|V  qt|tjrt|V  qt|tjrqt | qzwg }|r! |2 z	3 d H W }	|	V  q6 W d S j"r|d n|d j#rt$dd |D d  }
r% |
I d H _W d S |d j } r9|r3 || I d H _W d S |&d	d
 tj'dd(| dd}t| ty } z1 jj jj| jjd t } j|I d H }tttf tj|j)g|d_W Y d }~d S d }~ww )N r_   rj   r   z$include your response in a tool callzcall a toolc                 s  s     | ]}t |tjr|V  qd S rT   )rf   rg   BinaryImage)r   filerX   rX   rY   	<genexpr>  s    zACallToolsNode._run_stream.<locals>._run_stream.<locals>.<genexpr>zreturn an imager   zreturn textzPlease z or .r   r]   r_   )*rs   rj   text_processorr   r   rO   rf   rg   rh   TextPartr   BuiltinToolCallPart_handle_text_responser   r0   rv   r   r\   r_   rB   r   r@   rI   r'   r   rk   r   FilePartBuiltinToolCallEventBuiltinToolReturnPartBuiltinToolResultEventThinkingPartr   _handle_tool_callstoolsetr   next_handle_image_responseinsertr   join
tool_retry)r/  ru   textr   r   r   r   filesalternativeseventimagemer   r   rr   rX   rY   r#  =  s   






z.CallToolsNode._run_stream.<locals>._run_stream)ra   r%  )r  r   r   )rr   r   r#  rB  rX   rF  rY   r#  5  s   
izCallToolsNode._run_streamr   list[_messages.ToolCallPart]c           	   	   C s   t |}|jj|I d H |j_g }tdd}t|jj|| jd |||d2 z	3 d H W }|V  q&6 |rA|d }| |||| _d S |j	|I d H }t
ttf tj||d| _d S )Nr(   maxlen)r   r   r   final_resultr   output_partsoutput_final_resultr   r(  )rB   r   r   r  r   process_tool_callsr   _handle_final_resultr   r   r@   rI   r'   rg   r   )	rr   r   r   r   rK  rL  rB  rJ  r   rX   rX   rY   r8    s.   
	

z CallToolsNode._handle_tool_callsr?  rU   r/  (_output.BaseOutputProcessor[NodeRunEndT]c                   sP   t |}|||I d H }|jjD ]}|||I d H }q| |t|g S rT   )rB   processr   r   validaterN  r.   FinalResult)rr   r   r?  r/  r   result_data	validatorrX   rX   rY   r2    s   z#CallToolsNode._handle_text_responserC  _messages.BinaryImagec                   s    t t|}| |t|g S rT   )r   r'   rN  r.   rR  )rr   r   rC  rS  rX   rX   rY   r;    s   
z$CallToolsNode._handle_image_responserJ  result.FinalResult[NodeRunEndT]tool_responsesr   $End[result.FinalResult[NodeRunEndT]]c                 C  s,   |j j}|r|tj||j jd t|S )N)rj   r[   )r   rO   r   rg   r   r[   r&   )rr   r   rJ  rW  r,   rX   rX   rY   rN    s   z"CallToolsNode._handle_final_result)r   r   ra   r!  )r   r   ra   r"  )r   r   ra   r%  )r   r   r   rG  ra   r%  )r   r   r?  rU   r/  rO  ra   r!  )r   r   rC  rU  ra   r!  )r   r   rJ  rV  rW  r   ra   rX  )rw   rx   ry   rz   r}   r   r   r  r   r   r   r  r#  r8  r2  r;  rN  r   r   rX   rX   rX   rY   rA     s"   
 


v
!

rA   c                   @  s$   e Zd ZU dZded< ddd	Zd
S )SetFinalResultz^A node that immediately ends the graph run after a streaming response produced a final result.rV  rJ  r   r   ra   rX  c                   s   t | jS rT   )r&   rJ  r   rX   rX   rY   r     s   
zSetFinalResult.runN)r   r   ra   rX  )rw   rx   ry   rz   r}   r   rX   rX   rX   rY   rY    s   
 rY  <GraphRunContext[GraphAgentState, GraphAgentDeps[DepsT, Any]]r   c                 C  sd   t t | jj| jj| jj| jj| jj| jj	| jj
duo| jj
j| jj
r(| jj
jnt| jj| jjd
S )zEBuild a `RunContext` object from the current agent graph run context.N)
r   r   r/   r   r,   r   trace_include_contentinstrumentation_versionrS   r[   )r7   rI   r   r   r   r   r/   r   rO   r   r   include_contentversionr   rS   r[   )r   rX   rX   rY   rB     s   rB   rH  r   r   r   rG  r   r  rJ  &result.FinalResult[NodeRunEndT] | NonerK  r   rL  &deque[result.FinalResult[NodeRunEndT]]r%  c                  s  t t}|D ]}| |j}	|	r|	j}
nd}
||
 | q|d D ]}|rT|j|jkr8tj|jd|jd}nt	|V  tj|jd|jd}t
|V  || q#z
| |I dH }W nM tjyz } z|jj|jj||jjd |d}~w ty } z&|jj|jj||jjd t	|V  ||j t
|jV  W Y d}~q#d}~ww tj|jd|jd}|| t||j|j}q#g }|r|jjdkr|d	 D ]}|tj|jd
|jd qn||d	  |d r|jj|jj|jjd ||d  i  |durG||d  ||d  t| }dd |D }||kr5td| d| dd | D   fdd|D }t t}|rlt| | |jj|jj|jj ||d2 z
3 dH W }|V  q`6 |du rg |d |d }|rt!|j"t#j$s|D ]}|tj|jd
|jd qn!|r|d |d  |d |d  |D ]	}t	|V  q|s|r|jj%j&stdt#j$|d |d d}tt't(|dd}|r|| dS dS )zProcess function (i.e., non-result) tool calls in parallel.

    Also add stub return parts for any other tools that need it.

    Because async iterators can't have return values, we use `output_parts` and `output_final_result` as output arguments.
    unknownr   zFinal result processed.	tool_namer   r   z<Output tool not used - a final result was already processed.Nr.  rG   r   z9Tool not executed - a final result was already processed.r'  external
unapprovedc                 S  s   h | ]}|j qS rX   r   r   callrX   rX   rY   	<setcomp>o      z%process_tool_calls.<locals>.<setcomp>zMTool call results need to be provided for all deferred tool calls. Expected: z, got: c                 S  s   i | ]\}}|d kr||qS )r   rX   )r   call_idr.   rX   rX   rY   
<dictcomp>w  s    z&process_tool_calls.<locals>.<dictcomp>c                   s   g | ]	}|j  v r|qS rX   rf  rg  calls_to_run_resultsrX   rY   r   x      z&process_tool_calls.<locals>.<listcomp>)r   r   r   r   r/   r   rK  output_deferred_callszA deferred tool call was present, but `DeferredToolRequests` is not among output types. To resolve this, add `DeferredToolRequests` to the list of output types for this agent.)r   r   ))r   r|   get_tool_defrc  r   r   r   rg   r   FunctionToolCallEventFunctionToolResultEventhandle_callr+   rp   r   rv   r   r\   r_   r0   r>  r.   rR  r   r   setkeysr   r   _call_toolsr   r/   r   rf   r   r)   DeferredToolRequestsr   allows_deferred_toolsr   r'   )r   r   r   rJ  r   rK  rL  tool_calls_by_kindrh  r   r   r   rS  rE  calls_to_runresult_tool_call_idstool_call_ids_to_rundeferred_callsrB  r   deferred_tool_requestsrX   rm  rY   rM    s   
	





rM  dict[str, DeferredToolResult]r   r   r/   rP   r   r   rp  Edict[Literal['external', 'unapproved'], list[_messages.ToolCallPart]]c              	    s  i i i  |j d urt|}| jt|7  _|| |D ]}	t|	V  q |jddd |D dt| dt|dkr@dnd d	d
j d fdd}
|rvt	|D ]\}}	|
t
|	|	j|I d H  }rt|V  q[n5fdd|D }|}|rtj|tjdI d H \}}|D ]}||}|
||dI d H  }r|V  q|sW d    n1 sw   Y  |fddtD  |fddtD  t D ]}| |  ||  qd S )Nzrunning toolsc                 S  s   g | ]}|j qS rX   )rc  rg  rX   rX   rY   r     rj  z_call_tools.<locals>.<listcomp>zrunning z toolr(   r&  s)toolszlogfire.msg)
attributescoro_or_taskAwaitable[tuple[_messages.ToolReturnPart | _messages.RetryPromptPart, str | Sequence[_messages.UserContent] | None]] | Task[tuple[_messages.ToolReturnPart | _messages.RetryPromptPart, str | Sequence[_messages.UserContent] | None]]indexrQ   ra   $_messages.HandleResponseEvent | Nonec                   s   zt | r| I d H n|  \}}W n tjy"   d |< Y d S  tjy0   d |< Y d S w ||< |r?tj|d|< tj||dS )Nrd  re  r-  )	inspectisawaitabler.   r+   CallDeferredApprovalRequiredrg   r   rs  )r  r  	tool_parttool_user_content)deferred_calls_by_indextool_parts_by_indexuser_parts_by_indexrX   rY   handle_call_or_result  s   
z*_call_tools.<locals>.handle_call_or_resultc              	     s,   g | ]}t jt| |j|jd qS ))name)asynciocreate_task
_call_toolrn   r   rc  rg  )r   r   rX   rY   r     s    )return_when)r  r  c                      g | ]} | qS rX   rX   r   k)r  rX   rY   r         c                   r  rX   rX   r  )r  rX   rY   r     r  )r  r  r  rQ   ra   r  )tool_calls_limitr   r   r   check_before_tool_callrg   rr  start_as_current_spanshould_call_sequentially	enumerater  rn   r   r  waitFIRST_COMPLETEDr  r   sortedr   )r   r   r   r   r/   r   rK  rp  projected_usagerh  r  r  rB  taskspendingdonetaskr  rX   )r  r   r   r  r  rY   rw    sZ   


"

?rw  rt   _messages.ToolCallParttool_call_resultDeferredToolResult | Noneituple[_messages.ToolReturnPart | _messages.RetryPromptPart, str | Sequence[_messages.UserContent] | None]c              
     sD  zh|d u r|  |I d H }nYt|tr,|jd ur!tj||jd}| j |ddI d H }n<t|tr?tj|j	|j
|jdd fW S t|tjrTtj|j
|j	|jd}t|t|tjrf|j	|_	|j|_t||}W n ty } z|jd fW  Y d }~S d }~ww t|tjr|}n_t|t}|rttt |n|g}g }	g }
|D ]4}t|tjrtd|j	dt|tjr|j}|	d|  |
d	| d
|g q|	| qtjt|	dkr|s|	d n|	|
d}t|jtjst|jtrtdd |jD rtd|j	dtj|j	|j|j|jd}||jp d fS )N)argsT)approvedrb  )r   rc  r   zThe return value of tool zT contains invalid nested `ToolReturn` objects. `ToolReturn` should be used directly.z	See file zThis is file :r(   r   )return_valuer   c                 s  s    | ]	}t |tjV  qd S rT   )rf   rg   MultiModalContent)r   r   rX   rX   rY   r+  K  s
    

z_call_tool.<locals>.<genexpr>zThe `return_value` of tool zS contains invalid nested `MultiModalContent` objects. Please use `content` instead.)rc  r   r   metadata)rt  rf   r8   override_argsr{   r   r:   rg   r   rc  ru   r   r+   
ModelRetryr   r0   r>  r   r|   r   r   r   r  
identifierr   r   r   r  anyr  r   )r   rt   r  tool_resultrD  rE  tool_returnresult_is_listcontentsreturn_valuesuser_contentsr   r  return_partrX   rX   rY   r    s   




r  c                   @  s"   e Zd ZU ded< dZded< dS )_RunMessagesrN   r,   Fr   r   N)rw   rx   ry   r}   r   rX   rX   rX   rY   r  _  s   
 r  varzContextVar[_RunMessages]_messages_ctx_var&Iterator[list[_messages.ModelMessage]]c               	   c  st    d} g }zt  j}W n ty   t t|} Y nw z|V  W | dur-t |  dS dS | dur9t |  w w )aT  Context manager to access the messages used in a [`run`][pydantic_ai.agent.AbstractAgent.run], [`run_sync`][pydantic_ai.agent.AbstractAgent.run_sync], or [`run_stream`][pydantic_ai.agent.AbstractAgent.run_stream] call.

    Useful when a run may raise an exception, see [model errors](../agents.md#model-errors) for more information.

    Examples:
    ```python
    from pydantic_ai import Agent, capture_run_messages

    agent = Agent('test')

    with capture_run_messages() as messages:
        try:
            result = agent.run_sync('foobar')
        except Exception:
            print(messages)
            raise
    ```

    !!! note
        If you call `run`, `run_sync`, or `run_stream` more than once within a single `capture_run_messages` context,
        `messages` will represent the messages exchanged during the first call only.
    N)r  rn   r,   r   ru  r  reset)tokenr,   rX   rX   rY   rC   h  s   rC   c                   C  s   t  S rT   )r  rn   rX   rX   rX   rY   r     s   r   r  r   	deps_typetype[DepsT]output_typeOutputSpec[OutputT]sGraph[GraphAgentState, GraphAgentDeps[DepsT, OutputT], UserPromptNode[DepsT, OutputT], result.FinalResult[OutputT]]c                 C  s   t | pdttttf tttf tjt dd}||	|j
tttf |tttf |tttf |tttf |tttf  |jddS )zDBuild the execution [Graph][pydantic_graph.Graph] for a given agent.AgentF)r  
state_typer  
input_typer  auto_instrument)validate_graph_structure)r%   r=   r>   rI   rJ   r?   r.   rR  add	edge_from
start_nodetor   r@   rA   rY  build)r  r  r  grX   rX   rY   build_agent_graph  s$   

	
	r  r,   rN   
processorsr   r   c                   s   |D ]B}t |}t|r%|r||| I dH } qtt|}|| I dH } q|r8ttt |}t||| I dH } qtt|}t|| I dH } qt| dkrQt	
dt| d tjs^t	
d| S )z9Process message history through a sequence of processors.Nr   z"Processed history cannot be empty.rc   z1Processed history must end with a `ModelRequest`.)is_takes_ctxr   r   _HistoryProcessorAsync_HistoryProcessorSyncWithCtxrI   r    _HistoryProcessorSyncr   r+   r   rf   rg   r   )r,   r  r   	processor	takes_ctxasync_processorsync_processor_with_ctxsync_processorrX   rX   rY   r    s$   



r  c                 C  s.  g }| D ]}t |dkr|d nd}t|tjrR|rLt|tjrL|jr,|jr,|j|jkrLg |j|j}|jdd d tj||jpD|jd}||d< q|| qt|tjr|rt|tjr|j	du r|j
du r|jdu r|j	du r|j
du r|jdu rt|g |j|jd}||d< q|| q|S )	zKClean the message history by merging consecutive messages of the same type.r   rc   Nc                 S  s   t | tjtjB rdS dS )Nr   r(   )rf   rg   r   r   )xrX   rX   rY   rZ     ro  z(_clean_message_history.<locals>.<lambda>)keyr(  r   )r   rf   rg   r   r   rj   sortr   rh   provider_response_idprovider_name
model_namer   )r,   clean_messagesru   r   rj   merged_messagerX   rX   rY   r     sN   











r   )r   r   ra   r   )r   r   ra   r   )r   rZ  ra   r   )r   r   r   rG  r   r  rJ  r_  r   r   rK  r   rL  r`  ra   r%  )r   r   r   rG  r   r  r   r   r/   rP   r   r   rK  r   rp  r  ra   r%  )r   r   rt   r  r  r  ra   r  )ra   r  )ra   r  )r  r   r  r  r  r  ra   r  )r,   rN   r  r   r   r   ra   rN   )r,   rN   ra   rN   )~
__future__r   _annotationsr  r{   r  rV   r   collectionsr   r   collections.abcr   r   r   r	   r
   
contextlibr   r   contextvarsr   copyr   r   r   typingr   r   r   r   r   r   opentelemetry.tracer   typing_extensionsr   r   pydantic_ai._function_schemar   r  pydantic_ai._instrumentationr   pydantic_ai._tool_managerr   pydantic_ai._utilsr   r   r   r    pydantic_ai.builtin_toolsr!   pydantic_graphr"   r#   pydantic_graph.betar$   r%   pydantic_graph.nodesr&   r'   r&  r)   r*   r+   r,   rg   r-   r.   r/   r~   r0   r   r1   r2   settingsr3   r  r4   r5   r6   r7   r8   r9   r:   r;   models.instrumentedr<   __all__rE   rF   typeNoneTyper   rI   rJ   r|   ModelMessager  r  r  _HistoryProcessorAsyncWithCtxrD   	dataclassr=   r>   rR  r   r   r?   r   r@   rA   rY  rB   rM  rw  r  r  r  r}   rC   r   r  r  r   rX   rX   rX   rY   <module>   s     $( 

((
 
B  ^
 

\T
)

  