o
    iC                     @  s  d dl mZ d dlmZmZ d dlmZmZ d dlm	Z	m
Z
mZ d dlmZ 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mZmZ d d	lmZmZ d d
lmZ d dl m!Z! d dl"m#Z# d dl$m%Z% d dl&m'Z' d dl(m)Z)m*Z* d dl+m,Z,m-Z- d dl.m/Z/ d dl0m1Z1 d dl2m3Z3 d dl4m5Z5m6Z6 ddl7m8Z8m9Z9m:Z: erd dl;m<Z< d dl=m>Z>m?Z? g dZ@edZA	 edZB	 edZC	 ededZD	 eG dd  d eZEeG d!d" d"eeD ZFeG d#d$ d$eeeAeBeCe1e,f ZGd%S )&    )annotations)ABCabstractmethod)AsyncIteratorSequence)KW_ONLYField	dataclass)cached_property)
HTTPStatus)TYPE_CHECKINGAnyClassVarGenericProtocolTypeVarruntime_checkable)	BaseModelValidationError)DeferredToolRequestsDeferredToolResults)AbstractAgent)Instructions)AbstractBuiltinTool)	UserError)ModelMessage)KnownModelNameModel)OutputDataT
OutputSpec)ModelSettings)
AgentDepsT)AbstractToolset)RunUsageUsageLimits   )NativeEventOnCompleteFuncUIEventStream)Request)ResponseStreamingResponse)	UIAdapterStateHandler	StateDeps	RunInputTMessageTEventTStateT)boundc                   @  s8   e Zd ZU dZded< edddZejdd
dZdS )r-   zeProtocol for state handlers in agent runs. Requires the class to be a dataclass with a `state` field.zClassVar[dict[str, Field[Any]]]__dataclass_fields__returnr   c                 C     dS )z'Get the current state of the agent run.N selfr7   r7   ]/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/ui/_adapter.pystateE      zStateHandler.stater;   Nonec                 C  r6   )zSet the state of the agent run.

        This method is called to update the state of the agent run with the
        provided state.

        Args:
            state: The run state.
        Nr7   )r9   r;   r7   r7   r:   r;   J   s   
N)r5   r   )r;   r   r5   r=   )__name__
__module____qualname____doc____annotations__propertyr;   setterr7   r7   r7   r:   r-   =   s   
 r-   c                   @  s   e Zd ZU dZded< dS )r.   ah  Dependency type that holds state.

    This class is used to manage the state of an agent run. It allows setting
    the state of the agent run with a specific type of state model, which must
    be a subclass of `BaseModel`.

    The state is set using the `state` setter by the `Adapter` when the run starts.

    Implements the `StateHandler` protocol.
    r2   r;   N)r>   r?   r@   rA   rB   r7   r7   r7   r:   r.   W   s   
 r.   c                   @  sF  e Zd ZU dZded< 	 ded< 	 ded< dZd	ed
< 	 edUddZeedVddZ	eedWddZ
edXddZeedYddZedZd d!Zed[d#d$Z	d\d]d*d+Zd^d-d.Zd_d0d1Zdddddddddd2ddd3d`dLdMZdddddddddd2ddddNdadOdPZedddddddddd2ddddQdbdSdTZdS )cr,   a  Base class for UI adapters.

    This class is responsible for transforming agent run input received from the frontend into arguments for [`Agent.run_stream_events()`][pydantic_ai.Agent.run_stream_events], running the agent, and then transforming Pydantic AI events into protocol-specific events.

    The event stream transformation is handled by a protocol-specific [`UIEventStream`][pydantic_ai.ui.UIEventStream] subclass.
    &AbstractAgent[AgentDepsT, OutputDataT]agentr/   	run_inputr   _Nz
str | Noneacceptrequestr)   r5   ?UIAdapter[RunInputT, MessageT, EventT, AgentDepsT, OutputDataT]c                  s(   | ||  | I dH |jddS )z!Create an adapter from a request.NrI   )rF   rG   rI   )build_run_inputbodyheadersget)clsrJ   rF   r7   r7   r:   from_request{   s   
zUIAdapter.from_requestrM   bytesc                 C     t )zABuild a protocol-specific run input object from the request body.NotImplementedError)rP   rM   r7   r7   r:   rL         zUIAdapter.build_run_inputmessagesSequence[MessageT]list[ModelMessage]c                 C  rS   )z?Transform protocol-specific messages into Pydantic AI messages.rT   )rP   rW   r7   r7   r:   load_messages   rV   zUIAdapter.load_messages9UIEventStream[RunInputT, EventT, AgentDepsT, OutputDataT]c                 C  rS   )z3Build a protocol-specific event stream transformer.rT   r8   r7   r7   r:   build_event_stream   r<   zUIAdapter.build_event_streamc                 C  rS   )z:Pydantic AI messages from the protocol-specific run input.rT   r8   r7   r7   r:   rW      rV   zUIAdapter.messages"AbstractToolset[AgentDepsT] | Nonec                 C  r6   )zIToolset representing frontend tools from the protocol-specific run input.Nr7   r8   r7   r7   r:   toolset   r<   zUIAdapter.toolsetdict[str, Any] | Nonec                 C  r6   )z4Frontend state from the protocol-specific run input.Nr7   r8   r7   r7   r:   r;      r<   zUIAdapter.statestreamAsyncIterator[NativeEvent]on_completeOnCompleteFunc[EventT] | NoneAsyncIterator[EventT]c                 C  s   |   j||dS )a  Transform a stream of Pydantic AI events into protocol-specific events.

        Args:
            stream: The stream of Pydantic AI events to transform.
            on_complete: Optional callback function called when the agent run completes successfully.
                The callback receives the completed [`AgentRunResult`][pydantic_ai.agent.AgentRunResult] and can optionally yield additional protocol-specific events.
        rb   )r\   transform_stream)r9   r`   rb   r7   r7   r:   rf      s   zUIAdapter.transform_streamAsyncIterator[str]c                 C     |   |S )zEncode a stream of protocol-specific events as strings according to the `Accept` header value.

        Args:
            stream: The stream of protocol-specific events to encode.
        )r\   encode_streamr9   r`   r7   r7   r:   ri         zUIAdapter.encode_streamr+   c                 C  rh   )zGenerate a streaming response from a stream of protocol-specific events.

        Args:
            stream: The stream of protocol-specific events to encode.
        )r\   streaming_responserj   r7   r7   r:   rl      rk   zUIAdapter.streaming_responseToutput_typemessage_historydeferred_tool_resultsmodelinstructionsdepsmodel_settingsusage_limitsusage
infer_nametoolsetsbuiltin_toolsrn   OutputSpec[Any] | Nonero   Sequence[ModelMessage] | Nonerp   DeferredToolResults | Nonerq   #Model | KnownModelName | str | Nonerr   Instructions[AgentDepsT]rs   r!   rt   ModelSettings | Noneru   UsageLimits | Nonerv   RunUsage | Nonerw   boolrx   ,Sequence[AbstractToolset[AgentDepsT]] | Nonery   $Sequence[AbstractBuiltinTool] | Nonec                C  s   g |pg | j }| j}|r|p| jjtg}g |pg |}t|tr=| jp'i }t|jtr7t	|j
|}n|}||_n| jrKtdt	|j d| jj|||||||||	|
||dS )a  Run the agent with the protocol-specific run input and stream Pydantic AI events.

        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.
            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 to use for this run.
        z&State is provided but `deps` of type `zo` does not implement the `StateHandler` protocol: it needs to be a dataclass with a non-optional `state` field.)rn   ro   rp   rq   rs   rt   rr   ru   rv   rw   rx   ry   )rW   r^   rF   rn   r   
isinstancer-   r;   r   typemodel_validater   r>   run_stream_events)r9   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   r^   	raw_stater;   r7   r7   r:   run_stream_native   s:   !

zUIAdapter.run_stream_native)rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rb   c                C  s,   | j | j|||||||||	|
||d|dS )a  Run the agent with the protocol-specific run input and stream protocol-specific events.

        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.
            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 to use for this run.
            on_complete: Optional callback function called when the agent run completes successfully.
                The callback receives the completed [`AgentRunResult`][pydantic_ai.agent.AgentRunResult] and can optionally yield additional protocol-specific events.
        rm   re   )rf   r   )r9   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rb   r7   r7   r:   
run_stream	  s"   $zUIAdapter.run_stream)ro   rp   rq   rr   rs   rn   rt   ru   rv   rw   rx   ry   rb   r*   c                  s   zddl m} W n ty } ztd|d}~ww z| j||dI dH }W n tyC } z|| dtjdW  Y d}~S d}~ww ||j	|||||||	|
|||||dS )	a"  Handle a protocol-specific HTTP request by running the agent and returning a streaming response of protocol-specific events.

        Args:
            request: The incoming Starlette/FastAPI request.
            agent: The agent to run.
            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 to use for this run.
            on_complete: Optional callback function called when the agent run completes successfully.
                The callback receives the completed [`AgentRunResult`][pydantic_ai.agent.AgentRunResult] and can optionally yield additional protocol-specific events.

        Returns:
            A streaming Starlette response with protocol-specific events encoded per the request's `Accept` header value.
        r   )r*   u   Please install the `starlette` package to use `dispatch_request()` method, you can use the `ui` optional group — `pip install "pydantic-ai-slim[ui]"`N)rF   zapplication/json)content
media_typestatus_code)ro   rp   rs   rn   rq   rr   rt   ru   rv   rw   rx   ry   rb   )
starlette.responsesr*   ImportErrorrQ   r   jsonr   UNPROCESSABLE_ENTITYrl   r   )rP   rJ   rF   ro   rp   rq   rr   rs   rn   rt   ru   rv   rw   rx   ry   rb   r*   eadapterr7   r7   r:   dispatch_request?  sL   ,zUIAdapter.dispatch_request)rJ   r)   rF   rE   r5   rK   )rM   rR   r5   r/   )rW   rX   r5   rY   )r5   r[   )r5   rY   )r5   r]   )r5   r_   )N)r`   ra   rb   rc   r5   rd   )r`   rd   r5   rg   )r`   rd   r5   r+   )rn   rz   ro   r{   rp   r|   rq   r}   rr   r~   rs   r!   rt   r   ru   r   rv   r   rw   r   rx   r   ry   r   r5   ra   )rn   rz   ro   r{   rp   r|   rq   r}   rr   r~   rs   r!   rt   r   ru   r   rv   r   rw   r   rx   r   ry   r   rb   rc   r5   rd   ) rJ   r)   rF   rE   ro   r{   rp   r|   rq   r}   rr   r~   rs   r!   rn   rz   rt   r   ru   r   rv   r   rw   r   rx   r   ry   r   rb   rc   r5   r*   )r>   r?   r@   rA   rB   rI   classmethodrQ   r   rL   rZ   r\   r
   rW   r^   r;   rf   ri   rl   r   r   r   r7   r7   r7   r:   r,   g   s   
 


G6r,   N)H
__future__r   abcr   r   collections.abcr   r   dataclassesr   r   r	   	functoolsr
   httpr   typingr   r   r   r   r   r   r   pydanticr   r   pydantic_air   r   pydantic_ai.agentr   pydantic_ai.agent.abstractr   pydantic_ai.builtin_toolsr   pydantic_ai.exceptionsr   pydantic_ai.messagesr   pydantic_ai.modelsr   r   pydantic_ai.outputr   r   pydantic_ai.settingsr    pydantic_ai.toolsr!   pydantic_ai.toolsetsr"   pydantic_ai.usager#   r$   _event_streamr&   r'   r(   starlette.requestsr)   r   r*   r+   __all__r/   r0   r1   r2   r-   r.   r,   r7   r7   r7   r:   <module>   sN    $
&