Home / Function/ shielded() — langchain Function Reference

shielded() — langchain Function Reference

Architecture documentation for the shielded() function in manager.py from the langchain codebase.

Entity Profile

Dependency Diagram

graph TD
  d5af1f7c_c6c8_b6b1_a3ca_c8ed2a29ac4c["shielded()"]
  35cf5db6_bcb1_b854_6ebb_5e0368e51b58["manager.py"]
  d5af1f7c_c6c8_b6b1_a3ca_c8ed2a29ac4c -->|defined in| 35cf5db6_bcb1_b854_6ebb_5e0368e51b58
  style d5af1f7c_c6c8_b6b1_a3ca_c8ed2a29ac4c fill:#6366f1,stroke:#818cf8,color:#fff

Relationship Graph

Source Code

libs/core/langchain_core/callbacks/manager.py lines 221–253

def shielded(func: Func) -> Func:
    """Makes so an awaitable method is always shielded from cancellation.

    Args:
        func: The function to shield.

    Returns:
        The shielded function

    """

    @functools.wraps(func)
    async def wrapped(*args: Any, **kwargs: Any) -> Any:
        # Capture the current context to preserve context variables
        ctx = copy_context()

        # Create the coroutine
        coro = func(*args, **kwargs)

        # For Python 3.11+, create task with explicit context
        # For older versions, fallback to original behavior
        try:
            # Create a task with the captured context to preserve context variables
            task = asyncio.create_task(coro, context=ctx)  # type: ignore[call-arg, unused-ignore]
            # `call-arg` used to not fail 3.9 or 3.10 tests
            return await asyncio.shield(task)
        except TypeError:
            # Python < 3.11 fallback - create task normally then shield
            # This won't preserve context perfectly but is better than nothing
            task = asyncio.create_task(coro)
            return await asyncio.shield(task)

    return cast("Func", wrapped)

Subdomains

Frequently Asked Questions

What does shielded() do?
shielded() is a function in the langchain codebase, defined in libs/core/langchain_core/callbacks/manager.py.
Where is shielded() defined?
shielded() is defined in libs/core/langchain_core/callbacks/manager.py at line 221.

Analyze Your Own Codebase

Get architecture documentation, dependency graphs, and domain analysis for your codebase in minutes.

Try Supermodel Free