
    ilC                    <   S SK Jr  S SKrS SKrS SKJrJr  S SKJr  S SK	J
r
  S SKJr  \(       a  SSKJr  SS	KJrJr  SS
KJrJrJr  SSKJrJrJrJrJr  SSKJr  SSKJr  SSKJ r   SSK!J"r"J#r#  \" \$5      r%\RL                  " 5       r' " S S\(5      r) " S S\)S9r*g)    )annotationsN)AnyTuple)get_dispatcher)ValidationError)TYPE_CHECKING   Context)
StepConfigStepFunction)WorkflowConfigurationErrorWorkflowRuntimeErrorWorkflowValidationError)EventHumanResponseEventInputRequiredEvent
StartEvent	StopEvent)WorkflowHandler)ResourceManager)
RunResultT)get_steps_from_classget_steps_from_instancec                  ,   ^  \ rS rSrSU 4S jjrSrU =r$ )WorkflowMeta*   c                4   > [         TU ]  XU5        0 U l        g N)super__init___step_functions)clsnamebasesdct	__class__s       L/home/james-whalen/.local/lib/python3.13/site-packages/workflows/workflow.pyr!   WorkflowMeta.__init__+   s    c*79     )r$   strr%   zTuple[type, ...]r&   zdict[str, Any]returnNone)__name__
__module____qualname____firstlineno__r!   __static_attributes____classcell__)r'   s   @r(   r   r   *   s    : :r*   r   c                  &   \ rS rSrSr     S           SS jjrSS jr\SS j5       r\SS j5       r	SS jr
SS	 jr\SS
 j5       r\SS j5       rSS jr      SS jr\R$                    S       SS jj5       rSS jrSS jrSrg)Workflow0   a  
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]
Nc                @   Xl         X0l        X l        XPl        U R	                  5       U l        U R                  5       U l        U R                  5       U l	        U(       a  [        R                  " U5      OSU l        U=(       d
    [        5       U l        [        U l        g)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!   Workflow.__init__`   s    ,  #5 $7!"&"@"@"B!%!>!>!@4466IG12t 		 "2!F_5F%r*   c                   [        5       nU R                  5       R                  5        HJ  nUR                  nUR                   H+  n[        U[        5      (       d  M  UR                  U5        M-     ML     [        U5      nUS:X  a'  U R                  R                  nSU S3n[        U5      eUS:  a-  U R                  R                  nSU SU SU S3n[        U5      eUR                  5       $ )	zu
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)rI   start_events_found	step_funcstep_config
event_type	num_foundcls_namemsgs           r(   r=   "Workflow._ensure_start_event_class   s     58E*113I&/&<&<K)99
j*55&**:6 : 4 *+	>~~..H&Z'OQ  -S11]~~..HMi[XZ[mZn o  (z-  -S11%))++r*   c                    U R                   $ )zaThe `StartEvent` subclass accepted by this workflow.

Determined by inspecting step input types.
)r>   rI   s    r(   start_event_classWorkflow.start_event_class   s     &&&r*   c                    U R                   $ )fReturns all known events emitted by this workflow.

Determined by inspecting step input/output types.
)rB   rf   s    r(   eventsWorkflow.events   s     ||r*   c                   [        5       nU R                  5       R                  5        H  nUR                  nUR                  S:X  a  M!  UR
                   H+  n[        U[        5      (       d  M  UR                  U5        M-     UR                   H+  n[        U[        5      (       d  M  UR                  U5        M-     M     [        U5      $ )rj   _done)rT   rU   rV   rW   r/   return_typesrY   r   rZ   rX   list)rI   events_foundr^   r_   r`   s        r(   rA   !Workflow._ensure_events_collected   s    
 *-*113I&/&<&<K !!W,)66
j%00 $$Z0 7 *99
j%00 $$Z0 : 4 L!!r*   c                   [        5       nU R                  5       R                  5        HJ  nUR                  nUR                   H+  n[        U[        5      (       d  M  UR                  U5        M-     ML     [        U5      nUS:X  a'  U R                  R                  nSU S3n[        U5      eUS:  a-  U R                  R                  nSU SU SU S3n[        U5      eUR                  5       $ )	z`
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 rQ   rR   rS   )rT   rU   rV   rW   ro   rY   r   rZ   r[   r'   r/   r   r\   )rI   stop_events_foundr^   r_   r`   ra   rb   rc   s           r(   r?   !Workflow._ensure_stop_event_class   s     36%*113I&/&<&<K)66
j)44%))*5 7 4 )*	>~~..H&Z'NP  -S11]~~..HLYKWYZkYl m  (z-  -S11$((**r*   c                    U R                   $ )zgThe `StopEvent` subclass produced by this workflow.

Determined by inspecting step return annotations.
)r@   rf   s    r(   stop_event_classWorkflow.stop_event_class   s     %%%r*   c                   [        USS5      nU(       d  SUR                   S3n[        U5      eUR                  0 [        U 5      EU R                  E;   a  SUR                   S3n[        U5      eXR                  UR                  '   g)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.
rW   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#   funcr_   rc   s       r(   add_step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    0 [        U 5      EU R                  R                  E$ )zDReturns all the steps, whether defined as methods or free functions.)r   r'   r"   rf   s    r(   rU   Workflow._get_steps  s"    R)$/R4>>3Q3QRRr*   c                X   UbE  [        U[        5      (       d  Sn[        U5      eU(       a  SU 3n[        R	                  U5        U$  U R
                  " S0 UD6$ ! [         aC  nU R
                  R                  nSU SU 3n[        R                  U5        [        U5      eS nAff = f)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: r+   )

isinstancer   
ValueErrorloggerwarningr>   r   r/   debugr   )rI   start_eventkwargsrc   eev_names         r(   _get_start_event_instance"Workflow._get_start_event_instance  s     "k:66W o% AAGJ  s#	,**4V44 	,--66G;G9DbcibjkCLLO&s++		,s   
A 
B)&>B$$B)c                    SSK Jn  U R                  5         Ub  UOU" U 5      nUR                  (       a  SOU R                  " U40 UD6nUR                  XU R                  S9$ )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)workflowr   	semaphore)workflows.contextr   	_validate
is_runningr   _workflow_runrE   )rI   ctxr   r   r   start_event_instances         r(   runWorkflow.run#  sn    j 	. 	 _c'$- ~~ //FvF 	
   tyy ! 
 	
r*   c                "    U R                  5       $ )zz
Validate the workflow to ensure it's well-formed.

Returns True if the workflow uses human-in-the-loop, False otherwise.
)r   rf   s    r(   validateWorkflow.validateh  s     ~~r*   c           	        U R                   (       a  gU R                  5       (       d'  U R                  R                  nSU S3n[	        U5      eU R                  5       U l        U R                  5       U l        U R                  1n[        5       n/ nU R                  5       R                  5        H  u  pgUR                  nUS:w  a;  UR                   H+  n	[        U	[        5      (       d  M  UR                  U5          O   UR                   H  n	UR!                  U	5        M     UR"                   H$  n	U	[%        S 5      L a  M  UR!                  U	5        M&     M     U(       a8  SR'                  U5      n
[)        U5      S:X  a  SOSnS	U S
U
 S3n[+        U5      eSnU H  n[        U[        5      (       d  M  Sn  O   U(       d  Sn[+        U5      eXC-
  nU Vs1 s H'  n[        U[,        [.        [        45      (       a  M%  UiM)     nnU(       a&  SR'                  S U 5       5      n[+        SU 35      eX4-
  nU Vs1 s H-  n[        U[,        [.        U R                  45      (       a  M+  UiM/     nnU(       a&  SR'                  S U 5       5      n[+        SU 35      e[,        U;   =(       d	    [.        U;   $ s  snf s  snf )NFz
Workflow 'z' has no configured steps. Did you forget to annotate methods with @step or to register free-function steps via @step(workflow=...)?rn   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  8   #    U  H  oR                   v   M     g 7fr   r/   .0evs     r(   	<genexpr>%Workflow._validate.<locals>.<genexpr>  s     F4Ebkk4E   z6The following events are consumed but never produced: c              3  8   #    U  H  oR                   v   M     g 7fr   r   r   s     r(   r   r     s     BMbkkMr   z6The following events are produced but never consumed: )r;   rU   r'   r/   r   r=   r>   r?   r@   rT   itemsrW   rX   rY   r   appendrZ   ro   typejoinr[   r   r   r   )rI   rb   rc   produced_eventsconsumed_eventssteps_accepting_stop_eventr$   r^   r_   r`   
step_namespluralstop_okr   unconsumed_eventsxnamesunused_eventss                     r(   r   Workflow._validatep  s   ##   ~~..HXJ '? ? 
 -S11 #'"@"@"B!%!>!>!@&*&=&=%>%(U 13"#0668OD&/&<&<K w"-"="=J!*i88299$? #>
 *99
##J/ : *66
d+##J/ 7  9* &%?@J9:a?RSF:,  /X  YC)#.. !B"i(( " ;C)#.. ,= '
&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   $J>J>*K0K)
r;   rH   rB   r<   rF   rE   r>   r@   r9   r:   )g     F@FFNN)rJ   zfloat | NonerK   boolrL   r   rM   zResourceManager | NonerN   z
int | Noner-   r.   )r-   ztype[StartEvent])r-   zlist[type[Event]])r-   ztype[RunResultT])r{   r   r-   r.   )r-   zdict[str, StepFunction])r   StartEvent | Noner   r   r-   r   )NN)r   zContext | Noner   r   r   r   r-   r   )r-   r   )r/   r0   r1   r2   __doc__r!   r=   propertyrg   rk   rA   r?   rw   classmethodr|   rU   r   rG   spanr   r   r   r3   r+   r*   r(   r6   r6   0   s3   -b !%#(37*.$&$& !$& 	$&
 1$& ($& 
$&L,> ' '  ",+> & & 2 2"S,,,8;,	,6 __ #)-B
B
 'B
 	B

 
B
 B
H ^
r*   r6   )	metaclass)+
__future__r   rC   loggingtypingr   r   llama_index_instrumentationr   pydanticr   r   contextr   
decoratorsr   r   errorsr   r   r   rk   r   r   r   r   r   handlerr   resourcer   typesr   utilsr   r   r/   rG   	getLoggerr   r   r   r6   r+   r*   r(   <module>r      s}    #  
 7 $    0 
  % %  @H%
				:4 :^
 ^
r*   