
    Jih                        d dl 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 ddlmZ erddlmZ  G d	 d
ej"                  e         Zy)    )annotationsN)TYPE_CHECKINGAnyAsyncGenerator   )WorkflowRuntimeError)EventInternalDispatchEvent	StopEvent)
RunResultT)Contextc                       e Zd ZU dZded<   ded<   ded<   ded	<   d
d
d	 	 	 	 	 	 	 	 	 	 	 d fdZedd       ZddZddZ	ddZ
ddZddZ	 d	 	 	 ddZddZ xZS )WorkflowHandlera  
    Handle a running workflow: await results, stream events, access context, or cancel.

    Instances are returned by [Workflow.run][workflows.workflow.Workflow.run].
    They can be awaited for the final result and support streaming intermediate
    events via [stream_events][workflows.handler.WorkflowHandler.stream_events].

    See Also:
        - [Context][workflows.context.context.Context]
        - [StopEvent][workflows.events.StopEvent]
    r   _ctxasyncio.Task[None] | None	_run_taskbool_all_events_consumedStopEvent | None_stop_eventN)run_idrun_taskc               \    t        |   |i | || _        || _        || _        d| _        y )NF)super__init__r   r   r   r   )selfctxr   r   argskwargs	__class__s         c/var/www/html/BankruptcyAI-uat/bankruptcy-ai/venv/lib/python3.12/site-packages/workflows/handler.pyr   zWorkflowHandler.__init__#   s4     	$)&)	!$)!    c                    | j                   S )zGThe workflow [Context][workflows.context.context.Context] for this run.)r   r   s    r!   r   zWorkflowHandler.ctx1   s     yyr"   c                    | j                   S )zThe stop event for this run. Always defined once the future is done. In a future major release, this will be removed, and the result will be the stop event itself.)r   r$   s    r!   get_stop_eventzWorkflowHandler.get_stop_event6   s    r"   c                |   K   | j                          d{    | j                  J d       | j                  S 7 #w)zGet the stop event for this run. Always defined once the future is done. In a future major release, this will be removed, and the result will be the stop event itself.Nz3Stop event must be defined once the future is done.)resultr   r$   s    r!   stop_event_resultz!WorkflowHandler.stop_event_result:   sD     kkm+ 	
A	
+ 	 	s   <:$<c                x    || _         | j                  t        |      t        u r|j                         y |       y N)r   
set_resulttyper   r(   )r   
stop_events     r!   _set_stop_eventzWorkflowHandler._set_stop_eventB   s5    % 	!%j!1Y!>J	
DN	
r"   c                4    t        | j                               S r+   )strr(   r$   s    r!   __str__zWorkflowHandler.__str__K   s    4;;=!!r"   c                "    | j                         S )z,Return True when the workflow has completed.)doner$   s    r!   is_donezWorkflowHandler.is_doneN   s    yy{r"   c                  K   | j                   rd}t        |      | j                  j                         2 3 d{   }t	        |t
              r|s| t	        |t              s2d| _          y7 66 yw)a{  
        Stream events from the workflow execution as they occur.

        This method provides real-time access to events generated during workflow
        execution, allowing for monitoring and processing of intermediate results.
        Events are yielded in the order they are generated by the workflow.

        The stream includes all events written to the context's streaming queue,
        and terminates when a [StopEvent][workflows.events.StopEvent] is
        encountered, indicating the workflow has completed.

        Args:
            expose_internal (bool): Whether to expose internal events.

        Returns:
            AsyncGenerator[Event, None]: An async generator that yields Event objects
                as they are produced by the workflow.

        Raises:
            ValueError: If the context is not set on the handler.
            WorkflowRuntimeError: If all events have already been consumed by a
                previous call to `stream_events()` on the same handler instance.

        Examples:
            ```python
            handler = workflow.run()

            # Stream and process events in real-time
            async for event in handler.stream_events():
                if isinstance(event, StopEvent):
                    print(f"Workflow completed with result: {event.result}")
                else:
                    print(f"Received event: {event}")

            # Get final result
            result = await handler
            ```

        Note:
            Events can only be streamed once per handler instance. Subsequent
            calls to `stream_events()` will raise a WorkflowRuntimeError.
        z3All the streamed events have already been consumed.NT)r   r   r   stream_events
isinstancer
   r   )r   expose_internalmsgevs       r!   r7   zWorkflowHandler.stream_eventsR   sq     ^ $$GC&s++..0 	 	""34_H"i(,0)	0s+   4A5A3A1A3)A5(	A51A33A5c                   K   | j                   r=| j                   j                          | j                  	 | j                   d{    yyy7 # t        $ r Y yw xY ww)aq  Cancel the running workflow.

        Signals the underlying context to raise
        [WorkflowCancelledByUser][workflows.errors.WorkflowCancelledByUser],
        which will be caught by the workflow and gracefully end the run.

        Examples:
            ```python
            handler = workflow.run()
            await handler.cancel_run()
            ```
        N)r   _workflow_cancel_runr   	Exceptionr$   s    r!   
cancel_runzWorkflowHandler.cancel_run   s[      88HH))+~~)..(( *  )  s:   3AA AA 
AA 	AAAA)r   r   r   r   r   z
str | Noner   r   r   r   returnNone)r@   r   )r@   r   )r@   r   )r.   r   r@   rA   )r@   r1   )r@   r   )F)r9   r   r@   zAsyncGenerator[Event, None])r@   rA   )__name__
__module____qualname____doc____annotations__r   propertyr   r&   r)   r/   r2   r5   r7   r?   __classcell__)r    s   @r!   r   r      s    
 M((!! ".2** * 	*
 ,* * 
*    
"
 ',:#:	$:xr"   r   )
__future__r   asynciotypingr   r   r   errorsr   eventsr	   r
   r   typesr   contextr   Futurer    r"   r!   <module>rR      s<    #  5 5 ( ; ;  PgnnZ0 Pr"   