LangChain Reference home pageLangChain ReferenceLangChain Reference
  • GitHub
  • Main Docs
Deep Agents
LangChain
LangGraph
Integrations
LangSmith
  • Overview
    • Overview
    • Caches
    • Callbacks
    • Documents
    • Document loaders
    • Embeddings
    • Exceptions
    • Language models
    • Serialization
    • Output parsers
    • Prompts
    • Rate limiters
    • Retrievers
    • Runnables
    • Utilities
    • Vector stores
    MCP Adapters
    Standard Tests
    Text Splitters
    ⌘I

    LangChain Assistant

    Ask a question to get started

    Enter to send•Shift+Enter new line

    Menu

    OverviewCachesCallbacksDocumentsDocument loadersEmbeddingsExceptionsLanguage modelsSerializationOutput parsersPromptsRate limitersRetrieversRunnablesUtilitiesVector stores
    MCP Adapters
    Standard Tests
    Text Splitters
    Language
    Theme
    Pythonlangchain-corerunnablesretryRunnableRetry
    Class●Since v0.1

    RunnableRetry

    Retry a Runnable if it fails.

    RunnableRetry can be used to add retry logic to any object that subclasses the base Runnable.

    Such retries are especially useful for network calls that may fail due to transient errors.

    The RunnableRetry is implemented as a RunnableBinding. The easiest way to use it is through the .with_retry() method on all Runnables.

    Example: Here's an example that uses a RunnableLambda to raise an exception

    import time
    
    def foo(input) -> None:
        '''Fake function that raises an exception.'''
        raise ValueError(f"Invoking foo failed. At time {time.time()}")
    
    runnable = RunnableLambda(foo)
    
    runnable_with_retries = runnable.with_retry(
        retry_if_exception_type=(ValueError,),  # Retry only on ValueError
        wait_exponential_jitter=True,  # Add jitter to the exponential backoff
        stop_after_attempt=2,  # Try twice
        exponential_jitter_params={"initial": 2},  # if desired, customize backoff
    )
    
    # The method invocation above is equivalent to the longer form below:
    
    runnable_with_retries = RunnableRetry(
        bound=runnable,
        retry_exception_types=(ValueError,),
        max_attempt_number=2,
        wait_exponential_jitter=True,
        exponential_jitter_params={"initial": 2},
    )

    This logic can be used to retry any Runnable, including a chain of Runnables, but in general it's best practice to keep the scope of the retry as small as possible. For example, if you have a chain of Runnables, you should only retry the Runnable that is likely to fail, not the entire chain.

    Copy
    RunnableRetry(
      self,
      *,
      bound: Runnable[Input, Output],
      kwargs: Mapping[str, Any] | None = None,
      config: RunnableConfig | None = None,
      config_factories: list[Callable[[RunnableConfig], RunnableConfig]] | None = None,
      custom_input_type: type[Input] | BaseModel | None = None,
      custom_output_type: type[Output] | BaseModel | None = None,
      **other_kwargs: Any = {}
    )

    Bases

    RunnableBindingBase[Input, Output]

    Example:

    from langchain_core.chat_models import ChatOpenAI
    from langchain_core.prompts import PromptTemplate
    
    template = PromptTemplate.from_template("tell me a joke about {topic}.")
    model = ChatOpenAI(temperature=0.5)
    
    # Good
    chain = template | model.with_retry()
    
    # Bad
    chain = template | model
    retryable_chain = chain.with_retry()

    Attributes

    attribute
    retry_exception_types: tuple[type[BaseException], ...]

    The exception types to retry on. By default all exceptions are retried.

    In general you should only retry on exceptions that are likely to be transient, such as network errors.

    Good exceptions to retry are all server errors (5xx) and selected client errors (4xx) such as 429 Too Many Requests.

    attribute
    wait_exponential_jitter: bool

    Whether to add jitter to the exponential backoff.

    attribute
    exponential_jitter_params: ExponentialJitterParams | None

    Parameters for tenacity.wait_exponential_jitter. Namely: initial, max, exp_base, and jitter (all float values).

    attribute
    max_attempt_number: int

    The maximum number of attempts to retry the Runnable.

    Methods

    method
    invoke
    method
    ainvoke
    method
    batch
    method
    abatch

    Inherited fromRunnableBindingBase

    Attributes

    Abound: Runnable[Input, Output]Akwargs: Mapping[str, Any]
    —

    kwargs to pass to the underlying Runnable when running.

    Aconfig: RunnableConfig | None
    —

    The configuration to use.

    Aconfig_factories: list[Callable[[RunnableConfig], RunnableConfig]]
    —

    The config factories to bind to the underlying Runnable.

    Acustom_input_type: Any | None
    —

    Override the input type of the underlying Runnable with a custom type.

    Acustom_output_type: Any | None
    —

    Override the output type of the underlying Runnable with a custom type.

    Amodel_configAInputType: AnyAOutputType: AnyAconfig_specs: list[ConfigurableFieldSpec]

    Methods

    Mget_nameMget_input_schemaMget_output_schemaMget_graphMis_lc_serializable
    —

    Return True as this class is serializable.

    Mget_lc_namespace
    —

    Get the namespace of the LangChain object.

    Mbatch_as_completed
    —

    Run invoke in parallel on a list of inputs.

    Mabatch_as_completed
    —

    Run ainvoke in parallel on a list of inputs.

    MstreamMastreamMastream_events
    —

    Generate a stream of events.

    MtransformMatransform

    Inherited fromRunnableSerializable

    Attributes

    Aname: str
    —

    The name of the function.

    Amodel_config

    Methods

    Mto_json
    —

    Convert the graph to a JSON-serializable format.

    Mconfigurable_fieldsMconfigurable_alternatives
    —

    Configure alternatives for Runnable objects that can be set at runtime.

    Inherited fromSerializable

    Attributes

    Alc_secrets: dict[str, str]
    —

    A map of constructor argument names to secret ids.

    Alc_attributes: dict
    —

    List of attribute names that should be included in the serialized kwargs.

    Amodel_config

    Methods

    Mis_lc_serializable
    —

    Return True as this class is serializable.

    Mget_lc_namespace
    —

    Get the namespace of the LangChain object.

    Mlc_id
    —

    Return a unique identifier for this class for serialization purposes.

    Mto_json
    —

    Convert the graph to a JSON-serializable format.

    Mto_json_not_implemented
    —

    Serialize a "not implemented" object.

    Inherited fromRunnable

    Attributes

    Aname: str
    —

    The name of the function.

    AInputType: AnyAOutputType: AnyAinput_schema: type[BaseModel]
    —

    The type of input this Runnable accepts specified as a Pydantic model.

    Aoutput_schema: type[BaseModel]
    —

    Output schema.

    Aconfig_specs: list[ConfigurableFieldSpec]

    Methods

    Mget_nameMget_input_schemaMget_input_jsonschema
    —

    Get a JSON schema that represents the input to the Runnable.

    Mget_output_schemaMget_output_jsonschema
    —

    Get a JSON schema that represents the output of the Runnable.

    Mconfig_schema
    —

    The type of config this Runnable accepts specified as a Pydantic model.

    Mget_config_jsonschema
    —

    Get a JSON schema that represents the config of the Runnable.

    Mget_graphMget_prompts
    —

    Return a list of prompts used by this Runnable.

    Mpipe
    —

    Pipe Runnable objects.

    Mpick
    —

    Pick keys from the output dict of this Runnable.

    Massign
    —

    Merge the Dict input with the output produced by the mapping argument.

    Mbatch_as_completed
    —

    Run invoke in parallel on a list of inputs.

    Mabatch_as_completed
    —

    Run ainvoke in parallel on a list of inputs.

    MstreamMastreamMastream_log
    —

    Stream all output from a Runnable, as reported to the callback system.

    Mastream_events
    —

    Generate a stream of events.

    MtransformMatransformMbind
    —

    Bind arguments to a Runnable, returning a new Runnable.

    Mwith_configMwith_listeners
    —

    Bind lifecycle listeners to a Runnable, returning a new Runnable.

    Mwith_alisteners
    —

    Bind async lifecycle listeners to a Runnable.

    Mwith_types
    —

    Bind input and output types to a Runnable, returning a new Runnable.

    Mwith_retry
    —

    Create a new Runnable that retries the original Runnable on exceptions.

    Mmap
    —

    Map a function to multiple iterables.

    Mwith_fallbacks
    —

    Add fallbacks to a Runnable, returning a new Runnable.

    Mas_tool
    —

    Create a BaseTool from a Runnable.

    View source on GitHub