
    JiC                    0   d dl mZ d dlZd dlZd dlmZmZmZ d dlm	Z	 d dl
mZ erddlmZ ddlmZmZ dd	lmZmZmZ dd
lmZmZmZmZmZ ddlmZ ddlmZ ddlm Z  ddl!m"Z"m#Z#  e	e$      Z% ejL                         Z' G d de(      Z) G d de)      Z*y)    )annotationsN)TYPE_CHECKINGAnyTuple)get_dispatcher)ValidationError   Context)
StepConfigStepFunction)WorkflowConfigurationErrorWorkflowRuntimeErrorWorkflowValidationError)EventHumanResponseEventInputRequiredEvent
StartEvent	StopEvent)WorkflowHandler)ResourceManager)
RunResultT)get_steps_from_classget_steps_from_instancec                        e Zd Zd fdZ xZS )WorkflowMetac                6    t         |   |||       i | _        y N)super__init___step_functions)clsnamebasesdct	__class__s       d/var/www/html/BankruptcyAI-uat/bankruptcy-ai/venv/lib/python3.12/site-packages/workflows/workflow.pyr    zWorkflowMeta.__init__*   s    uc*79    )r#   strr$   zTuple[type, ...]r%   zdict[str, Any]returnNone)__name__
__module____qualname__r    __classcell__)r&   s   @r'   r   r   )   s    : :r(   r   c                     e Zd ZU dZded<   	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZedd       Zedd       Z	dd	Z
dd
Zedd       Zedd       ZddZ	 	 	 	 	 	 ddZej$                  	 	 d	 	 	 	 	 	 	 dd       ZddZddZy)Workflowa  
    Event-driven orchestrator to define and run application flows using typed steps.

    A `Workflow` is composed of `@step`-decorated callables that accept and emit
    typed [Event][workflows.events.Event]s. Steps can be declared as instance
    methods or as free functions registered via the decorator.

    Key features:
    - Validation of step signatures and event graph before running
    - Typed start/stop events
    - Streaming of intermediate events
    - Optional human-in-the-loop events
    - Retry policies per step
    - Resource injection

    Examples:
        Basic usage:

        ```python
        from workflows import Workflow, step
        from workflows.events import StartEvent, StopEvent

        class MyFlow(Workflow):
            @step
            async def start(self, ev: StartEvent) -> StopEvent:
                return StopEvent(result="done")

        result = await MyFlow(timeout=60).run(topic="Pirates")
        ```

        Custom start/stop events and streaming:

        ```python
        handler = MyFlow().run()
        async for ev in handler.stream_events():
            ...
        result = await handler
        ```

    See Also:
        - [step][workflows.decorators.step]
        - [Event][workflows.events.Event]
        - [Context][workflows.context.context.Context]
        - [WorkflowHandler][workflows.handler.WorkflowHandler]
        - [RetryPolicy][workflows.retry_policy.RetryPolicy]
    dict[str, StepFunction]r!   Nc                2   || _         || _        || _        || _        | j	                         | _        | j                         | _        | j                         | _	        |rt        j                  |      nd| _        |xs
 t               | _        t        | _        y)a.  
        Initialize a workflow instance.

        Args:
            timeout (float | None): Max seconds to wait for completion. `None`
                disables the timeout.
            disable_validation (bool): Skip pre-run validation of the event graph
                (not recommended).
            verbose (bool): If True, print step activity.
            resource_manager (ResourceManager | None): Custom resource manager
                for dependency injection.
            num_concurrent_runs (int | None): Limit on concurrent `run()` calls.
        N)_timeout_verbose_disable_validation_num_concurrent_runs_ensure_start_event_class_start_event_class_ensure_stop_event_class_stop_event_class_ensure_events_collected_eventsasyncio	Semaphore_semr   _resource_manager
dispatcher_dispatcher)selftimeoutdisable_validationverboseresource_managernum_concurrent_runss         r'   r    zWorkflow.__init__b   s    ,  #5 $7!"&"@"@"B!%!>!>!@4466IG12t 		 "2!F_5F%r(   c                   t               }| j                         j                         D ]A  }|j                  }|j                  D ]$  }t        |t              s|j                  |       & C t        |      }|dk(  r'| j                  j                  }d| d}t        |      |dkD  r-| j                  j                  }d| d| d| d}t        |      |j                         S )	z
        Returns the StartEvent type used in this workflow.

        It works by inspecting the events received by the step methods.
        r   zOAt least one Event of type StartEvent must be received by any step. (Workflow 'z(' has no @step that accepts StartEvent.)r	   z;Only one type of StartEvent is allowed per workflow, found :  in workflow ''.)set
_get_stepsvalues_step_configaccepted_events
issubclassr   addlenr&   r,   r   pop)rD   start_events_found	step_funcstep_config
event_type	num_foundcls_namemsgs           r'   r8   z"Workflow._ensure_start_event_class   s    58E*113 	7I&/&<&<K)99 7
j*5&**:67	7 *+	>~~..H&Z'OQ  -S11]~~..HMi[XZ[mZn o  (z-  -S11%))++r(   c                    | j                   S )zqThe `StartEvent` subclass accepted by this workflow.

        Determined by inspecting step input types.
        )r9   rD   s    r'   start_event_classzWorkflow.start_event_class   s     &&&r(   c                    | j                   S )vReturns all known events emitted by this workflow.

        Determined by inspecting step input/output types.
        )r=   r_   s    r'   eventszWorkflow.events   s     ||r(   c                v   t               }| j                         j                         D ]  }|j                  }|j                  dk(  r|j
                  D ]$  }t        |t              s|j                  |       & |j                  D ]$  }t        |t              s|j                  |       &  t        |      S )rb   _done)rN   rO   rP   rQ   r,   return_typesrS   r   rT   rR   list)rD   events_foundrX   rY   rZ   s        r'   r<   z!Workflow._ensure_events_collected   s    
 *-*113 	1I&/&<&<K !!W,)66 1
j%0 $$Z01 *99 1
j%0 $$Z01	1 L!!r(   c                   t               }| j                         j                         D ]A  }|j                  }|j                  D ]$  }t        |t              s|j                  |       & C t        |      }|dk(  r'| j                  j                  }d| d}t        |      |dkD  r-| j                  j                  }d| d| d| d}t        |      |j                         S )	zx
        Returns the StopEvent type used in this workflow.

        It works by inspecting the events returned.
        r   zNAt least one Event of type StopEvent must be returned by any step. (Workflow 'z'' has no @step that returns StopEvent.)r	   z:Only one type of StopEvent is allowed per workflow, found rK   rL   rM   )rN   rO   rP   rQ   rf   rS   r   rT   rU   r&   r,   r   rV   )rD   stop_events_foundrX   rY   rZ   r[   r\   r]   s           r'   r:   z!Workflow._ensure_stop_event_class   s    36%*113 	6I&/&<&<K)66 6
j)4%))*56	6 )*	>~~..H&Z'NP  -S11]~~..HLYKWYZkYl m  (z-  -S11$((**r(   c                    | j                   S )zwThe `StopEvent` subclass produced by this workflow.

        Determined by inspecting step return annotations.
        )r;   r_   s    r'   stop_event_classzWorkflow.stop_event_class   s     %%%r(   c                
   t        |dd      }|sd|j                   d}t        |      |j                  i t        |       | j                  v rd|j                   d}t        |      || j                  |j                  <   y)z
        Adds a free function as step for this workflow instance.

        It raises an exception if a step with the same name was already added to the workflow.
        rQ   NzStep function z" is missing the `@step` decorator.zA step z> is already part of this workflow, please choose another name.)getattrr,   r   r   r!   )r"   funcrY   r]   s       r'   add_stepzWorkflow.add_step   s     *1~t)L"4==/1STC)#..==P3C8PC<O<OPPDMM?*hiC)#..-1DMM*r(   c                H    i t        |       | j                  j                  S )zDReturns all the steps, whether defined as methods or free functions.)r   r&   r!   r_   s    r'   rO   zWorkflow._get_steps  s"    R)$/R4>>3Q3QRRr(   c                @   |;t        |t              sd}t        |      |rd| }t        j	                  |       |S 	  | j
                  di |S # t        $ rC}| j
                  j                  }d| d| }t        j                  |       t        |      d }~ww xY w)Nz?The 'start_event' argument must be an instance of 'StartEvent'.zKeyword arguments are not supported when 'run()' is invoked with the 'start_event' parameter. These keyword arguments will be ignored: z'Failed creating a start event of type 'z' with the keyword arguments:  )

isinstancer   
ValueErrorloggerwarningr9   r   r,   debugr   )rD   start_eventkwargsr]   eev_names         r'   _get_start_event_instancez"Workflow._get_start_event_instance
  s     "k:6W o% AAGJ  s#	,*4**4V44 	,--66G;G9DbcibjkCLLO&s++		,s   A 	B>BBc                    ddl m} | j                          ||n ||       }|j                  rdn | j                  |fi |}|j                  | || j                        S )a  Run the workflow and return a handler for results and streaming.

        This schedules the workflow execution in the background and returns a
        [WorkflowHandler][workflows.handler.WorkflowHandler] that can be awaited
        for the final result or used to stream intermediate events.

        You may pass either a concrete `start_event` instance or keyword
        arguments that will be used to construct the inferred
        [StartEvent][workflows.events.StartEvent] subclass.

        Args:
            ctx (Context | None): Optional context to resume or share state
                across runs. If omitted, a fresh context is created.
            start_event (StartEvent | None): Optional explicit start event.
            **kwargs (Any): Keyword args to initialize the start event when
                `start_event` is not provided.

        Returns:
            WorkflowHandler: A future-like object to await the final result and
            stream events.

        Raises:
            WorkflowValidationError: If validation fails and validation is
                enabled.
            WorkflowRuntimeError: If the start event cannot be created from kwargs.
            WorkflowTimeoutError: If execution exceeds the configured timeout.

        Examples:
            ```python
            # Create and run with kwargs
            handler = MyFlow().run(topic="Pirates")

            # Stream events
            async for ev in handler.stream_events():
                ...

            # Await final result
            result = await handler
            ```

            If you subclassed the start event, you can also directly pass it in:

            ```python
            result = await my_workflow.run(start_event=MyStartEvent(topic="Pirates"))
            ```
        r   r
   N)workflowry   	semaphore)workflows.contextr   	_validate
is_runningr}   _workflow_runr@   )rD   ctxry   rz   r   start_event_instances         r'   runzWorkflow.run%  ss    j 	. 	 _c'$- ~~ ///FvF 	
   ';tyy ! 
 	
r(   c                "    | j                         S )z
        Validate the workflow to ensure it's well-formed.

        Returns True if the workflow uses human-in-the-loop, False otherwise.
        )r   r_   s    r'   validatezWorkflow.validatej  s     ~~r(   c           	        | j                   ry| j                         s'| j                  j                  }d| d}t	        |      | j                         | _        | j                         | _        | j                  h}t               }g }| j                         j                         D ]  \  }}|j                  }|dk7  r4|j                  D ]%  }	t        |	t              s|j                  |        n |j                  D ]  }	|j!                  |	        |j"                  D ]!  }	|	t%        d       u r|j!                  |	       #  |r7dj'                  |      }
t)        |      dk(  rdnd}d	| d
|
 d}t+        |      d}|D ]  }t        |t              sd} n |sd}t+        |      ||z
  }|D ch c]  }t        |t,        t.        t        f      s|! }}|r&dj'                  d |D              }t+        d|       ||z
  }|D ch c]%  }t        |t,        t.        | j                  f      s|' }}|r&dj'                  d |D              }t+        d|       t,        |v xs t.        |v S c c}w c c}w )NFz
Workflow 'z' has no configured steps. Did you forget to annotate methods with @step or to register free-function steps via @step(workflow=...)?re   z', 'r	    sStepz 'zi' cannot accept StopEvent. StopEvent signals the end of the workflow. Use a different Event type instead.Tz'No event of type StopEvent is produced.z, c              3  4   K   | ]  }|j                     y wr   r,   .0evs     r'   	<genexpr>z%Workflow._validate.<locals>.<genexpr>  s     FbbkkF   z6The following events are consumed but never produced: c              3  4   K   | ]  }|j                     y wr   r   r   s     r'   r   z%Workflow._validate.<locals>.<genexpr>  s     BbbkkBr   z6The following events are produced but never consumed: )r6   rO   r&   r,   r   r8   r9   r:   r;   rN   itemsrQ   rR   rS   r   appendrT   rf   typejoinrU   r   r   r   )rD   r\   r]   produced_eventsconsumed_eventssteps_accepting_stop_eventr#   rX   rY   rZ   
step_namespluralstop_okr   unconsumed_eventsxnamesunused_eventss                     r'   r   zWorkflow._validater  s   ##  ~~..HXJ '? ? 
 -S11 #'"@"@"B!%!>!>!@&*&=&=%>%(U 13"#0668 	0OD)&/&<&<K w"-"="= J!*i8299$?
 *99 0
##J/0 *66 0
d+##J/0	0* &%?@J9:a?RSF:,  /X  YC)#.. ! 	B"i(	 ;C)#.. ,o= '
a"46H)!TU 
 

 IIF4EFFE)HP 
 (/9 #
&(:D<R<RS 
 
 IIBMBBE)HP  /1 5!_4	
7

s   3$I0
*I5)g     F@FFNN)rE   zfloat | NonerF   boolrG   r   rH   zResourceManager | NonerI   z
int | Noner*   r+   )r*   ztype[StartEvent])r*   zlist[type[Event]])r*   ztype[RunResultT])ro   r   r*   r+   )r*   r2   )ry   StartEvent | Nonerz   r   r*   r   )NN)r   zContext | Nonery   r   rz   r   r*   r   )r*   r   )r,   r-   r.   __doc____annotations__r    r8   propertyr`   rc   r<   r:   rl   classmethodrp   rO   r}   rB   spanr   r   r   rs   r(   r'   r1   r1   /   s;   -` -, !%#(37*.$&$& !$& 	$&
 1$& ($& 
$&L,> ' '  ",+> & & 2 2"S,,,8;,	,6 __ #)-B
B
 'B
 	B

 
B
 B
H ^
r(   r1   )	metaclass)+
__future__r   r>   loggingtypingr   r   r   llama_index_instrumentationr   pydanticr   contextr   
decoratorsr   r   errorsr   r   r   rc   r   r   r   r   r   handlerr   resourcer   typesr   utilsr   r   r,   rB   	getLoggerrv   r   r   r1   rs   r(   r'   <module>r      s    #    7 $  0 
  % %  @H%
				:4 :a
 a
r(   