o
    i                     @  sr  U d dl mZ d dlZd dlZd dlmZmZ d dlm	Z	m
Z
mZmZmZmZmZ d dlmZmZmZ d dlmZ d dl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# d
dl$m%Z%m&Z&m'Z'm(Z(m)Z*m+Z+m,Z,m-Z. d
dl/m0Z0 d
dl1m2Z2 d
dl3m4Z4m5Z5 d
dl,m6Z6m7Z7m8Z8 d
dl9m:Z:m;Z;m<Z< d
dl=m>Z> d
dl?m@Z@mAZAmBZBmCZCmDZD d
dlEmFZF d
dl-mGZGmHZH erd dlImJZJ d dlKmLZL d dlMmNZNmOZO d dlPmQZQ d dlRmSZS d dlTmUZUmVZV d dlWmXZXmYZY d dlZm[Z[ e!dZ\e!dZ]e^dZ_e!dZ`	 eeBe@ e	e*ja ged f Zbd ecd!< 	 ede&jee@ B eede&jee@ B  B dB ZfG d"d# d#ee@e4f eZgdS )$    )annotationsN)ABCabstractmethod)AsyncIterableAsyncIterator	AwaitableCallableIteratorMappingSequence)AbstractAsyncContextManagerasynccontextmanagercontextmanager)	FrameType)TYPE_CHECKINGAnyGeneric	TypeAliascastoverload)SelfTypeIsTypeVar)End   )_agent_graph_system_prompt_utils
exceptionsmessagesmodelsresultusage)ToolManager)AbstractBuiltinTool)OutputDataT
OutputSpec)AgentStreamFinalResultStreamedRunResult)AgentRunAgentRunResultAgentRunResultEvent)ModelSettings)
AgentDepsTDeferredToolResults
RunContextToolToolFuncEither)AbstractToolset)RunUsageUsageLimits)FastA2A)Broker)AgentProviderSkill)Storage)
Middleware)	BaseRouteRoute)ExceptionHandlerLifespanAGUIAppTSRunOutputDataTr   EventStreamHandlerc                   @  s  e Zd ZdZeedddZeedddZejedddZeedddZ	eedddZ
eedddZeedddZe	ddddddddddddddddd5d6Ze	dddddddddddddd7dd:d6Z	ddddddddddddddddd=d6Ze	ddddddddddddddddd>d?Ze	dddddddddddddd7dd@d?Z	dddddddddddddddddAd?Ze	dddddddddddddddddCdDZe	dddddddddddddd7ddFdDZe	dddddddddddddddddHdDZe	ddddddddddddddIddKdLZe	dddddddddddddMddOdLZ	ddddddddddddddIddQdLZe	ddddddddddddddRddTdUZe	dddddddddddddVddXdUZ	ddddddddddddddRddZdUZ	ddddddddddddd[dd\d]Ze	ddddddddddddddRdd_d`Ze	dddddddddddddVddbd`Zee	ddddddddddddddRdddd`ZeeejejejejejejdeddodpZddsdtZeeddudvZeddzd{Zedd}d~ZedddZedddZ edddZ!edddZ"dddddddddddddddddddddZ#dddddddddddddddddZ$			ddddZ%			ddddZ&dS )AbstractAgentzAbstract superclass for [`Agent`][pydantic_ai.agent.Agent], [`WrapperAgent`][pydantic_ai.agent.WrapperAgent], and your own custom agent implementations.return1models.Model | models.KnownModelName | str | Nonec                 C     t )z,The default model configured for this agent.NotImplementedErrorself rN   `/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/agent/abstract.pymodelM      zAbstractAgent.model
str | Nonec                 C  rI   )zThe 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.
        rJ   rL   rN   rN   rO   nameS      zAbstractAgent.namevalueNonec                 C  rI   )z,Set the name of the agent, used for logging.rJ   )rM   rU   rN   rN   rO   rS   \   rQ   typec                 C  rI   )z+The type of dependencies used by the agent.rJ   rL   rN   rN   rO   	deps_typeb   rQ   zAbstractAgent.deps_typeOutputSpec[OutputDataT]c                 C  rI   )zjThe type of data output by agent runs, used to validate the data returned by the model, defaults to `str`.rJ   rL   rN   rN   rO   output_typeh   rQ   zAbstractAgent.output_type%EventStreamHandler[AgentDepsT] | Nonec                 C  rI   )zcOptional handler for events from the model's streaming response and the agent's execution of tools.rJ   rL   rN   rN   rO   event_stream_handlern   rQ   z"AbstractAgent.event_stream_handler%Sequence[AbstractToolset[AgentDepsT]]c                 C  rI   )zVAll toolsets registered on the agent.

        Output tools are not included.
        rJ   rL   rN   rN   rO   toolsetst   rT   zAbstractAgent.toolsetsNTrZ   message_historydeferred_tool_resultsrP   instructionsdepsmodel_settingsusage_limitsr"   
infer_namer^   builtin_toolsr\   user_prompt,str | Sequence[_messages.UserContent] | NonerZ   r`   'Sequence[_messages.ModelMessage] | Nonera   DeferredToolResults | NonerP   rb   Instructions[AgentDepsT]rc   r.   rd   ModelSettings | Nonere   _usage.UsageLimits | Noner"   _usage.RunUsage | Nonerf   boolr^   ,Sequence[AbstractToolset[AgentDepsT]] | Nonerg   $Sequence[AbstractBuiltinTool] | Noner\   AgentRunResult[OutputDataT]c                     d S NrN   rM   rh   rZ   r`   ra   rP   rb   rc   rd   re   r"   rf   r^   rg   r\   rN   rN   rO   run}      zAbstractAgent.run)r`   ra   rP   rb   rc   rd   re   r"   rf   r^   rg   r\   OutputSpec[RunOutputDataT]AgentRunResult[RunOutputDataT]c                  rt   ru   rN   rv   rN   rN   rO   rw      rx   !OutputSpec[RunOutputDataT] | NoneAgentRunResult[Any]c                  s  |r| j du r| t  |p| j}| j|||||||||	|
||d4 I dH O}|2 z@3 dH W }|durl| |s@| |rl||j	4 I dH }|t
|j	|I dH  W d  I dH  n1 I dH sgw   Y  q,6 W d  I dH  n1 I dH s~w   Y  |jdusJ d|jS )a  Run the agent with a user prompt in async mode.

        This method builds an internal agent graph (using system prompts, tools and output schemas) and then
        runs the graph to completion. The result of the run is returned.

        Example:
        ```python
        from pydantic_ai import Agent

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

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

        Args:
            user_prompt: User input to start/continue the conversation.
            output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
                output validators since output validators would expect an argument that matches the agent's output type.
            message_history: History of the conversation so far.
            deferred_tool_results: Optional results for deferred tool calls in the message history.
            model: Optional model to use for this run, required if `model` was not set when creating the agent.
            instructions: Optional additional instructions to use for this run.
            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.
            toolsets: Optional additional toolsets for this run.
            event_stream_handler: Optional handler for events from the model's streaming response and the agent's execution of tools to use for this run.
            builtin_tools: Optional additional builtin tools for this run.

        Returns:
            The result of the run.
        N)rh   rZ   r`   ra   rP   rb   rc   rd   re   r"   r^   rg   z%The graph run did not finish properly)rS   _infer_nameinspectcurrentframer\   iteris_model_request_nodeis_call_tools_nodestreamctxr   build_run_contextr!   )rM   rh   rZ   r`   ra   rP   rb   rc   rd   re   r"   rf   r^   rg   r\   	agent_runnoder   rN   rN   rO   rw      sB   7
((c                C     d S ru   rN   rv   rN   rN   rO   run_sync      zAbstractAgent.run_syncc                C  r   ru   rN   rv   rN   rN   rO   r     r   c                C  sL   |r| j du r| t  t | j|||||||||	|
d|||dS )a  Synchronously run the agent with a user prompt.

        This is a convenience method that wraps [`self.run`][pydantic_ai.agent.AbstractAgent.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')

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

        Args:
            user_prompt: User input to start/continue the conversation.
            output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
                output validators since output validators would expect an argument that matches the agent's output type.
            message_history: History of the conversation so far.
            deferred_tool_results: Optional results for deferred tool calls in the message history.
            model: Optional model to use for this run, required if `model` was not set when creating the agent.
            instructions: Optional additional instructions to use for this run.
            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.
            toolsets: Optional additional toolsets for this run.
            event_stream_handler: Optional handler for events from the model's streaming response and the agent's execution of tools to use for this run.
            builtin_tools: Optional additional builtin tools for this run.

        Returns:
            The result of the run.
        NFr_   )rS   r}   r~   r   r   get_event_looprun_until_completerw   rv   rN   rN   rO   r   !  s(   6NAbstractAsyncContextManager[result.StreamedRunResult[AgentDepsT, OutputDataT]]c                C  r   ru   rN   rv   rN   rN   rO   
run_streamm  r   zAbstractAgent.run_streamQAbstractAsyncContextManager[result.StreamedRunResult[AgentDepsT, RunOutputDataT]]c                C  r   ru   rN   rv   rN   rN   rO   r     r   8AsyncIterator[result.StreamedRunResult[AgentDepsT, Any]]c                 s  |r| j du rt  }r| |j |p| j}d}| j|||||||||	|
d||d4 I dH   j}t|t	j
s>J |}	  j| |r|4 I dH mddfd	d
}|durn|t	|I dH  n|2 z3 dH W }qr6 durtdjj|rtdd}jj d fdd}tjj|V  	 W d  I dH  nW d  I dH  n1 I dH sw   Y  n7| |r|dur| j4 I dH |t	 jI dH  W d  I dH  n1 I dH sw   Y   |I dH }t|tr& jdur&tjjjj jdV  d}nt|t	js2tdtt	jt t f |}qAW d  I dH  n1 I dH sNw   Y  |s[tddS )a  Run the agent with a user prompt in async streaming mode.

        This method builds an internal agent graph (using system prompts, tools and output schemas) and then
        runs the graph until the model produces output matching the `output_type`, for example text or structured data.
        At this point, a streaming run result object is yielded from which you can stream the output as it comes in,
        and -- once this output has completed streaming -- get the complete output, message history, and usage.

        As this method will consider the first output matching the `output_type` to be the final output,
        it will stop running the agent graph and will not execute any tool calls made by the model after this "final" output.
        If you want to always run the agent graph to completion and stream events and output at the same time,
        use [`agent.run()`][pydantic_ai.agent.AbstractAgent.run] with an `event_stream_handler` or [`agent.iter()`][pydantic_ai.agent.AbstractAgent.iter] instead.

        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_output())
                #> The capital of the UK is London.
        ```

        Args:
            user_prompt: User input to start/continue the conversation.
            output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
                output validators since output validators would expect an argument that matches the agent's output type.
            message_history: History of the conversation so far.
            deferred_tool_results: Optional results for deferred tool calls in the message history.
            model: Optional model to use for this run, required if `model` was not set when creating the agent.
            instructions: Optional additional instructions to use for this run.
            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.
            toolsets: Optional additional toolsets for this run.
            builtin_tools: Optional additional builtin tools for this run.
            event_stream_handler: Optional handler for events from the model's streaming response and the agent's execution of tools to use for this run.
                It will receive all the events up until the final result is found, which you can then read or stream from inside the context manager.
                Note that it does _not_ receive any events after the final result is found.

        Returns:
            The result of the run.
        NF)rZ   r`   ra   rP   rc   rb   rd   re   r"   rf   r^   rg   Tr   r'   rG   1AsyncIterator[_messages.ModelResponseStreamEvent]c                  s6   | 2 z3 d H W }|V  t |tjr|  d S q6 d S ru   )
isinstance	_messagesFinalResultEvent)r   event)final_result_eventrN   rO   stream_to_final  s   z1AbstractAgent.run_stream.<locals>.stream_to_finalz Agent run produced final resultsrV   c                    s   t  I dH jjg } tjjjjj	d| d2 z3 dH W }q6 | r5
tj| jjd  tI dH  dS )zCalled when the stream has completed.

                                The model response will have been added to messages by now
                                by `StreamedRunResult._marked_completed`.
                                N)tool_manager
tool_callstool_call_resultsfinal_resultr   output_parts)run_id)r(   
get_output	tool_nametool_call_idr   process_tool_callsrc   r   responser   appendr   ModelRequeststater   nextSetFinalResult)parts_event)r   r   	graph_ctxr   r   rN   rO   on_complete  s$   z-AbstractAgent.run_stream.<locals>.on_complete)
run_resultz<Should have produced a StreamedRunResult before getting herez3Agent run finished without producing a final result)r   r'   rG   r   )rG   rV   )!rS   r~   r   r}   f_backr\   r   	next_noder   r   UserPromptNoder   r   r   r   r(   r   r   r   AgentRunErrorr   r`   copyr)   rc   new_message_indexr   r   r   r!   	AgentNoder   r   )rM   rh   rZ   r`   ra   rP   rb   rc   rd   re   r"   rf   r^   rg   r\   frameyielded
first_noder   r   _r   r   rN   )r   r   r   r   r   r   rO   r     s   A




$(J(*u
rZ   r`   ra   rP   rc   rd   re   r"   rf   r^   rg   r\   5result.StreamedRunResultSync[AgentDepsT, OutputDataT]c                C  r   ru   rN   rM   rh   rZ   r`   ra   rP   rc   rd   re   r"   rf   r^   rg   r\   rN   rN   rO   run_stream_syncV     zAbstractAgent.run_stream_sync)r`   ra   rP   rc   rd   re   r"   rf   r^   rg   r\   8result.StreamedRunResultSync[AgentDepsT, RunOutputDataT]c                C  r   ru   rN   r   rN   rN   rO   r   i  r   -result.StreamedRunResultSync[AgentDepsT, Any]c                  s`   r	j du r	t   	
fdd}t t| }t	|S )a  Run the agent with a user prompt in sync streaming mode.

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

        This method builds an internal agent graph (using system prompts, tools and output schemas) and then
        runs the graph until the model produces output matching the `output_type`, for example text or structured data.
        At this point, a streaming run result object is yielded from which you can stream the output as it comes in,
        and -- once this output has completed streaming -- get the complete output, message history, and usage.

        As this method will consider the first output matching the `output_type` to be the final output,
        it will stop running the agent graph and will not execute any tool calls made by the model after this "final" output.
        If you want to always run the agent graph to completion and stream events and output at the same time,
        use [`agent.run()`][pydantic_ai.agent.AbstractAgent.run] with an `event_stream_handler` or [`agent.iter()`][pydantic_ai.agent.AbstractAgent.iter] instead.

        Example:
        ```python
        from pydantic_ai import Agent

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

        def main():
            response = agent.run_stream_sync('What is the capital of the UK?')
            print(response.get_output())
            #> The capital of the UK is London.
        ```

        Args:
            user_prompt: User input to start/continue the conversation.
            output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
                output validators since output validators would expect an argument that matches the agent's output type.
            message_history: History of the conversation so far.
            deferred_tool_results: Optional results for deferred tool calls in the message history.
            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.
            toolsets: Optional additional toolsets for this run.
            builtin_tools: Optional additional builtin tools for this run.
            event_stream_handler: Optional handler for events from the model's streaming response and the agent's execution of tools to use for this run.
                It will receive all the events up until the final result is found, which you can then read or stream from inside the context manager.
                Note that it does _not_ receive any events after the final result is found.

        Returns:
            The result of the run.
        Nc                   sf   	j 
 d4 I d H } | V  W d   I d H  d S 1 I d H s,w   Y  d S )Nr   )r   )stream_resultrg   ra   rc   r\   rf   r`   rP   rd   rZ   rM   r^   r"   re   rh   rN   rO   _consume_stream  s&   .z6AbstractAgent.run_stream_sync.<locals>._consume_stream)
rS   r}   r~   r   r   r   r   anextr!   StreamedRunResultSync)rM   rh   rZ   r`   ra   rP   rc   rd   re   r"   rf   r^   rg   r\   r   async_resultrN   r   rO   r   |  s
   A&
)rZ   r`   ra   rP   rb   rc   rd   re   r"   rf   r^   rg   LAsyncIterator[_messages.AgentStreamEvent | AgentRunResultEvent[OutputDataT]]c                C  r   ru   rN   rM   rh   rZ   r`   ra   rP   rb   rc   rd   re   r"   rf   r^   rg   rN   rN   rO   run_stream_events  r   zAbstractAgent.run_stream_events)r`   ra   rP   rb   rc   rd   re   r"   rf   r^   rg   OAsyncIterator[_messages.AgentStreamEvent | AgentRunResultEvent[RunOutputDataT]]c                C  r   ru   rN   r   rN   rN   rO   r     r   DAsyncIterator[_messages.AgentStreamEvent | AgentRunResultEvent[Any]]c                C  s>   |r| j du r| t  | j|||||||||	|
||dS )a  Run the agent with a user prompt in async mode and stream events from the run.

        This is a convenience method that wraps [`self.run`][pydantic_ai.agent.AbstractAgent.run] and
        uses the `event_stream_handler` kwarg to get a stream of events from the run.

        Example:
        ```python
        from pydantic_ai import Agent, AgentRunResultEvent, AgentStreamEvent

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

        async def main():
            events: list[AgentStreamEvent | AgentRunResultEvent] = []
            async for event in agent.run_stream_events('What is the capital of France?'):
                events.append(event)
            print(events)
            '''
            [
                PartStartEvent(index=0, part=TextPart(content='The capital of ')),
                FinalResultEvent(tool_name=None, tool_call_id=None),
                PartDeltaEvent(index=0, delta=TextPartDelta(content_delta='France is Paris. ')),
                PartEndEvent(
                    index=0, part=TextPart(content='The capital of France is Paris. ')
                ),
                AgentRunResultEvent(
                    result=AgentRunResult(output='The capital of France is Paris. ')
                ),
            ]
            '''
        ```

        Arguments are the same as for [`self.run`][pydantic_ai.agent.AbstractAgent.run],
        except that `event_stream_handler` is now allowed.

        Args:
            user_prompt: User input to start/continue the conversation.
            output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
                output validators since output validators would expect an argument that matches the agent's output type.
            message_history: History of the conversation so far.
            deferred_tool_results: Optional results for deferred tool calls in the message history.
            model: Optional model to use for this run, required if `model` was not set when creating the agent.
            instructions: Optional additional instructions to use for this run.
            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.
            toolsets: Optional additional toolsets for this run.
            builtin_tools: Optional additional builtin tools for this run.

        Returns:
            An async iterable of stream events `AgentStreamEvent` and finally a `AgentRunResultEvent` with the final
            run result.
        NrZ   r`   ra   rP   rb   rc   rd   re   r"   r^   rg   )rS   r}   r~   r   _run_stream_eventsr   rN   rN   rO   r     s    Gr   c                 s   t jtjtt B   \
}d
fddd 	
fd
d}t| }|4 I d H  |2 z	3 d H W }|V  q96 W d   I d H  n1 I d H sTw   Y  |I d H }t|V  d S )Nr   RunContext[AgentDepsT]events)AsyncIterable[_messages.AgentStreamEvent]rG   rV   c                   s*   |2 z3 d H W }  |I d H  q6 d S ru   )send)r   r   r   )send_streamrN   rO   r\   k  s   z>AbstractAgent._run_stream_events.<locals>.event_stream_handlerr|   c                     sj   
4 I d H ! 	j d dI d H W  d   I d H  S 1 I d H s.w   Y  d S )NFr_   )rw   rN   rg   ra   rc   r\   rb   r`   rP   rd   rZ   rM   r   r^   r"   re   rh   rN   rO   	run_agentq  s&   
0z3AbstractAgent._run_stream_events.<locals>.run_agent)r   r   r   r   rG   rV   )rG   r|   )anyiocreate_memory_object_streamr   AgentStreamEventr,   r   asynciocreate_task)rM   rh   rZ   r`   ra   rP   rb   rc   rd   re   r"   r^   rg   receive_streamr   taskmessager!   rN   r   rO   r   W  s   
*(
z AbstractAgent._run_stream_events>AbstractAsyncContextManager[AgentRun[AgentDepsT, OutputDataT]]c                C  r   ru   rN   r   rN   rN   rO   r     r   zAbstractAgent.iterAAbstractAsyncContextManager[AgentRun[AgentDepsT, RunOutputDataT]]c                C  r   ru   rN   r   rN   rN   rO   r     r   (AsyncIterator[AgentRun[AgentDepsT, Any]]c                C s   t )a  A contextmanager which can be used to iterate over the agent graph's nodes as they are executed.

        This method builds an internal agent graph (using system prompts, tools and output schemas) and then returns an
        `AgentRun` object. The `AgentRun` can be used to async-iterate over the nodes of the graph as they are
        executed. This is the API to use if you want to consume the outputs coming from each LLM model response, or the
        stream of events coming from the execution of tools.

        The `AgentRun` also provides methods to access the full message history, new messages, and usage statistics,
        and the final result of the run once it has completed.

        For more details, see the documentation of `AgentRun`.

        Example:
        ```python
        from pydantic_ai import Agent

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

        async def main():
            nodes = []
            async with agent.iter('What is the capital of France?') as agent_run:
                async for node in agent_run:
                    nodes.append(node)
            print(nodes)
            '''
            [
                UserPromptNode(
                    user_prompt='What is the capital of France?',
                    instructions_functions=[],
                    system_prompts=(),
                    system_prompt_functions=[],
                    system_prompt_dynamic_functions={},
                ),
                ModelRequestNode(
                    request=ModelRequest(
                        parts=[
                            UserPromptPart(
                                content='What is the capital of France?',
                                timestamp=datetime.datetime(...),
                            )
                        ],
                        run_id='...',
                    )
                ),
                CallToolsNode(
                    model_response=ModelResponse(
                        parts=[TextPart(content='The capital of France is Paris.')],
                        usage=RequestUsage(input_tokens=56, output_tokens=7),
                        model_name='gpt-4o',
                        timestamp=datetime.datetime(...),
                        run_id='...',
                    )
                ),
                End(data=FinalResult(output='The capital of France is Paris.')),
            ]
            '''
            print(agent_run.result.output)
            #> The capital of France is Paris.
        ```

        Args:
            user_prompt: User input to start/continue the conversation.
            output_type: Custom output type to use for this run, `output_type` may only be used if the agent has no
                output validators since output validators would expect an argument that matches the agent's output type.
            message_history: History of the conversation so far.
            deferred_tool_results: Optional results for deferred tool calls in the message history.
            model: Optional model to use for this run, required if `model` was not set when creating the agent.
            instructions: Optional additional instructions to use for this run.
            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.
            toolsets: Optional additional toolsets for this run.
            builtin_tools: Optional additional builtin tools for this run.

        Returns:
            The result of the run.
        rJ   r   rN   rN   rO   r     s   b)rS   rc   rP   r^   toolsrb   rS   str | _utils.UnsetAgentDepsT | _utils.Unset9models.Model | models.KnownModelName | str | _utils.Unset4Sequence[AbstractToolset[AgentDepsT]] | _utils.Unsetr   KSequence[Tool[AgentDepsT] | ToolFuncEither[AgentDepsT, ...]] | _utils.Unset'Instructions[AgentDepsT] | _utils.UnsetIterator[None]c                c  s    t )a]  Context manager to temporarily override agent name, dependencies, model, toolsets, tools, or instructions.

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

        Args:
            name: The name to use instead of the name passed to the agent constructor and agent run.
            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.
            toolsets: The toolsets to use instead of the toolsets passed to the agent constructor and agent run.
            tools: The tools to use instead of the tools registered with the agent.
            instructions: The instructions to use instead of the instructions registered with the agent.
        rJ   )rM   rS   rc   rP   r^   r   rb   rN   rN   rO   override  s   zAbstractAgent.overridefunction_frameFrameType | Nonec                 C  s   | j du s	J d|dur@|j }rB|j D ]\}}|| u r%|| _  dS q|j|jkrD|j D ]\}}|| u r?|| _  dS q1dS dS dS dS )zzInfer the agent name from the call frame.

        RunUsage should be `self._infer_name(inspect.currentframe())`.
        NzName already set)rS   r   f_localsitems	f_globals)rM   r   parent_framerS   itemrN   rN   rO   r}   4  s$   
zAbstractAgent._infer_namec                   c  s6    t   dV  W d   dS 1 sw   Y  dS )z/Run tool calls sequentially during the context.N)r#   sequential_tool_callsrN   rN   rN   rO   r   G  s   
"z#AbstractAgent.sequential_tool_callsr   9_agent_graph.AgentNode[T, S] | End[result.FinalResult[S]]+TypeIs[_agent_graph.ModelRequestNode[T, S]]c                 C     t | tjS )zCheck if the node is a `ModelRequestNode`, narrowing the type if it is.

        This method preserves the generic parameters while narrowing the type, unlike a direct call to `isinstance`.
        )r   r   ModelRequestNoder   rN   rN   rO   r   N     z#AbstractAgent.is_model_request_node(TypeIs[_agent_graph.CallToolsNode[T, S]]c                 C  r   )zCheck if the node is a `CallToolsNode`, narrowing the type if it is.

        This method preserves the generic parameters while narrowing the type, unlike a direct call to `isinstance`.
        )r   r   CallToolsNoder   rN   rN   rO   r   X  r   z AbstractAgent.is_call_tools_node)TypeIs[_agent_graph.UserPromptNode[T, S]]c                 C  r   )zCheck if the node is a `UserPromptNode`, narrowing the type if it is.

        This method preserves the generic parameters while narrowing the type, unlike a direct call to `isinstance`.
        )r   r   r   r   rN   rN   rO   is_user_prompt_nodeb  r   z!AbstractAgent.is_user_prompt_node"TypeIs[End[result.FinalResult[S]]]c                 C  s
   t | tS )zCheck if the node is a `End`, narrowing the type if it is.

        This method preserves the generic parameters while narrowing the type, unlike a direct call to `isinstance`.
        )r   r   r   rN   rN   rO   is_end_nodel  s   
zAbstractAgent.is_end_node&AbstractAgent[AgentDepsT, OutputDataT]c                      t ru   rJ   rL   rN   rN   rO   
__aenter__v     zAbstractAgent.__aenter__argsr   bool | Nonec                   r   ru   rJ   )rM   r   rN   rN   rO   	__aexit__z  r   zAbstractAgent.__aexit__F)rZ   r`   ra   rP   rc   rd   re   r"   rf   r^   debugroutes
middlewareexception_handlers
on_startupon_shutdownlifespanOutputSpec[OutputDataT] | NoneUsageLimits | NoneRunUsage | Noner  r  Sequence[BaseRoute] | Noner  Sequence[Middleware] | Noner  %Mapping[Any, ExceptionHandler] | Noner  "Sequence[Callable[[], Any]] | Noner  r  1Lifespan[AGUIApp[AgentDepsT, OutputDataT]] | None AGUIApp[AgentDepsT, OutputDataT]c                C  s   ddl m} |di d| d|d|d|d|d|d	|d
|d|d|	d|
d|d|d|d|d|d|d|S )a  Returns an ASGI application that handles every AG-UI request by running the agent.

        Note that the `deps` will be the same for each request, with the exception of the AG-UI state that's
        injected into the `state` field of a `deps` object that implements the [`StateHandler`][pydantic_ai.ag_ui.StateHandler] protocol.
        To provide different `deps` for each request (e.g. based on the authenticated user),
        use [`pydantic_ai.ag_ui.run_ag_ui`][pydantic_ai.ag_ui.run_ag_ui] or
        [`pydantic_ai.ag_ui.handle_ag_ui_request`][pydantic_ai.ag_ui.handle_ag_ui_request] instead.

        Example:
        ```python
        from pydantic_ai import Agent

        agent = Agent('openai:gpt-4o')
        app = agent.to_ag_ui()
        ```

        The `app` is an ASGI application that can be used with any ASGI server.

        To run the application, you can use the following command:

        ```bash
        uvicorn app:app --host 0.0.0.0 --port 8000
        ```

        See [AG-UI docs](../ui/ag-ui.md) for more information.

        Args:
            output_type: Custom output type to use for this run, `output_type` may only be used if the agent has
                no output validators since output validators would expect an argument that matches the agent's
                output type.
            message_history: History of the conversation so far.
            deferred_tool_results: Optional results for deferred tool calls in the message history.
            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.
            toolsets: Optional additional toolsets for this run.

            debug: Boolean indicating if debug tracebacks should be returned on errors.
            routes: A list of routes to serve incoming HTTP and WebSocket requests.
            middleware: A list of middleware to run for every request. A starlette application will always
                automatically include two middleware classes. `ServerErrorMiddleware` is added as the very
                outermost middleware, to handle any uncaught errors occurring anywhere in the entire stack.
                `ExceptionMiddleware` is added as the very innermost middleware, to deal with handled
                exception cases occurring in the routing or endpoints.
            exception_handlers: A mapping of either integer status codes, or exception class types onto
                callables which handle the exceptions. Exception handler callables should be of the form
                `handler(request, exc) -> response` and may be either standard functions, or async functions.
            on_startup: A list of callables to run on application startup. Startup handler callables do not
                take any arguments, and may be either standard functions, or async functions.
            on_shutdown: A list of callables to run on application shutdown. Shutdown handler callables do
                not take any arguments, and may be either standard functions, or async functions.
            lifespan: A lifespan context function, which can be used to perform startup and shutdown tasks.
                This is a newer style that replaces the `on_startup` and `on_shutdown` handlers. Use one or
                the other, not both.

        Returns:
            An ASGI application for running Pydantic AI agents with AG-UI protocol support.
        r   r@   agentrZ   r`   ra   rP   rc   rd   re   r"   rf   r^   r  r  r  r  r  r  r  NrN   )pydantic_ai.ui.ag_ui.apprA   )rM   rZ   r`   ra   rP   rc   rd   re   r"   rf   r^   r  r  r  r  r  r  r  rA   rN   rN   rO   to_ag_ui  sL   T	
zAbstractAgent.to_ag_uizhttp://localhost:8000z1.0.0storagebrokerrS   urlversiondescriptionproviderskillsr  r  r  r  r  r  Storage | Noner  Broker | Noner  strr  r  r  AgentProvider | Noner  list[Skill] | NoneSequence[Route] | None"dict[Any, ExceptionHandler] | NoneLifespan[FastA2A] | Noner6   c                C  s0   ddl m} || |||||||||	|
|||dS )a  Convert the agent to a FastA2A application.

        Example:
        ```python
        from pydantic_ai import Agent

        agent = Agent('openai:gpt-4o')
        app = agent.to_a2a()
        ```

        The `app` is an ASGI application that can be used with any ASGI server.

        To run the application, you can use the following command:

        ```bash
        uvicorn app:app --host 0.0.0.0 --port 8000
        ```
        r   )agent_to_a2ar  )_a2ar%  )rM   r  r  rS   r  r  r  r  r  r  r  r  r  r  r%  rN   rN   rO   to_a2a  s"   %zAbstractAgent.to_a2apydantic-airM   r   	prog_namec              	     s<   ddl m} ddlm} |d| || d||dI dH  dS )a%  Run the agent in a CLI chat interface.

        Args:
            deps: The dependencies to pass to the agent.
            prog_name: The name of the program to use for the CLI. Defaults to 'pydantic-ai'.
            message_history: History of the conversation so far.

        Example:
        ```python {title="agent_to_cli.py" test="skip"}
        from pydantic_ai import Agent

        agent = Agent('openai:gpt-4o', instructions='You always respond in Italian.')

        async def main():
            await agent.to_cli()
        ```
        r   )Console)run_chatTmonokai)r   r  rc   console
code_themer)  r`   N)rich.consoler*  pydantic_ai._clir+  )rM   rc   r)  r`   r*  r+  rN   rN   rO   to_cli$  s   zAbstractAgent.to_clic                 C  s   t  | j|||dS )aG  Run the agent in a CLI chat interface with the non-async interface.

        Args:
            deps: The dependencies to pass to the agent.
            prog_name: The name of the program to use for the CLI. Defaults to 'pydantic-ai'.
            message_history: History of the conversation so far.

        ```python {title="agent_to_cli_sync.py" test="skip"}
        from pydantic_ai import Agent

        agent = Agent('openai:gpt-4o', instructions='You always respond in Italian.')
        agent.to_cli_sync()
        agent.to_cli_sync(prog_name='assistant')
        ```
        )rc   r)  r`   )r   r   r   r1  )rM   rc   r)  r`   rN   rN   rO   to_cli_syncI  s   zAbstractAgent.to_cli_sync)rG   rH   )rG   rR   )rU   rR   rG   rV   )rG   rW   )rG   rY   )rG   r[   )rG   r]   ru   )rh   ri   rZ   rV   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   r\   r[   rG   rs   )rh   ri   rZ   ry   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   r\   r[   rG   rz   )rh   ri   rZ   r{   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   r\   r[   rG   r|   )rh   ri   rZ   rV   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   r\   r[   rG   r   )rh   ri   rZ   ry   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   r\   r[   rG   r   )rh   ri   rZ   r{   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   r\   r[   rG   r   )rh   ri   rZ   rV   r`   rj   ra   rk   rP   rH   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   r\   r[   rG   r   )rh   ri   rZ   ry   r`   rj   ra   rk   rP   rH   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   r\   r[   rG   r   )rh   ri   rZ   r{   r`   rj   ra   rk   rP   rH   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   r\   r[   rG   r   )rh   ri   rZ   rV   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   rG   r   )rh   ri   rZ   ry   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   rG   r   )rh   ri   rZ   r{   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   rG   r   )rh   ri   rZ   r{   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   r^   rq   rg   rr   rG   r   )rh   ri   rZ   rV   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   rG   r   )rh   ri   rZ   ry   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   rG   r   )rh   ri   rZ   r{   r`   rj   ra   rk   rP   rH   rb   rl   rc   r.   rd   rm   re   rn   r"   ro   rf   rp   r^   rq   rg   rr   rG   r   )rS   r   rc   r   rP   r   r^   r   r   r   rb   r   rG   r   )r   r   rG   rV   )rG   r   )r   r   rG   r   )r   r   rG   r   )r   r   rG   r   )r   r   rG   r   )rG   r   )r   r   rG   r   )$rZ   r	  r`   rj   ra   rk   rP   rH   rc   r.   rd   rm   re   r
  r"   r  rf   rp   r^   rq   r  rp   r  r  r  r  r  r  r  r  r  r  r  r  rG   r  )r  r  r  r  rS   rR   r  r  r  r  r  rR   r  r   r  r!  r  rp   r  r"  r  r  r  r#  r  r$  rG   r6   )Nr(  N)
rM   r   rc   r.   r)  r  r`   rj   rG   rV   )'__name__
__module____qualname____doc__propertyr   rP   rS   setterrX   rZ   r\   r^   r   rw   r   r   r   r   r   r   r   r   r   UNSETr   r}   staticmethodr   r   r   r   r   r   r  r  r'  r1  r2  rN   rN   rN   rO   rF   J   s   TL AY^6c
				p:'rF   )h
__future__r   _annotationsr   r~   abcr   r   collections.abcr   r   r   r   r	   r
   r   
contextlibr   r   r   typesr   typingr   r   r   r   r   r   r   typing_extensionsr   r   r   pydantic_graphr    r   r   r   r   r   r   r    r!   r"   _usage_tool_managerr#   rg   r$   outputr%   r&   r'   r(   r)   rw   r*   r+   r,   settingsr-   r   r.   r/   r0   r1   r2   r^   r3   r4   r5   fasta2a.applicationsr6   fasta2a.brokerr7   fasta2a.schemar8   r9   fasta2a.storager:   starlette.middlewarer;   starlette.routingr<   r=   starlette.typesr>   r?   r  rA   rB   rC   rW   NoneTyperD   r   rE   __annotations__r  SystemPromptFuncInstructionsrF   rN   rN   rN   rO   <module>   s`    $ (
