
    g3fia_                         d Z ddl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
mZmZ ddlmZ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mZmZmZmZmZmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z% e
rddlm&Z&  G d dee"e#f         Z'dede(fdZ)dede(fdZ*y)z:Runnable that can fallback to other Runnables if it fails.    N)AsyncIteratorIteratorSequence)wraps)TYPE_CHECKINGAnycast)	BaseModel
ConfigDict)override)AsyncCallbackManagerCallbackManager)RunnableRunnableSerializable)RunnableConfigensure_config%get_async_callback_manager_for_configget_callback_manager_for_configget_config_listpatch_configset_config_context)ConfigurableFieldSpecInputOutputcoro_with_contextget_unique_config_specs)AsyncCallbackManagerForChainRunc                   D   e Zd ZU dZeeef   ed<   	 eeeef      ed<   	 e	fZ
eee   df   ed<   	 dZedz  ed<   	  ed	      Zeed
ee   fd              Zeed
ee   fd              Zed"dedz  d
ee   fd       Ze	 d"dedz  d
ee   fd       Zeed
ee   fd              Zeed
efd              Zeed
ee   fd              Z ed
e!eeef      fd       Z"e	 d"dededz  de#d
efd       Z$e	 d"dededz  de#dz  d
efd       Z%e	 d"dddee   deee   z  dz  dede#dz  d
ee   f
d       Z&e	 d"dddee   deee   z  dz  dede#dz  d
ee   f
d       Z'e	 d"dededz  de#dz  d
e!e   fd       Z(e	 d"dededz  de#dz  d
e)e   fd       Z*d ed
e#fd!Z+y)#RunnableWithFallbacksus  `Runnable` that can fallback to other `Runnable`s if it fails.

    External APIs (e.g., APIs for a language model) may at times experience
    degraded performance or even downtime.

    In these cases, it can be useful to have a fallback `Runnable` that can be
    used in place of the original `Runnable` (e.g., fallback to another LLM provider).

    Fallbacks can be defined at the level of a single `Runnable`, or at the level
    of a chain of `Runnable`s. Fallbacks are tried in order until one succeeds or
    all fail.

    While you can instantiate a `RunnableWithFallbacks` directly, it is usually
    more convenient to use the `with_fallbacks` method on a `Runnable`.

    Example:
        ```python
        from langchain_core.chat_models.openai import ChatOpenAI
        from langchain_core.chat_models.anthropic import ChatAnthropic

        model = ChatAnthropic(model="claude-3-haiku-20240307").with_fallbacks(
            [ChatOpenAI(model="gpt-3.5-turbo-0125")]
        )
        # Will usually use ChatAnthropic, but fallback to ChatOpenAI
        # if ChatAnthropic fails.
        model.invoke("hello")

        # And you can also use fallbacks at the level of a chain.
        # Here if both LLM providers fail, we'll fallback to a good hardcoded
        # response.

        from langchain_core.prompts import PromptTemplate
        from langchain_core.output_parser import StrOutputParser
        from langchain_core.runnables import RunnableLambda


        def when_all_is_lost(inputs):
            return (
                "Looks like our LLM providers are down. "
                "Here's a nice 🦜️ emoji for you instead."
            )


        chain_with_fallback = (
            PromptTemplate.from_template("Tell me a joke about {topic}")
            | model
            | StrOutputParser()
        ).with_fallbacks([RunnableLambda(when_all_is_lost)])
        ```
    runnable	fallbacks.exceptions_to_handleNexception_keyT)arbitrary_types_allowedreturnc                 .    | j                   j                  S N)r    	InputTypeselfs    `/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/runnables/fallbacks.pyr(   zRunnableWithFallbacks.InputTypen   s     }}&&&    c                 .    | j                   j                  S r'   )r    
OutputTyper)   s    r+   r.   z RunnableWithFallbacks.OutputTypes   s     }}'''r,   configc                 8    | j                   j                  |      S r'   )r    get_input_schemar*   r/   s     r+   r1   z&RunnableWithFallbacks.get_input_schemax   s    }}--f55r,   c                 8    | j                   j                  |      S r'   )r    get_output_schemar2   s     r+   r4   z'RunnableWithFallbacks.get_output_schema|   s     }}..v66r,   c                 T    t        d | j                  g| j                  D              S )Nc              3   B   K   | ]  }|j                   D ]  }|   y wr'   )config_specs).0stepspecs      r+   	<genexpr>z5RunnableWithFallbacks.config_specs.<locals>.<genexpr>   s3      '
))'
  '
'
s   )r   r    r!   r)   s    r+   r7   z"RunnableWithFallbacks.config_specs   s.     ' '
88'
 
 	
r,   c                      y)z,Return `True` as this class is serializable.T clss    r+   is_lc_serializablez(RunnableWithFallbacks.is_lc_serializable   s     r,   c                 
    g dS )zwGet the namespace of the LangChain object.

        Returns:
            `["langchain", "schema", "runnable"]`
        )	langchainschemar    r=   r>   s    r+   get_lc_namespacez&RunnableWithFallbacks.get_lc_namespace   s
     32r,   c              #   T   K   | j                    | j                  E d{    y7 w)zxIterator over the `Runnable` and its fallbacks.

        Yields:
            The `Runnable` then its fallbacks.
        Nr    r!   r)   s    r+   	runnableszRunnableWithFallbacks.runnables   s      mm>>!!s   (&(inputkwargsc           	      ,   | j                   *t        |t              sdt        |       d}t	        |      t        |      }t        |      }|j                  d ||j                  d      xs | j                         |j                  dd             }d }d }| j                  D ]  }		 | j                   r|||| j                   <   t        ||j                               }
t        |
      5 } |j                  |	j                   ||fi |}d d d        |j#                         |c S  |d}t	        |      |j)                  |       |# 1 sw Y   AxY w# | j$                  $ r}||}|}Y d }~d }~wt&        $ r}|j)                  |        d }~ww xY wNXIf 'exception_key' is specified then input must be a dictionary.However found a type of 
 for inputrun_namerun_idnamerO   	callbacksz$No error stored at end of fallbacks.)r#   
isinstancedicttype
ValueErrorr   r   on_chain_startgetget_namepoprG   r   	get_childr   runinvokeon_chain_endr"   BaseExceptionon_chain_error)r*   rH   r/   rI   msgcallback_managerrun_managerfirst_error
last_errorr    child_configcontextoutputes                 r+   r^   zRunnableWithFallbacks.invoke   s    )*UD2I++/;-zC  S/!v&:6B&55J':4==?::h-	 6 
 
 	H%%**@0:E$,,-+Fk>S>S>UV'5 (W[[  !	F ((0+	, 8CS/!"";/+  ,, &"#K
  **1-s=   'AE* E

E
E	EF%E00F<FFc           	        K   | j                   *t        |t              sdt        |       d}t	        |      t        |      }t        |      }|j                  d ||j                  d      xs | j                         |j                  dd              d {   }d }d }| j                  D ]  }		 | j                   r|||| j                   <   t        ||j                               }
t        |
      5 } |j                  |	j                   ||fi |}t#        ||       d {   }d d d        |j%                         d {    |c S  |d}t	        |      |j+                  |       d {    |7 7 V# 1 sw Y   UxY w7 C# | j&                  $ r}||}|}Y d }~d }~wt(        $ r }|j+                  |       d {  7    d }~ww xY w7 awrK   )r#   rT   rU   rV   rW   r   r   rX   rY   rZ   r[   rG   r   r\   r   r]   ainvoker   r_   r"   r`   ra   )r*   rH   r/   rI   rb   rc   rd   re   rf   r    rg   rh   corori   rj   s                  r+   rl   zRunnableWithFallbacks.ainvoke   s     )*UD2I++/;-zC  S/!v&@H,;;J':4==?::h-	 < 
 
 
 	H%%**@0:E$,,-+Fk>S>S>UV'5 D&7;;x'7'7Q&QD#4T7#CCFD "..v666#	$ 8CS/!((555?
  DD D 7 ,, &"#K
  !00333 	6s   BGE8G1AF
4/E<#E:$E<(F
0GF,G1G2G:E<<F	F
G
GF$G$G0GGGGGF)return_exceptionsinputsrn   c                   | j                   /t        d |D              sdt        |d          d}t        |      |sg S t	        |t        |            }|D cg c]K  }t        j                  |j                  d      d d|j                  d      d |j                  d      d 	      M }}t        |||d
      D 	cg c]`  \  }}	}|j                  d t        |	t              r|	nd|	i|j                  d      xs | j                         |j                  dd             b }
}	}}i }t        t        |            }i }d }| j                   D ]x  } |j"                  t%        |j'                               D 	cg c]  \  }}	|		 c}	}t%        |      D cg c]#  }t)        ||   |
|   j+                               % c}fddi|}t        t%        |j-                         j'                               |d
      D ]  \  \  }}	}t        |t.              r6t        || j0                        s |s|xs |}n|||<   |j                  |       Ot        || j0                        r!| j                   r||	| j                   <   |||<   |
|   j3                  |       |||<   |j                  |       |j                  |d         |r||ry n t%        |j'                               }|D ]  \  }}|
|   j5                  |        |s
|r|d   d   |j7                  |       t%        |j'                               D cg c]  \  }}|	 c}}S c c}w c c}}	}w c c}	}w c c}w c c}}w )Nc              3   <   K   | ]  }t        |t                y wr'   rT   rU   r8   input_s     r+   r;   z.RunnableWithFallbacks.batch.<locals>.<genexpr>        6
)/Jvt$6
   YIf 'exception_key' is specified then inputs must be dictionaries.However found a type of r   rM   rS   Ftagsmetadatainheritable_callbackslocal_callbacksverboseinheritable_tags
local_tagsinheritable_metadatalocal_metadatastrictrH   rN   rO   rP   rR   rn   T   )r#   allrV   rW   r   lenr   	configurerY   ziprX   rT   rU   rZ   r[   	enumeraterG   batchsorteditemsr   r\   copyr`   r"   r_   ra   update)r*   ro   r/   rn   rI   rb   configscallback_managerscmrt   run_managers	to_return	run_againhandled_exceptionsfirst_to_raiser    _ioutputsri   sorted_handled_exceptionserrors                         r+   r   zRunnableWithFallbacks.batch	  s    )# 6
396
 3
++/q	?*;:G  S/!I "&#f+6 "
  %%&,jj&= $!'F!3%+ZZ
%;#
 
( '*!675'

 

 #FF $VT2&8IZZ
+>t}}zz(D1	  

 

 %'	6*+	79 "	H$hnn)/	0A)BCIAvC $I.  !|A7P7P7RS	 #'	 	G (+y~~'--/0'%( 4#FV fm4ZD55> -)7)A606*1-MM!$(A(AB))5;t112,2&q) O008#)IaLMM!$&**1d3'4( $$E"	H %++=+C+C+E$F!1 	2HAuO**51	2 %>+A.q11+,(.y/@(AB91fBBO


$ DN Cs    AM	>A%M9M(M9M c                   K    j                   /t        d |D              sdt        |d          d}t        |      |sg S t	        |t        |            }|D cg c]K  }t        j                  |j                  d      d d|j                  d      d |j                  d      d 	      M }}t        j                   fd
t        |||d      D          d {   i }t        t        |            }	i }
d } j                  D ]  } |j                  t!        |	j#                               D cg c]  \  }}|	 c}}t!        |	      D cg c]#  }t%        ||   |   j'                               % c}fddi| d {   }t        t!        |	j)                         j#                               |d      D ]  \  \  }}}t+        |t,              r6t+        | j.                        s |s|xs |}n||
|<   |	j1                  |       Ot+        | j.                        r! j                   r|| j                   <   ||
|<   |||<   |   j3                  |       d {    |	j1                  |       |
j1                  |d         |r||	r n t!        |
j#                               }t        j                  fd|D          d {    |s
|r|d   d   |j5                  |
       t!        |j#                               D cg c]  \  }}t7        d|       c}}S c c}w 7 Kc c}}w c c}w 7 7 7 oc c}}w w)Nc              3   <   K   | ]  }t        |t                y wr'   rr   rs   s     r+   r;   z/RunnableWithFallbacks.abatch.<locals>.<genexpr>r  ru   rv   rw   r   rM   rS   Frx   ry   rz   c           
   3      K   | ]N  \  }}}|j                  d ||j                  d      xs j                         |j                  dd              P y w)NrN   rO   rP   )rX   rY   rZ   r[   )r8   r   rt   r/   r*   s       r+   r;   z/RunnableWithFallbacks.abatch.<locals>.<genexpr>  s\      
 'B !!J/B4==?!::h5	 " 
s   AAr   rR   rn   Tc              3   L   K   | ]  \  }}|   j                  |        y wr'   )ra   )r8   r   r   r   s      r+   r;   z/RunnableWithFallbacks.abatch.<locals>.<genexpr>  s,      Au Q..u5s   !$r   r   )r#   r   rV   rW   r   r   r   r   rY   asynciogatherr   rU   r   rG   abatchr   r   r   r\   r   rT   r`   r"   r[   r_   r   r	   )r*   ro   r/   rn   rI   rb   r   r   r   r   r   r   r    r   rt   r   r   ri   r   r   s   `                  @r+   r   zRunnableWithFallbacks.abatchi  sl     )# 6
396
 3
++/q	?*;:G  S/!I "&#f+6 "
  !**&,jj&= $!'F!3%+ZZ
%;#
 
 ELNN
 +.%vwu+
E
 ?
 8:	6*+	79 $	H+HOO)/	0A)BCIAvC $I.  !|A7P7P7RS	 #'	 	 	G (+y~~'--/0'%( 4#FV fm4ZD55> -)7)A606*1-MM!$(A(AB))5;t112,2&q)#)IaL&q/66v>>>MM!$&**1d3'4* $$I$	L %++=+C+C+E$F!nn 9
 	
 	
 !%>+A.q11+,8>y?P8QR91fXv&RR_
?
( D	8 ?	
 Ss   AM AL --M L%AM 1L(=M (L.5M L3CM L6/M :M L8	=M L:
M (M 6M 8M :M c           	   +     K   | j                   *t        |t              sdt        |       d}t	        |      t        |      }t        |      }|j                  d ||j                  d      xs | j                         |j                  dd             }d }d }| j                  D ]  }		 | j                   r|||| j                   <   t        ||j                               }
t        |
      5 } |j                  |	j                   |fi |}|j                  t"        |      }d d d        d } n |r|j)                  |       | |}	 D ]  }| 	 ||z   } 	 |j-                  |       y # 1 sw Y   NxY w# | j$                  $ r}||n|}|}Y d }~d }~wt&        $ r}|j)                  |        d }~ww xY w# t*        $ r d }Y }w xY w# t&        $ r}|j)                  |        d }~ww xY wwNrL   rM   rN   rO   rP   rR   )r#   rT   rU   rV   rW   r   r   rX   rY   rZ   r[   rG   r   r\   r   r]   streamnextr"   r`   ra   	TypeErrorr_   r*   rH   r/   rI   rb   rc   rd   re   rf   r    rg   rh   r   chunkrj   ri   s                   r+   r   zRunnableWithFallbacks.stream  s      )*UD2I++/;-zC  S/!v&:6B&55J':4==?::h-	 6 
 
 	H%%**@0:E$,,-+Fk>S>S>UV'5 >(W[[  !F
 %,KKf$=E> #)	* &&{3 %		 ""#e^F" 	  (A> > ,, #.#6aK
  **1-" ! "!F" 	&&q)	s   B&G0)AE:,5E.!E:) G0
	G F<G G0.E7	3E::F9	FG0F9"F44F99G0<G
G 	G

G 	G-G((G--G0c           	     T  K   | j                   *t        |t              sdt        |       d}t	        |      t        |      }t        |      }|j                  d ||j                  d      xs | j                         |j                  dd              d {   }d }d }| j                  D ]  }		 | j                   r|||| j                   <   t        ||j                               }
t        |
      5 } |	j                  ||
fi |}t!        t#        |      |       d {   }d d d        d } n |r|j)                  |       d {    | |}	 2 3 d {   }| 	 ||z   }7 7 O# 1 sw Y   NxY w# | j$                  $ r}||n|}|}Y d }~d }~wt&        $ r }|j)                  |       d {  7    d }~ww xY w7 7 m# t*        $ r d }Y w xY w6 n,# t&        $ r }|j)                  |       d {  7    d }~ww xY w|j-                  |       d {  7   y wr   )r#   rT   rU   rV   rW   r   r   rX   rY   rZ   r[   rG   r   r\   r   astreamr   anextr"   r`   ra   r   r_   r   s                   r+   r   zRunnableWithFallbacks.astream  sd     )*UD2I++/;-zC  S/!v&@H,;;J':4==?::h-	 < 
 
 
 	H%%**@0:E$,,-+Fk>S>S>UV'5 L-X--$ !F
 #4E&M7"KKEL #)	* ,,[999 %		% " "e"#e^FO
& LL L ,, #.#6aK
  !00333 :" ! "!F"	  &  	,,Q///	 &&v...s  BH(E/H(1AE?4-E3!E1"E3&E?.H(	G

H(G! GGG"G! )G.G! /H(1E33E<	8E??GFH(G'G;F><GGH(GGG! GG!  H(!	H
*H>H?HH

H(!H$"H(rQ   c                      t         j                        t              r*t              dt        dt        dt        f fd       }|S S )af  Get an attribute from the wrapped `Runnable` and its fallbacks.

        Returns:
            If the attribute is anything other than a method that outputs a `Runnable`,
            returns `getattr(self.runnable, name)`. If the attribute is a method that
            does return a new `Runnable` (e.g. `model.bind_tools([...])` outputs a new
            `RunnableBinding`) then `self.runnable` and each of the runnables in
            `self.fallbacks` is replaced with `getattr(x, name)`.

        Example:
            ```python
            from langchain_openai import ChatOpenAI
            from langchain_anthropic import ChatAnthropic

            gpt_4o = ChatOpenAI(model="gpt-4o")
            claude_3_sonnet = ChatAnthropic(model="claude-sonnet-4-5-20250929")
            model = gpt_4o.with_fallbacks([claude_3_sonnet])

            model.model_name
            # -> "gpt-4o"

            # .bind_tools() is called on both ChatOpenAI and ChatAnthropic
            # Equivalent to:
            # gpt_4o.bind_tools([...]).with_fallbacks([claude_3_sonnet.bind_tools([...])])
            model.bind_tools([...])
            # -> RunnableWithFallbacks(
                runnable=RunnableBinding(bound=ChatOpenAI(...), kwargs={"tools": [...]}),
                fallbacks=[RunnableBinding(bound=ChatAnthropic(...), kwargs={"tools": [...]})],
            )
            ```
        argsrI   r%   c                       | i |}g }j                   D ]%  }t        |      }|j                   || i |       '  j                  di i j	                         ||dS )NrF   r=   )r!   getattrappend	__class__
model_dump)	r   rI   new_runnablenew_fallbacksfallbackfallback_attrattrrQ   r*   s	         r+   wrappedz2RunnableWithFallbacks.__getattr__.<locals>.wrappedt  s    #T4V4 " $ IH$+Hd$;M!(()G)GHI &t~~ //+$0%2 r,   )r   r    _returns_runnabler   r   )r*   rQ   r   r   s   `` @r+   __getattr__z!RunnableWithFallbacks.__getattr__Q  sU    @ t}}d+T"4[s c c   Nr,   r'   ),__name__
__module____qualname____doc__r   r   r   __annotations__r   	Exceptionr"   tuplerV   r`   r#   strr   model_configpropertyr   r(   r.   r   r
   r1   r4   listr   r7   classmethodboolr@   rD   r   rG   r   r^   rl   r   r   r   r   r   r   r=   r,   r+   r   r   $   s   1f uf}%%&/00)=FL%] 3S 89H !%M3:$  $L '4; '  ' (DL (  ( 6~'< 6Y 6 6 .27$t+7	i7 7
 
d#89 
  
 4    3c 3  3 "8HUF]$;< " " <@//$2T$9/LO/	/ /b  )-// %/ *	/
 
/ /b  @D]C
 #(]CU]C n!55<]C
  ]C *]C 
f]C ]C~  @DeS
 #(eSUeS n!55<eS
  eS *eS 
feS eSN  )-=)=) %=) *	=)
 
&	=) =)~  )-=/=/ %=/ *	=/
 
v	=/ =/~5 5 5r,   r   r   r%   c                     t        |       syt        j                  |       j                  d      }t	        |xr t        |            S )NFr%   )callabletypingget_type_hintsrY   r   _is_runnable_type)r   return_types     r+   r   r     s=    D>''-11(;K> 1+ >??r,   type_c                    t        j                  |       rt        | t              S t	        | dd       }t        j                  |      rt        |t              S |t
        j                  u rt        d | j                  D              S y)N
__origin__c              3   2   K   | ]  }t        |        y wr'   )r   )r8   ts     r+   r;   z$_is_runnable_type.<locals>.<genexpr>  s     @A$Q'@s   F)	inspectisclass
issubclassr   r   r   Unionr   __args__)r   origins     r+   r   r     sf    u%**UL$/Fv&(++@@@@r,   )+r   r   r   r   collections.abcr   r   r   	functoolsr   r   r   r	   pydanticr
   r   typing_extensionsr    langchain_core.callbacks.managerr   r   langchain_core.runnables.baser   r   langchain_core.runnables.configr   r   r   r   r   r   r   langchain_core.runnables.utilsr   r   r   r   r   r   r   r   r   r   r=   r,   r+   <module>r      s    @    = =  + + * & R H    Pb	0? b	J@C @D @S T r,   