
    g              	      ,   U d dl mZ d dlZd dlZd dlZd dlmZmZm	Z	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mZmZmZmZ d dlZd dlmZmZmZ d	d
l 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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 dZ9 ejt                  d      Z;	 d dl<Z=d dl>m?Z? e=j                  j                  xj                   eC e?eD      j                  j                               fz  c_B         eHd      ZIed   ZJ	  ed      ZK	 e ej                  d       G d dee0e+f                       ZMej                   G d d             ZN ed      ZOdePd<   ed d       ZQej                   G d dee+                ZRy# eG$ r Y w xY w)!    )annotationsN)AsyncIterator	AwaitableIteratorSequence)AbstractAsyncContextManagerasynccontextmanagercontextmanager)
ContextVar)	FrameType)AnyCallableGenericLiteralcastfinaloverload)TypeVarassert_never
deprecated   )_result_system_prompt_utils
exceptionsmessagesmodelsresultusage)
ResultData)ModelSettingsmerge_model_settings)		AgentDeps
RunContextToolToolDefinitionToolFuncContextToolFuncEitherToolFuncPlain
ToolParamsToolPrepareFunc)Agentcapture_run_messagesEndStrategyzpydantic-ai)
otel_scope)Path)early
exhaustiveRunResultDataF)initc                   	   e Zd ZU dZded<   	 ded<   	 ded<   	 ded	<   	  ej                  d
      Zded<    ej                  d
      Zded<    ej                  d
      Z	ded<    ej                  d
      Z
ded<    ej                  d
      Zded<    ej                  d
      Zded<    ej                  d
      Zded<    ej                  d
      Zded<    ej                  d
      Zded<    ej                  d
      Zded<    ej                  d
      Zded<    ej                  d d
!      Zd"ed#<    ej                  d d
!      Zd$ed%<   	 dded&ed d d'd(d d d&d
d)d*	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ded+Zed d d d d d d d,d-	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dfd.       Zed d d d d d d,d/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dgd0       Zd d d d d d d d,d1	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dhd2Zed d d d d d d,d/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 did3       Zed d d d d d d,d/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 djd4       Zd d d d d d d d,d-	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dkd5Zed d d d d d d d,d-	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dld6       Zed d d d d d d,d/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dmd7       Zed d d d d d d d,d-	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dnd8       Zeej<                  ej<                  d9	 	 	 	 	 dod:       Ze	 	 	 	 dpd;       Z e	 	 	 	 dqd<       Z edrd=       Z edsd>       Z ed
d?	 	 	 dtd@       Z 	 ddd
d?	 	 	 	 	 dudAZ e	 	 	 	 dvdB       Z!e	 	 	 	 dwdC       Z!edxdD       Z!e	 	 	 	 dydE       Z!	 	 	 	 dzdFZ!ed{dG       Z"ed d dH	 	 	 	 	 d|dI       Z"	 ddd d dH	 	 	 	 	 	 	 d}dJZ"ed~dK       Z#ed d dH	 	 	 	 	 ddL       Z#	 ddd d dH	 	 	 	 	 	 	 ddMZ#	 	 	 	 	 	 	 	 	 	 ddNZ$ddOZ%ddPZ&	 	 	 	 	 	 ddQZ'	 	 	 	 	 	 ddRZ(	 	 	 	 ddSZ)	 	 	 	 	 	 	 	 ddTZ*	 	 	 	 	 	 	 	 ddUZ+	 	 	 	 	 	 	 	 ddVZ,	 	 	 	 	 	 	 	 ddWZ-	 	 	 	 	 	 	 	 	 	 ddXZ.	 	 	 	 	 	 	 	 ddYZ/	 	 	 	 	 	 	 	 ddZZ0dd[Z1dd\Z2	 	 	 	 	 	 	 	 dd]Z3dd^Z4dd_Z5e6dd`       Z7e8 e9dad b      ddc              Z:y )r,   aY  Class for defining "agents" - a way to have a specific type of "conversation" with an LLM.

    Agents are generic in the dependency type they take [`AgentDeps`][pydantic_ai.tools.AgentDeps]
    and the result data type they return, [`ResultData`][pydantic_ai.result.ResultData].

    By default, if neither generic parameter is customised, agents have type `Agent[None, str]`.

    Minimal usage example:

    ```python
    from pydantic_ai import Agent

    agent = Agent('openai:gpt-4o')
    result = agent.run_sync('What is the capital of France?')
    print(result.data)
    #> Paris
    ```
    +models.Model | models.KnownModelName | Nonemodel
str | Nonenamer.   end_strategyModelSettings | Nonemodel_settingsF)reprstr_result_tool_name_result_tool_descriptionz'_result.ResultSchema[ResultData] | None_result_schemaz4list[_result.ResultValidator[AgentDeps, ResultData]]_result_validatorsztuple[str, ...]_system_promptszdict[str, Tool[AgentDeps]]_function_toolsint_default_retriesz2list[_system_prompt.SystemPromptRunner[AgentDeps]]_system_prompt_functionsz7dict[str, _system_prompt.SystemPromptRunner[AgentDeps]] _system_prompt_dynamic_functionstype[AgentDeps]
_deps_type_max_result_retriesN)defaultr=   z_utils.Option[AgentDeps]_override_depsz_utils.Option[models.Model]_override_model r   final_resultr1   )result_typesystem_prompt	deps_typer9   r<   retriesresult_tool_nameresult_tool_descriptionresult_retriestoolsdefer_model_checkr:   c                  ||r|| _         nt        j                  |      | _         || _        || _        || _        || _        |	| _        t        j                  |   j                  |||	      | _        t        |t              r|fn
t        |      | _        i | _        || _        |D ]>  }t        |t$              r| j'                  |       %| j'                  t%        |             @ || _        g | _        i | _        |
|
n|| _        g | _        y)a?	  Create an agent.

        Args:
            model: The default model to use for this agent, if not provide,
                you must provide the model when calling it.
            result_type: The type of the result data, used to validate the result data, defaults to `str`.
            system_prompt: Static system prompts to use for this agent, you can also register system
                prompts via a function with [`system_prompt`][pydantic_ai.Agent.system_prompt].
            deps_type: The type used for dependency injection, this parameter exists solely to allow you to fully
                parameterize the agent, and therefore get the best out of static type checking.
                If you're not using deps, but want type checking to pass, you can set `deps=None` to satisfy Pyright
                or add a type hint `: Agent[None, <return type>]`.
            name: The name of the agent, used for logging. If `None`, we try to infer the agent name from the call frame
                when the agent is first run.
            model_settings: Optional model request settings to use for this agent's runs, by default.
            retries: The default number of retries to allow before raising an error.
            result_tool_name: The name of the tool to use for the final result.
            result_tool_description: The description of the final result tool.
            result_retries: The maximum number of retries to allow for result validation, defaults to `retries`.
            tools: Tools to register with the agent, you can also register tools via the decorators
                [`@agent.tool`][pydantic_ai.Agent.tool] and [`@agent.tool_plain`][pydantic_ai.Agent.tool_plain].
            defer_model_check: by default, if you provide a [named][pydantic_ai.models.KnownModelName] model,
                it's evaluated to create a [`Model`][pydantic_ai.models.Model] instance immediately,
                which checks for the necessary environment variables. Set this to `false`
                to defer the evaluation until the first run. Useful if you want to
                [override the model][pydantic_ai.Agent.override] for testing.
            end_strategy: Strategy for handling tool calls that are requested alongside a final result.
                See [`EndStrategy`][pydantic_ai.agent.EndStrategy] for more information.
        N)r7   r   infer_modelr:   r9   r<   r?   r@   r   ResultSchemabuildrA   
isinstancer>   tuplerC   rD   rF   r%   _register_toolrJ   rG   rH   rK   rB   )selfr7   rQ   rR   rS   r9   r<   rT   rU   rV   rW   rX   rY   r:   tools                  F/var/www/openai/venv/lib/python3.12/site-packages/pydantic_ai/agent.py__init__zAgent.__init__x   s   \ =-DJ++E2DJ(	,!1(?%%22;?EE)+B
 4>mS3Q/W\]jWk! 'D$%##D)##DJ/	 
 $(*%02-5C5O>U\ "$    TrQ   message_historyr7   depsr<   usage_limitsr   
infer_namec                  K   y wNrO   
ra   user_promptrQ   rg   r7   rh   r<   ri   r   rj   s
             rc   runz	Agent.run   s      (+   )rg   r7   rh   r<   ri   r   rj   c                  K   y wrl   rO   rm   s
             rc   ro   z	Agent.run   s      +.rp   )rg   r7   rh   r<   ri   r   rQ   rj   c          	       K   |	r/| j                   #| j                  t        j                                | j	                  |       d{   }
| j                  |      }|rt        |      nd}| j                  |      }t        j                  d|| |
j                         | j                   xs d      5 }t        ||
|xs t        j                         |      }| j                  |||       d{   }||_        | j                  j!                         D ]	  }d|_         t%        | j&                  |      }|xs t        j(                         }	 |j+                  |j,                         |xj.                  dz  c_        t        j                  d|j.                        5  | j1                  ||       d{   }ddd       t        j                  d	|j.                        5 }j3                  ||       d{   \  }}|j5                  d
|       |j5                  d|       ddd       |j7                         |j,                  j9                  d       |j;                  |j,                         t        j                  d|j.                        5 }| j=                  |||       d{   \  }}|r$|j7                  t?        j@                  |             ||jB                  }|jD                  }|j5                  d|       |j5                  d|j,                         |j5                  d|       d|_#        tI        jJ                  |||||j,                        cddd       cddd       S |j5                  d|       djM                  d |D              }d| |_#        	 ddd       c7 k7 7 # 1 sw Y   xY w7 # 1 sw Y   xY w7 )# 1 sw Y   4xY w# 1 sw Y   yxY ww)a  Run the agent with a user prompt in async mode.

        Example:
        ```python
        from pydantic_ai import Agent

        agent = Agent('openai:gpt-4o')

        result_sync = agent.run_sync('What is the capital of Italy?')
        print(result_sync.data)
        #> Rome
        ```

        Args:
            result_type: Custom result type to use for this run, `result_type` may only be used if the agent has no
                result validators since result validators would expect an argument that matches the agent's result type.
            user_prompt: User input to start/continue the conversation.
            message_history: History of the conversation so far.
            model: Optional model to use for this run, required if `model` was not set when creating the agent.
            deps: Optional dependencies to use for this run.
            model_settings: Optional settings to use for this model's request.
            usage_limits: Optional limits on model request count or token usage.
            usage: Optional usage to start with, useful for resuming a conversation or agents used in tools.
            infer_name: Whether to try to infer the agent name from the call frame if it's not set.

        Returns:
            The result of the run.
        Nr   z{agent_name} run {prompt=}agentpromptrs   
model_name
agent_namer   %preparing model and tools {run_step=}run_stepzmodel requestresponser   )requestshandle model responseall_messagesr   %handle model response -> final resulttool_responses c              3  4   K   | ]  }|j                     y wrl   	part_kind.0rs     rc   	<genexpr>zAgent.run.<locals>.<genexpr>I  s     5Z>aakk>   handle model response -> )'r9   _infer_nameinspectcurrentframe
_get_model	_get_depslen_prepare_result_schema_logfirespanr$   _usageUsage_prepare_messagesr   rD   valuescurrent_retryr"   r<   UsageLimitscheck_before_requestr   rz   _prepare_modelrequestset_attributeappendincrcheck_tokens_handle_model_response	_messagesModelRequestdata	tool_namemessager   	RunResultjoin)ra   rn   rg   r7   rh   r<   ri   r   rQ   rj   
model_usednew_message_indexresult_schemarun_spanrun_contextr   rb   agent_modelmodel_req_spanmodel_responserequest_usagehandle_spanrP   r   result_datarU   tool_responses_strs                              rc   ro   z	Agent.run   s    R $))+W1134??511
~~d#4CC033K@]](!(yy+G  
 $T:u7NP[\K!33KR]^^H#+K ,,335%&" 6 2$2E2E~VN'?6+=+=+?L11+2C2CD$$)$]]#JU`UiUi]j(,(;(;K(W"WK k ]]?[=Q=Q]RVd:E:M:MhXf:g4g1NM"00^L"00-H S
 /!!&&}q&A))+*;*;<]]#:[EYEY]Z^i9=9T9T&]: 40L. & 	(>(>~(NO $/&2&7&7+7+A+A( ..~xH ..w8I8IJ#11(KH.U+%//$&7FVXcXiXi # [ZC
 
n $112BNS-0XX5Z>5Z-Z*0IJ\I].^+1 [! / 2 _ #X kj 5h SR4 [ZC
 
s   AO4N3	A+O44;O(/N60B1O(!N<7N98N<<)O(%O;O	<+O'A2O(O0O1B0O!	O(*
O444O)
O(3O46O(9N<<O	O(	OO	O(OO%	!O((O1-O4c                    y rl   rO   )	ra   rn   rg   r7   rh   r<   ri   r   rj   s	            rc   run_synczAgent.run_syncL  s     (+re   c                    y rl   rO   rm   s
             rc   r   zAgent.run_syncZ  s     +.re   c                   |	r/| j                   #| j                  t        j                                t	        j
                         j                  | j                  ||||||||d	            S )a   Run the agent with a user prompt synchronously.

        This is a convenience method that wraps [`self.run`][pydantic_ai.Agent.run] with `loop.run_until_complete(...)`.
        You therefore can't use this method inside async code or if there's an active event loop.

        Example:
        ```python
        from pydantic_ai import Agent

        agent = Agent('openai:gpt-4o')

        async def main():
            result = await agent.run('What is the capital of France?')
            print(result.data)
            #> Paris
        ```

        Args:
            result_type: Custom result type to use for this run, `result_type` may only be used if the agent has no
                result validators since result validators would expect an argument that matches the agent's result type.
            user_prompt: User input to start/continue the conversation.
            message_history: History of the conversation so far.
            model: Optional model to use for this run, required if `model` was not set when creating the agent.
            deps: Optional dependencies to use for this run.
            model_settings: Optional settings to use for this model's request.
            usage_limits: Optional limits on model request count or token usage.
            usage: Optional usage to start with, useful for resuming a conversation or agents used in tools.
            infer_name: Whether to try to infer the agent name from the call frame if it's not set.

        Returns:
            The result of the run.
        Frf   )r9   r   r   r   asyncioget_event_looprun_until_completero   rm   s
             rc   r   zAgent.run_synci  sp    Z $))+W1134%%'::HH' /-)   

 	
re   c                    y rl   rO   rm   s
             rc   
run_streamzAgent.run_stream  s	     X[re   c                    y rl   rO   rm   s
             rc   r   zAgent.run_stream  s	     [^re   c                 K   |	r= j                   1t        j                         x}
r j                  |
j                          j                  |       d{   } j                  |      }|rt        |      nd} j                  |      t        j                  d| |j                          j                   xs d      5 t        |||xs t        j                         |       j                  ||       d{   _         j                   j#                         D ]	  }d|_         t'         j(                  |      }|xs t        j*                         }	 xj,                  dz  c_        |j/                  j0                         t        j                  dj,                        5   j3                         d{   }ddd       t        j                  d	j,                        5 }j5                  |      4 d{   }j0                  xj6                  dz  c_        |j9                  d
|j:                  j<                         |j?                  ddd       t        j                  d      5 } jA                  |       d{   }tC        |tD              r}|jF                  }|jH                  d|_%         fd}tM        jN                  ||| jP                  |	       	 ddd       ddd      d{    ddd       ddd       y|\  }}jS                  |       |r$jS                  tU        jV                  |             |j9                  d|       djY                  d |D              }d| |_%        |j1                         }j0                  j[                  |       |j]                  j0                         	 ddd       ddd      d{    ddd       7 7 7 ?# 1 sw Y   ?xY w7 
7 7 # 1 sw Y   BxY w7 9# 1 d{  7  sw Y   IxY w# 1 sw Y   MxY w# 1 sw Y   yxY ww)aj  Run the agent with a user prompt in async mode, returning a streamed response.

        Example:
        ```python
        from pydantic_ai import Agent

        agent = Agent('openai:gpt-4o')

        async def main():
            async with agent.run_stream('What is the capital of the UK?') as response:
                print(await response.get_data())
                #> London
        ```

        Args:
            result_type: Custom result type to use for this run, `result_type` may only be used if the agent has no
                result validators since result validators would expect an argument that matches the agent's result type.
            user_prompt: User input to start/continue the conversation.
            message_history: History of the conversation so far.
            model: Optional model to use for this run, required if `model` was not set when creating the agent.
            deps: Optional dependencies to use for this run.
            model_settings: Optional settings to use for this model's request.
            usage_limits: Optional limits on model request count or token usage.
            usage: Optional usage to start with, useful for resuming a conversation or agents used in tools.
            infer_name: Whether to try to infer the agent name from the call frame if it's not set.

        Returns:
            The result of the run.
        Nr   z!{agent_name} run stream {prompt=}rs   rt   r   rx   ry   zmodel request {run_step=}response_typer}   r   c                 n  K   d   } t        | t        j                        sJ | j                  D cg c]  }t        |t        j                        s|! }}	j                  |       d{   }|r$j                  t        j                  |             j                  d       yc c}w 7 Bw)zCalled when the stream has completed.

                                    The model response will have been added to messages by now
                                    by `StreamedRunResult._marked_completed`.
                                    Nr~   )	r^   r   ModelResponsepartsToolCallPart_process_function_toolsr   r   r   )
last_messagepart
tool_callsr   r   r   rU   r   r   ra   s
       rc   on_completez%Agent.run_stream.<locals>.on_complete$  s      4<B<L+5lID[D[+\$\+\9E9K9K2&9KzZ^`i`v`vOw9K %/ 2& 372N2N(24DkS`3& -&E (-(0	8N8Nu8U(V$,$:$:>8$T2&-&s#   0B5B.B.B50B31AB5r   r   c              3  4   K   | ]  }|j                     y wrl   r   r   s     rc   r   z#Agent.run_stream.<locals>.<genexpr>L  s     =bSaaakkSar   r   )/r9   r   r   r   f_backr   r   r   r   r   r   r$   r   r   r   r   rD   r   r   r"   r<   r   rz   r   r   r   request_streamr|   r   	__class____name____exit___handle_streamed_model_responser^   _MarkFinalResultr   r   r   r   StreamedRunResultrB   r   r   r   r   r   r   )ra   rn   rQ   rg   r7   rh   r<   ri   r   rj   framer   r   rb   r   r   r   r   maybe_final_resultresult_streamr   model_response_msgr   r   model_response_usager   r   rU   r   r   s   `                        @@@@@rc   r   zAgent.run_stream  s    V $))+,,..u.  .??511
~~d#4CC033K@]]/!(yy+G  
 $T:u7NP[\K!33KR]^^H#+K ,,335%&" 6 2$2E2E~VN'?6+=+=+?L$$)$11+2C2CD]]#JU`UiUi]j(,(;(;K(W"WK k ]]#>I]I]]^bp*99(NSSWe#))22a72&44_nF^F^FgFgh '//dDA%]]+BC{7;7[7[ .]8 2.
  **<>NO0B0G0G3E3O3O 06] 3!U !U$ '-&>&>$,$5$0$1$1$/$($;$;$4$/
'" 
!" !'Q D  TS _1
 
V FX B 2N (0B C#1$,OOI4J4J>4Z$[ + 9 9:JN [58XX=bSa=b5b 28QRdQe6f 37E7K7K7M 4 + 1 1 6 67K L , 9 9+:K:K Lq D  TS _ / 2 _ #X kj  T2  T DC  TSSS _^1
 
s%  AQPA+Q;QPB1Q5PP
P)Q9QP
QA.P1P#	PA(P#	P1
QP QQ"	Q+B6P#	"P1*Q5P/6Q:
QQQ
PP	QQP#	 Q#P,(P1/Q1Q7P:8Q?QQ	QQQ)rh   r7   c             #  Z  K   t        j                  |      r'| j                  }t        j                  |      | _        nt         j                  }t        j                  |      r:| j
                  }t        j                  t        j                  |            | _        nt         j                  }	 d t        j                  |      r|| _        t        j                  |      r|| _        yy# t        j                  |      r|| _        t        j                  |      r|| _        w w xY ww)a  Context manager to temporarily override agent dependencies and model.

        This is particularly useful when testing.
        You can find an example of this [here](../testing-evals.md#overriding-model-via-pytest-fixtures).

        Args:
            deps: The dependencies to use instead of the dependencies passed to the agent run.
            model: The model to use instead of the model passed to the agent run.
        N)r   is_setrM   SomeUNSETrN   r   r[   )ra   rh   r7   override_deps_beforeoverride_model_befores        rc   overridezAgent.overrideS  s       ==#'#6#6 "(++d"3D#)<<  ==$($8$8!#);;v/A/A%/H#ID $*LL!	=}}12&:#}}23'<$ 4 }}12&:#}}23'<$ 4s   B,D+/C- 3:D+-;D((D+c                    y rl   rO   ra   funcs     rc   rR   zAgent.system_prompty  s     25re   c                    y rl   rO   r   s     rc   rR   zAgent.system_prompt~  s     =@re   c                    y rl   rO   r   s     rc   rR   zAgent.system_prompt  s    NQre   c                    y rl   rO   r   s     rc   rR   zAgent.system_prompt  s    dgre   dynamicc                   y rl   rO   )ra   r   s     rc   rR   zAgent.system_prompt  s	     nqre   c                   |	 	 	 	 d fd}|S rJ d        j                   j                  t        j                  |             |S )a  Decorator to register a system prompt function.

        Optionally takes [`RunContext`][pydantic_ai.tools.RunContext] as its only argument.
        Can decorate a sync or async functions.

        The decorator can be used either bare (`agent.system_prompt`) or as a function call
        (`agent.system_prompt(...)`), see the examples below.

        Overloads for every possible signature of `system_prompt` are included so the decorator doesn't obscure
        the type of the function, see `tests/typed_agent.py` for tests.

        Args:
            func: The function to decorate
            dynamic: If True, the system prompt will be reevaluated even when `messages_history` is provided,
                see [`SystemPromptPart.dynamic_ref`][pydantic_ai.messages.SystemPromptPart.dynamic_ref]

        Example:
        ```python
        from pydantic_ai import Agent, RunContext

        agent = Agent('test', deps_type=str)

        @agent.system_prompt
        def simple_system_prompt() -> str:
            return 'foobar'

        @agent.system_prompt(dynamic=True)
        async def async_system_prompt(ctx: RunContext[str]) -> str:
            return f'{ctx.deps} is the best'
        ```
        c                    t        j                  |       }j                  j                  |       r|j                  | j
                  <   | S )Nr   )r   SystemPromptRunnerrG   r   rH   __qualname__)func_runnerr   ra   s     rc   	decoratorz&Agent.system_prompt.<locals>.decorator  sI     (::5'R--44V<PVD99%:L:LMre   z"dynamic can't be True in this caser   )r   *_system_prompt.SystemPromptFunc[AgentDeps]returnr   )rG   r   r   r   )ra   r   r   r   s   ` ` rc   rR   zAgent.system_prompt  s^    R <A; D DD;))001R1RSWah1ijKre   c                    y rl   rO   r   s     rc   result_validatorzAgent.result_validator  s	     EHre   c                    y rl   rO   r   s     rc   r   zAgent.result_validator  s	     PSre   c                    y rl   rO   r   s     rc   r   zAgent.result_validator  s    svre   c                    y rl   rO   r   s     rc   r   zAgent.result_validator  s     9<re   c               |    | j                   j                  t        j                  t        t
        f   |             |S )a8  Decorator to register a result validator function.

        Optionally takes [`RunContext`][pydantic_ai.tools.RunContext] as its first argument.
        Can decorate a sync or async functions.

        Overloads for every possible signature of `result_validator` are included so the decorator doesn't obscure
        the type of the function, see `tests/typed_agent.py` for tests.

        Example:
        ```python
        from pydantic_ai import Agent, ModelRetry, RunContext

        agent = Agent('test', deps_type=str)

        @agent.result_validator
        def result_validator_simple(data: str) -> str:
            if 'wrong' in data:
                raise ModelRetry('wrong response')
            return data

        @agent.result_validator
        async def result_validator_deps(ctx: RunContext[str], data: str) -> str:
            if ctx.deps in data:
                raise ModelRetry('wrong response')
            return data

        result = agent.run_sync('foobar', deps='spam')
        print(result.data)
        #> success (no tool calls)
        ```
        )rB   r   r   ResultValidatorr#   r   r   s     rc   r   zAgent.result_validator  s2    D 	&&w'>'>y#~'Nt'TUre   c                    y rl   rO   r   s     rc   rb   z
Agent.tool  s    orre   )rT   preparec                   y rl   rO   ra   rT   r   s      rc   rb   z
Agent.tool  s	     fire   c              T     |	 	 	 	 d fd}|S  j                  |d       |S )a  Decorator to register a tool function which takes [`RunContext`][pydantic_ai.tools.RunContext] as its first argument.

        Can decorate a sync or async functions.

        The docstring is inspected to extract both the tool description and description of each parameter,
        [learn more](../tools.md#function-tools-and-schema).

        We can't add overloads for every possible signature of tool, since the return type is a recursive union
        so the signature of functions decorated with `@agent.tool` is obscured.

        Example:
        ```python
        from pydantic_ai import Agent, RunContext

        agent = Agent('test', deps_type=int)

        @agent.tool
        def foobar(ctx: RunContext[int], x: int) -> int:
            return ctx.deps + x

        @agent.tool(retries=2)
        async def spam(ctx: RunContext[str], y: float) -> float:
            return ctx.deps + y

        result = agent.run_sync('foobar', deps=1)
        print(result.data)
        #> {"foobar":1,"spam":1.0}
        ```

        Args:
            func: The tool function to register.
            retries: The number of retries to allow for this tool, defaults to the agent's default retries,
                which defaults to 1.
            prepare: custom method to prepare the tool definition for each step, return `None` to omit this
                tool from a given step. This is useful if you want to customise a tool at call time,
                or omit it completely from a step. See [`ToolPrepareFunc`][pydantic_ai.tools.ToolPrepareFunc].
        c                0    j                  | d       | S NT_register_functionr   r   rT   ra   s    rc   tool_decoratorz"Agent.tool.<locals>.tool_decorator:  s     ''tWgFre   T)r   &ToolFuncContext[AgentDeps, ToolParams]r   r  r   ra   r   rT   r   r  s   ` `` rc   rb   z
Agent.tool  sC    Z <=7 "! ##D$AKre   c                    y rl   rO   r   s     rc   
tool_plainzAgent.tool_plainG  s    [^re   c                   y rl   rO   r   s      rc   r  zAgent.tool_plainJ  s	     LOre   c              L     |
d fd}|S  j                  |d       |S )a  Decorator to register a tool function which DOES NOT take `RunContext` as an argument.

        Can decorate a sync or async functions.

        The docstring is inspected to extract both the tool description and description of each parameter,
        [learn more](../tools.md#function-tools-and-schema).

        We can't add overloads for every possible signature of tool, since the return type is a recursive union
        so the signature of functions decorated with `@agent.tool` is obscured.

        Example:
        ```python
        from pydantic_ai import Agent, RunContext

        agent = Agent('test')

        @agent.tool
        def foobar(ctx: RunContext[int]) -> int:
            return 123

        @agent.tool(retries=2)
        async def spam(ctx: RunContext[str]) -> float:
            return 3.14

        result = agent.run_sync('foobar', deps=1)
        print(result.data)
        #> {"foobar":123,"spam":3.14}
        ```

        Args:
            func: The tool function to register.
            retries: The number of retries to allow for this tool, defaults to the agent's default retries,
                which defaults to 1.
            prepare: custom method to prepare the tool definition for each step, return `None` to omit this
                tool from a given step. This is useful if you want to customise a tool at call time,
                or omit it completely from a step. See [`ToolPrepareFunc`][pydantic_ai.tools.ToolPrepareFunc].
        c                0    j                  | d       | S )NFr   r  s    rc   r  z(Agent.tool_plain.<locals>.tool_decorator  s    ''ugwGre   F)r   ToolFuncPlain[ToolParams]r   r  r   r  s   ` `` rc   r  zAgent.tool_plainS  s1    Z <
 "!##D%'BKre   c                d    ||n| j                   }t        ||||      }| j                  |       y)z1Private utility to register a function as a tool.N)	takes_ctxmax_retriesr   )rF   r%   r`   )ra   r   r  rT   r   retries_rb   s          rc   r  zAgent._register_function  s4     &17t7L7LDI8WUD!re   c                   |j                   !t        j                  || j                        }|j                  | j
                  v r"t        j                  d|j                        | j                  rD|j                  | j                  j                  v r"t        j                  d|j                        || j
                  |j                  <   y)z,Private utility to register a tool instance.N)r  z(Tool name conflicts with existing tool: z-Tool name conflicts with result schema name: )
r  dataclassesreplacerF   r9   rD   r   	UserErrorrA   rX   )ra   rb   s     rc   r`   zAgent._register_tool  s    #&&t9N9NOD99,,,&&)QRVR[R[Q^'_``4990C0C0I0I#I&&)VW[W`W`Vc'dee*.TYY're   c                L  K   | j                   x}r1|!| j                  t        j                  d      |j                  }|S |t        j                  |      }|S | j                  (t        j                  | j                        x}| _        |S t        j                  d      w)zCreate a model configured for this agent.

        Args:
            model: model to use for this run, required if `model` was not set when creating the agent.

        Returns:
            The model used
        z`model` must be set either when creating the agent or when calling it. (Even when `override(model=...)` is customizing the model that will actually be called)zF`model` must be set either when creating the agent or when calling it.)rN   r7   r   r  valuer   r[   )ra   r7   
some_modelmodel_s       rc   r   zAgent._get_model  s      ---:-}!3 **n   %%F  ''.F  ZZ#"("4"4TZZ"@@FTZ  &&'opps   B"B$c                .  K   g dfd}t        j                  t        || j                  j	                                 d{    j
                  j                  | j                  |      ||j                         ng        d{   S 7 K7 w)z&Build tools and create an agent model.c                   K   j                  | j                  | j                        }| j                  |       d {   x}rj	                  |       y y 7 w)N)retryr   )replace_withr   r9   prepare_tool_defr   )rb   ctxtool_deffunction_toolsr   s      rc   add_toolz&Agent._prepare_model.<locals>.add_tool  sU     **1C1Ctyy*YC!%!6!6s!;;;x;%%h/ <;s   <AA AN)r  allow_text_resultresult_toolsrb   zTool[AgentDeps]r   None)	r   gathermaprD   r   r7   r   _allow_text_result	tool_defs)ra   r   r   r   r  s    `  @rc   r   zAgent._prepare_model  s      02	0
 nnc(D,@,@,G,G,IJKKK &&22)"55mD6C6O002UW 3 
 
 	
 	L
s%   ABBABBBBc                  K   | j                   r|D ]  }t        |t        j                        st	        |j
                        D ]  \  }}t        |t        j                        s!|j                  s.| j                   j                  |j                        x}sV|j                  |       d{   }t        j                  ||j                        |j
                  |<     yy7 8w)zvReevaluate any `SystemPromptPart` with dynamic_ref in the provided messages by running the associated runner function.Ndynamic_ref)
rH   r^   r   r   	enumerater   SystemPromptPartr+  getro   )ra   r   r   msgir   r   updated_part_contents           rc   _reevaluate_dynamic_promptsz!Agent._reevaluate_dynamic_prompts  s     
 00c9#9#9:#,SYY#74%dI,F,FGDL\L\)-)N)N)R)RSWScSc)ddvd=CZZ=T7T 4/8/I/I$8dFVFV0"		! $8   1 8Us(   ,C)5C)%C)2'C)C).C'/9C)c                    |Y| j                   rt        j                  d      t        j                  |   j                  || j                  | j                        S | j                  S )NzJCannot set a custom run `result_type` when the agent has result validators)	rB   r   r  r   r\   r]   r?   r@   rA   )ra   rQ   s     rc   r   zAgent._prepare_result_schema  sd     "&& **+wxx''4::T33T5R5R  &&&re   c                8  K   	 t         j                         }|j                  rg }n|j                  }d|_        	 |re|j                  |       | j                  ||       d {    |j                  t        j                  t        j                  |      g             |S | j                  |       d {   }|j                  t        j                  |             |j                  t        j                  |             |S # t        $ r g }Y w xY w7 7 awr   )_messages_ctx_varr.  usedr   LookupErrorextendr2  r   r   r   UserPromptPart
_sys_parts)ra   rn   rg   r   ctx_messagesr   r   s          rc   r   zAgent._prepare_messages  s     		),002L   '00$(!OOO,228[IIIOOI22I4L4L[4Y3Z[\ 	 //+66ELL11+>?OOI2259:)  	857H	8 J 7sH   DD AD#D$AD6D7ADDDDDDc                  K   g }g }|j                   D ]V  }t        |t        j                        r)|j                  s*|j                  |j                         F|j                  |       X |r| j                  |||       d{   S |r,dj                  |      }| j                  |||       d{   S t        j                  d      7 G7 w)zProcess a non-streamed response from the model.

        Returns:
            A tuple of `(final_result, request parts)`. If `final_result` is not `None`, the conversation should end.
        Nz

zReceived empty model response)r   r^   r   TextPartcontentr   _handle_structured_responser   _handle_text_responser   UnexpectedModelBehavior)ra   r   r   r   textsr   r   texts           rc   r   zAgent._handle_model_response  s      35
"((D$	 2 23<<LL.!!$' ) 99*kS`aaa;;u%D33D+}UUU445TUU b Vs)   :CACC-C2C3CCc                |  K   | j                  |      r:t        t        |      }	 | j                  ||d       d{   }t	        |d      g fS | j                  |       t        j                  d      }d|gfS 7 ># t
        j                  $ r*}| j                  |       d|j                  gfcY d}~S d}~ww xY ww)zHHandle a plain text response from the model for non-streaming responses.NQPlain text responses are not permitted, please call one of the functions instead.r>  )r'  r   r3   _validate_resultr   r   ToolRetryError_incr_result_retry
tool_retryr   RetryPromptPart)ra   rC  r   r   result_data_inputr   er{   s           rc   r@  zAgent._handle_text_response.  s      ""=1 $]D 9?$($9$9:K[Z^$__
 (T:B>>##K0 00kH (## `)) ,''4all^++,sD   "B<A< A:A<  :B<:A< <B9B4.B9/B<4B99B<c                  K   |sJ d       d}g }|x}r[|j                  |      x}rH|\  }}	 |j                  |      }	| j                  |	||       d{   }	t        |	|j                        }|| j                  ||xr |j                  ||       d{   z  }||fS 7 K# t
        j                  $ r6}
| j                  |       |j                  |
j                         Y d}
~
wd}
~
ww xY w7 Xw)z^Handle a structured response containing tool calls from the model for non-streaming responses.zExpected at least one tool callN)	find_toolvalidaterG  r   r   r   rH  rI  r   rJ  r   )ra   r   r   r   rP   r   matchcallresult_toolr   rM  s              rc   r?  z!Agent._handle_structured_responseB  s     <<<z @D24))=)%//
;;u;$)!kQ"-"6"6t"<K(,(=(=k;X\(]"]K
 $4K#PL 	t33?)?)?m
 
 	
 U"" #^-- /++K8LL../
sL   *C0'B" B B" <C0C.
C0 B" "C+5,C&!C0&C++C0c           	     Z  K   g }g }t        |      xr | j                  dk(  }d}|D ]  }	|	j                  |k(  r@|s>d}|j                  t	        j
                  |	j                  d|	j                               S| j                  j                  |	j                        x}
r|r<|j                  t	        j
                  |	j                  d|	j                               |j                  t        j                  |
j                  |	|      |	j                               |Y|	j                  |j                  v rA||j                  t	        j
                  |	j                  d	|	j                               T|j                  | j                  |	j                  ||              |rit        j                  d
|D cg c]  }|j!                          c}      5  t        j"                  |  d{   }|j%                  |       ddd       |S |S c c}w 7 &# 1 sw Y   |S xY ww)zProcess function (non-result) tool calls in parallel.

        Also add stub return parts for any other tools that need it.
        r1   FTzFinal result processed.)r   r>  tool_call_idz9Tool not executed - a final result was already processed.r9   Nz<Result tool not used - a final result was already processed.running {tools=}rX   )boolr:   r   r   r   ToolReturnPartrU  rD   r.  r   create_taskro   rX   _unknown_toolr   r   get_namer%  r8  )ra   r   rU   r   r   r   tasksstub_function_toolsfound_used_result_toolrR  rb   ttask_resultss                rc   r   zAgent._process_function_toolsb  s     35@B"#34U9J9Jg9U "'D~~!11:P)-&,,"&.. 9%)%6%6 --11$..AAA&LL!00&*nn$_)-):): LL!4!4TXXdK5PW[WeWe!fg*t~~ATAT/T $/LL!00&*nn$b)-):): T//][\C H 1PU9VPU1!**,PU9VWKR>>[`KaEa\* X u :WEa X sC   D:H+>BH+ H
H+H5H6HH+HH(#H+c           	       K   t        |t        j                        rP| j                  |      rt	        |d      S | j                  |       t        j                  d      }|2 3 d{   }
t        |t        j                        r||j                         }|j                  s6	 |j                          d{    |j                         }|j                  s6|j!                  |j                        x}r|\  }	}t	        ||	j"                        S |2 3 d{   }
tA        |       y7 6 dj                  |j                  d            }t        j                  t        j                  |      g      |gfS 7 # t        $ r Y w xY w7 r6 |j                         }
|
j                  st%        j&                  d      g }g }|
j                  D ]  }t        |t        j(                        s|}	| j*                  j                  |	j"                        x}rA|j-                  t/        j0                  |j3                  |	|      |	j"                               |j-                  | j5                  |	j"                  ||              t6        j9                  d	|D cg c]  }|j;                          nc c}w c}
      5  t/        j<                  |  d{  7  }|j?                  |       ddd       |
|fS # 1 sw Y   |
|fS xY ww)zProcess a streamed response from the model.

        Returns:
            Either a final result or a tuple of the model response and the tool responses for the next request.
            If a final result is returned, the conversation should end.
        NrE  rF   T)r   z Received empty tool call messagerV  rW  rX  )!r^   r   StreamTextResponser'  r   rI  r   rK  r   r.  r   r=  StreamStructuredResponser   	__anext__StopAsyncIterationrO  r   r   rA  r   rD   r   r   r[  ro   r\  r   r   r]  r%  r8  r   )ra   r   r   r   r{   _rC  structured_msgrQ  rR  r   r^  r   itemrb   ra  rb  s                    rc   r   z%Agent._handle_streamed_model_response  s     nf&?&?@&&}5'==''4$44o  . ! (G(GH( "0!3!3!5(..,66888 &4%7%7%9N ).. *33N4H4HII5I#GD!+NDNNKK * a* (Y~ ww~111=> ..	0B0B40H/IJXJVV 9- >!/!3!3!5%++ 889[\\ EGE68E*00dI$:$:;D#3377GGtGW%8%8$9T[_[i[i%jkT%7%7Ub%cd 1 1PU9VPU1!**,PU9VWKR>>[`KaEaEa\* X &u,, X &u,,s   A!L#D-'D+(D-+:L&E= 9E;:E= >L:LFFFL+D--AL;E= =	F	LF		LFAL.B,LJ2
1L?K8KK8,L8L=
Lc                   K   | j                   rLt        t        |      }| j                   D ]  }|j                  |||       d {   } t        t        |      S |S 7 wrl   )rB   r   r    rP  r3   )ra   r   r   	tool_callagent_result_data	validators         rc   rG  zAgent._validate_result  sc      "" $Z =!44	*3*<*<=NPY[f*g$g! 5'899 %hs   AAAAc                    |xj                   dz  c_         |j                   | j                  kD  r#t        j                  d| j                   d      y )Nr   zExceeded maximum retries (z) for result validation)r  rK   r   rA  )ra   r   s     rc   rI  zAgent._incr_result_retry  sS    Qt77744,T-E-E,FF]^  8re   c                  K   | j                   D cg c]  }t        j                  |       }}| j                  D ]  }|j	                  |       d{   }|j
                  r;|j                  t        j                  ||j                  j                               c|j                  t        j                  |              |S c c}w 7 xw)z0Build the initial messages for the conversation.Nr*  )	rC   r   r-  rG   ro   r   r   functionr   )ra   r   pr   sys_prompt_runnerru   s         rc   r:  zAgent._sys_parts  s     ]a]q]q5r]qXYi6P6PQR6S]q5r!%!>!>,00==F ((	 : :6O`OiOiOvOv wx	 : :6 BC "?  6s=s   CC%CCA9Cc                   | j                  |       t        | j                  j                               }|r|j	                  |j                                |rddj                  |       }nd}t        j                  d|d|       S )NzAvailable tools: z, zNo tools available.zUnknown tool name: z. rF  )	rI  listrD   keysr8  
tool_namesr   r   rK  )ra   r   r   r   namesr/  s         rc   r\  zAgent._unknown_tool  s     	,T))..01LL1134%dii&6%78C'C((3FymSUVYUZ1[\\re   c                :    | j                   x}r|j                  S |S )zGet deps for a run.

        If we've overridden deps via `_override_deps`, use that, otherwise use the deps passed to the call.

        We could do runtime type checking of deps against `self._deps_type`, but that's a slippery slope.
        )rM   r  )ra   rh   	some_depss      rc   r   zAgent._get_deps  s$     +++9+??"Kre   c                >   | j                   J d       ||j                  x}ry|j                  j                         D ]  \  }}|| u s|| _          y |j                  |j                  k7  r0|j                  j                         D ]  \  }}|| u s|| _          y yyyy)zwInfer the agent name from the call frame.

        Usage should be `self._infer_name(inspect.currentframe())`.
        NzName already set)r9   r   f_localsitems	f_globals)ra   function_frameparent_framer9   rk  s        rc   r   zAgent._infer_name!  s    
 yy 4"44 %-444|4"."7"7"="="?JD$t|$(	 #@  ((L,B,BB&2&<&<&B&B&D
d4<(,DI" 'E C 5 &re   c                &    | d u xs | j                   S rl   )r!  )r   s    rc   r'  zAgent._allow_text_result4  s    $G(G(GGre   WThe `last_run_messages` attribute has been removed, use `capture_run_messages` instead.)categoryc                    t        d      )Nr  )AttributeError)ra   s    rc   last_run_messageszAgent.last_run_messages8  s    
 vwwre   rl   )r7   r6   rQ   ztype[ResultData]rR   zstr | Sequence[str]rS   rI   r9   r8   r<   r;   rT   rE   rU   r>   rV   r8   rW   
int | NonerX   z:Sequence[Tool[AgentDeps] | ToolFuncEither[AgentDeps, ...]]rY   rY  r:   r.   )rn   r>   rQ   r$  rg   #list[_messages.ModelMessage] | Noner7   r6   rh   r#   r<   r;   ri   _usage.UsageLimits | Noner   _usage.Usage | Nonerj   rY  r   result.RunResult[ResultData])rn   r>   rQ   type[RunResultData]rg   r  r7   r6   rh   r#   r<   r;   ri   r  r   r  rj   rY  r   result.RunResult[RunResultData])rn   r>   rg   r  r7   r6   rh   r#   r<   r;   ri   r  r   r  rQ   type[RunResultData] | Nonerj   rY  r   result.RunResult[Any])rn   r>   rg   r  r7   r6   rh   r#   r<   r;   ri   r  r   r  rj   rY  r   r  )rn   r>   rQ   r  rg   r  r7   r6   rh   r#   r<   r;   ri   r  r   r  rj   rY  r   r  )rn   r>   rQ   r  rg   r  r7   r6   rh   r#   r<   r;   ri   r  r   r  rj   rY  r   r  )rn   r>   rQ   r$  rg   r  r7   r6   rh   r#   r<   r;   ri   r  r   r  rj   rY  r   zLAbstractAsyncContextManager[result.StreamedRunResult[AgentDeps, ResultData]])rn   r>   rQ   r  rg   r  r7   r6   rh   r#   r<   r;   ri   r  r   r  rj   rY  r   zOAbstractAsyncContextManager[result.StreamedRunResult[AgentDeps, RunResultData]])rn   r>   rQ   r  rg   r  r7   r6   rh   r#   r<   r;   ri   r  r   r  rj   rY  r   z7AsyncIterator[result.StreamedRunResult[AgentDeps, Any]])rh   zAgentDeps | _utils.Unsetr7   z3models.Model | models.KnownModelName | _utils.Unsetr   zIterator[None])r   &Callable[[RunContext[AgentDeps]], str]r   r  )r   1Callable[[RunContext[AgentDeps]], Awaitable[str]]r   r  )r   Callable[[], str]r   r  )r   Callable[[], Awaitable[str]]r   r  )r   rY  r   zbCallable[[_system_prompt.SystemPromptFunc[AgentDeps]], _system_prompt.SystemPromptFunc[AgentDeps]])r   z1_system_prompt.SystemPromptFunc[AgentDeps] | Noner   rY  r   zCallable[[_system_prompt.SystemPromptFunc[AgentDeps]], _system_prompt.SystemPromptFunc[AgentDeps]] | _system_prompt.SystemPromptFunc[AgentDeps])r   9Callable[[RunContext[AgentDeps], ResultData], ResultData]r   r  )r   DCallable[[RunContext[AgentDeps], ResultData], Awaitable[ResultData]]r   r  )r   "Callable[[ResultData], ResultData]r   r  )r   -Callable[[ResultData], Awaitable[ResultData]]r   r  )r   2_result.ResultValidatorFunc[AgentDeps, ResultData]r   r  )r   r  r   r  )rT   r  r   !ToolPrepareFunc[AgentDeps] | Noner   zZCallable[[ToolFuncContext[AgentDeps, ToolParams]], ToolFuncContext[AgentDeps, ToolParams]])r   z-ToolFuncContext[AgentDeps, ToolParams] | NonerT   r  r   r  r   r   )r   r  r   r  )rT   r  r   r  r   z@Callable[[ToolFuncPlain[ToolParams]], ToolFuncPlain[ToolParams]])r   z ToolFuncPlain[ToolParams] | NonerT   r  r   r  r   r   )
r   z%ToolFuncEither[AgentDeps, ToolParams]r  rY  rT   r  r   r  r   r$  r#  )r7   r6   r   zmodels.Model)r   RunContext[AgentDeps]r   *_result.ResultSchema[RunResultData] | Noner   zmodels.AgentModel)r   list[_messages.ModelMessage]r   r  r   r$  )rQ   r  r   r  )rn   r>   rg   r  r   r  r   r  )r   z_messages.ModelResponser   r  r   r  r   Otuple[_MarkFinalResult[RunResultData] | None, list[_messages.ModelRequestPart]])rC  r>   r   r  r   r  r   r  )r   list[_messages.ToolCallPart]r   r  r   r  r   r  )
r   r  rU   r8   r   r  r   r  r    list[_messages.ModelRequestPart])r   zmodels.EitherStreamedResponser   r  r   r  r   zr_MarkFinalResult[models.EitherStreamedResponse] | tuple[_messages.ModelResponse, list[_messages.ModelRequestPart]])r   r3   r   r  rm  z_messages.ToolCallPart | Noner   r3   )r   r  r   r$  )r   r  r   r  )r   r>   r   r  r   r  r   z_messages.RetryPromptPart)rh   r#   r   r#   )r  zFrameType | Noner   r$  )r   r  r   rY  )r   r  );r   
__module__r   __doc____annotations__r  fieldr?   r@   rA   rB   rC   rD   rF   rG   rH   rJ   rK   rM   rN   r>   NoneTyperd   r   ro   r   r   r	   r
   r   r   r   rR   r   rb   r  r  r`   r   r   r2  r   r   r   r@  r?  r   r   rG  rI  r:  r\  r   r   staticmethodr'  propertyr   r  rO   re   rc   r,   r,   @   s   ( 766
 H((
 /[..E:s:+<;+<+<%+HjH>Ok>O>OUZ>[N;[O`{O`O`fkOlLl'8{'8'8e'DO_D2C+2C2C2OO/O-K--59c9SdS^SdSdjoSpPp`q`k`q`qa$&]  #4+"3"3"?J?0{00e<</@{/@/@TY/ZN,Z3D;3D3DTX]3^O0^ >BH% ),-/%-/3 ..2%)LN"'$+H%:H% &	H%
 +H% #H% H% -H% H% H% ",H% #H% JH%  H% "H%T 
 !?C=A/326%)++ 	+
 =+ ;+ + -+ 0+ #+ + 
&+ +  @D=A/326%).. )	.
 =. ;. . -. 0. #. . 
). .$ @D=A/326%)26j_j_ =	j_
 ;j_ j_ -j_ 0j_ #j_ 0j_ j_ 
j_X 
 @D=A/326%)++ =	+
 ;+ + -+ 0+ #+ + 
&+ +  @D=A/326%).. 0	.
 =. ;. . -. 0. #. . 
). .$ 37?C=A/326%);
;
 0	;

 =;
 ;;
 ;
 -;
 0;
 #;
 ;
 
;
z 
 !?C=A/326%)[[ 	[
 =[ ;[ [ -[ 0[ #[ [ 
V[ [  @D=A/326%)^^ )	^
 =^ ;^ ^ -^ 0^ #^ ^ 
Y^ ^ 
 37?C=A/326%)LMLM 0	LM
 =LM ;LM LM -LM 0LM #LM LM 
ALM LM\  *0EK\\	#= '#= C	#=
 
#= #=J 5:5	/5 5 @E@	:@ @ Q Qg g$)q!q	kq q CG8
 8?8
 8	58t HMH	BH H SXS	MS S v v<A<	6< <#F#	;#J r r
 #59i 	i
 3i 
di i ?C:
 #59:;:
 : 3: 
:x ^ ^
 #59O 	O
 3O 
JO O 267
 #597.7
 7 37 
7r
"3
" 
" 	
"
 3
" 

"/8
0
Ak
	
&"4"CX"	""
'5
'	3
'1Tcx	%6V/V +V B	V
 
YVB$$&;$Lv$	X$(#0# +# B	#
 
Y#@:0: %: +	:
 B: 
*:xE)5E) +E) B	E)	KE)N" + 1	
 
	]] +] B	]
 
#] 
#& H H alpx xre   r,   c                  &    e Zd ZU ded<   dZded<   y)_RunMessagesr  r   FrY  r6  N)r   r  r   r  r6  rO   re   rc   r  r  @  s    **D$re   r  varzContextVar[_RunMessages]r5  c               #    K   	 t         j                         j                   y# t        $ rW g } t         j	                  t        |             }	 |  t         j                  |       Y y# t         j                  |       w xY ww xY ww)a*  Context manager to access the messages used in a [`run`][pydantic_ai.Agent.run], [`run_sync`][pydantic_ai.Agent.run_sync], or [`run_stream`][pydantic_ai.Agent.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)r5  r.  r   r7  setr  reset)r   tokens     rc   r-   r-   I  sp     0+##%... +13!%%l8&<=	+N##E*##E*+s7   B % B)BA*B(B*BBBc                  (    e Zd ZU dZded<   	 ded<   y)r   a  Marker class to indicate that the result is the final result.

    This allows us to use `isinstance`, which wouldn't be possible if we were returning `ResultData` directly.

    It also avoids problems in the case where the result type is itself `None`, but is set.
    r    r   r8   r   N)r   r  r   r  r  rO   re   rc   r   r   l  s      Hre   r   )r   z&Iterator[list[_messages.ModelMessage]])S
__future__r   _annotationsr   r  r   collections.abcr   r   r   r   
contextlibr   r	   r
   contextvarsr   typesr   typingr   r   r   r   r   r   r   logfire_apityping_extensionsr   r   r   rd  r   r   r   r   r   r   r   r   r   r   r    settingsr!   r"   rX   r#   r$   r%   r&   r'   r(   r)   r*   r+   __all__Logfirer   logfire._internal.stack_infologfirepathlibr0   	_internal
stack_infoNON_USER_CODE_PREFIXESr>   __file__parentabsoluteImportErrortyper  r.   r3   	dataclassr,   r  r5  r  r-   r   rO   re   rc   <module>r     s   2    H H W W "  I I I  ? ?	 	 	  9
 
 
 9;-8d'   77CX@U@U@^@^@`<a;cc7:+,
 ( d E"{xGIz)* {x # {x|'   
 /9.? + ? + +D Iwz* I I)  		s   $F FF