value = _eval_type(value, base_globals, base_locals)
                hints[name] = value
        return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
    if globalns is None:
        if isinstance(obj, types.ModuleType):
            globalns = obj.__dict__
        else:
            nsobj = obj
            # Find globalns for the unwrapped object.
            while hasattr(nsobj, '__wrapped__'):
                nsobj = nsobj.__wrapped__
            globalns = getattr(nsobj, '__globals__', {})
        if localns is None:
            localns = globalns
    elif localns is None:
        localns = globalns
    hints = getattr(obj, '__annotations__', None)
    if hints is None:
        # Return empty annotations for something that _could_ have them.
        if isinstance(obj, _allowed_types):
            return {}
        else:
            raise TypeError('{!r} is not a module, class, method, '
                            'or function.'.format(obj))
    hints = dict(hints)
    for name, value in hints.items():
        if value is None:
            value = type(None)
        if isinstance(value, str):
            # class-level forward refs were handled above, this must be either
            # a module-level annotation or a function argument annotation
            value = ForwardRef(
                value,
                is_argument=not isinstance(obj, types.ModuleType),
                is_class=False,
            )
        hints[name] = _eval_type(value, globalns, localns)
    return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
def _strip_annotations(t):
    """Strip the annotations from a given type."""


def _strip_annotations(t):
    """Strip the annotations from a given type."""
    if isinstance(t, _AnnotatedAlias):
        return _strip_annotations(t.__origin__)
    if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
        return _strip_annotations(t.__args__[0])
    if isinstance(t, _GenericAlias):
        stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
        if stripped_args == t.__args__:
            return t
        return t.copy_with(stripped_args)
    if isinstance(t, GenericAlias):
        stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
        if stripped_args == t.__args__:
            return t
        return GenericAlias(t.__origin__, stripped_args)
    if isinstance(t, types.UnionType):
        stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
        if stripped_args == t.__args__:
            return t
        return functools.reduce(operator.or_, stripped_args)
    return t
def get_origin(tp):
    """Get the unsubscripted version of a type.
    This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar,
    Annotated, and others. Return None for unsupported types.
    Examples::
        assert get_origin(Literal[42]) is Literal
        assert get_origin(int) is None
        assert get_origin(ClassVar[int]) is ClassVar
        assert get_origin(Generic) is Generic
        assert get_origin(Generic[T]) is Generic
        assert get_origin(Union[T, int]) is Union
        assert get_origin(List[Tuple[T, T]][int]) is list
        assert get_origin(P.args) is P
    """


assert get_origin(P.args) is P
    """
    if isinstance(tp, _AnnotatedAlias):
        return Annotated
    if isinstance(tp, (_BaseGenericAlias, GenericAlias,
                       ParamSpecArgs, ParamSpecKwargs)):
        return tp.__origin__
    if tp is Generic:
        return Generic
    if isinstance(tp, types.UnionType):
        return types.UnionType
    return None
def get_args(tp):
    """Get type arguments with all substitutions performed.
    For unions, basic simplifications used by Union constructor are performed.
    Examples::
        assert get_args(Dict[str, int]) == (str, int)
        assert get_args(int) == ()
        assert get_args(Union[int, Union[T, int], str][int]) == (int, str)
        assert get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
        assert get_args(Callable[[], T][int]) == ([], int)
    """
    if isinstance(tp, _AnnotatedAlias):
        return (tp.__origin__,) + tp.__metadata__
    if isinstance(tp, (_GenericAlias, GenericAlias)):
        res = tp.__args__
        if _should_unflatten_callable_args(tp, res):
            res = (list(res[:-1]), res[-1])
        return res
    if isinstance(tp, types.UnionType):
        return tp.__args__
    return ()
def is_typeddict(tp):
    """Check if an annotation is a TypedDict class.
    For example::
        class Film(TypedDict):
            title: str
            year: int
        is_typeddict(Film)              # => True
        is_typeddict(Union[list, str])  # => False


is_typeddict(Union[list, str])  # => False
    """
    return isinstance(tp, _TypedDictMeta)
_ASSERT_NEVER_REPR_MAX_LENGTH = 100
def assert_never(arg: Never, /) -> Never:
    """Statically assert that a line of code is unreachable.
    Example::
        def int_or_str(arg: int | str) -> None:
            match arg:
                case int():
                    print("It's an int")
                case str():
                    print("It's a str")
                case _:
                    assert_never(arg)
    If a type checker finds that a call to assert_never() is
    reachable, it will emit an error.
    At runtime, this throws an exception when called.
    """
    value = repr(arg)
    if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
        value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
    raise AssertionError(f"Expected code to be unreachable, but got: {value}")
def no_type_check(arg):
    """Decorator to indicate that annotations are not type hints.
    The argument must be a class or function; if it is a class, it
    applies recursively to all methods and classes defined in that class
    (but not to methods defined in its superclasses or subclasses).
    This mutates the function(s) or class(es) in place.
    """
    if isinstance(arg, type):
        for key in dir(arg):
            obj = getattr(arg, key)
            if (
                not hasattr(obj, '__qualname__')
                or obj.__qualname__ != f'{arg.__qualname__}.{obj.__name__}'
                or getattr(obj, '__module__', None) != arg.__module__
            ):


or getattr(obj, '__module__', None) != arg.__module__
            ):
                # We only modify objects that are defined in this type directly.
                # If classes / methods are nested in multiple layers,
                # we will modify them when processing their direct holders.
                continue
            # Instance, class, and static methods:
            if isinstance(obj, types.FunctionType):
                obj.__no_type_check__ = True
            if isinstance(obj, types.MethodType):
                obj.__func__.__no_type_check__ = True
            # Nested types:
            if isinstance(obj, type):
                no_type_check(obj)
    try:
        arg.__no_type_check__ = True
    except TypeError:  # built-in classes
        pass
    return arg
def no_type_check_decorator(decorator):
    """Decorator to give another decorator the @no_type_check effect.
    This wraps the decorator with something that wraps the decorated
    function in @no_type_check.
    """
    @functools.wraps(decorator)
    def wrapped_decorator(*args, **kwds):
        func = decorator(*args, **kwds)
        func = no_type_check(func)
        return func
    return wrapped_decorator
def _overload_dummy(*args, **kwds):
    """Helper for @overload to raise when called."""
    raise NotImplementedError(
        "You should not call an overloaded function. "
        "A series of @overload-decorated functions "
        "outside a stub module should always be followed "
        "by an implementation that is not @overload-ed.")
# {module: {qualname: {firstlineno: func}}}
_overload_registry = defaultdict(functools.partial(defaultdict, dict))
def overload(func):
    """Decorator for overloaded functions/methods.


def overload(func):
    """Decorator for overloaded functions/methods.
    In a stub file, place two or more stub definitions for the same
    function in a row, each decorated with @overload.
    For example::
        @overload
        def utf8(value: None) -> None: ...
        @overload
        def utf8(value: bytes) -> bytes: ...
        @overload
        def utf8(value: str) -> bytes: ...
    In a non-stub file (i.e. a regular .py file), do the same but
    follow it with an implementation.  The implementation should *not*
    be decorated with @overload::
        @overload
        def utf8(value: None) -> None: ...
        @overload
        def utf8(value: bytes) -> bytes: ...
        @overload
        def utf8(value: str) -> bytes: ...
        def utf8(value):
            ...  # implementation goes here
    The overloads for a function can be retrieved at runtime using the
    get_overloads() function.
    """
    # classmethod and staticmethod
    f = getattr(func, "__func__", func)
    try:
        _overload_registry[f.__module__][f.__qualname__][f.__code__.co_firstlineno] = func
    except AttributeError:
        # Not a normal function; ignore.
        pass
    return _overload_dummy
def get_overloads(func):
    """Return all defined overloads for *func* as a sequence."""
    # classmethod and staticmethod
    f = getattr(func, "__func__", func)
    if f.__module__ not in _overload_registry:
        return []
    mod_dict = _overload_registry[f.__module__]


return []
    mod_dict = _overload_registry[f.__module__]
    if f.__qualname__ not in mod_dict:
        return []
    return list(mod_dict[f.__qualname__].values())
def clear_overloads():
    """Clear all overloads in the registry."""
    _overload_registry.clear()
def final(f):
    """Decorator to indicate final methods and final classes.
    Use this decorator to indicate to type checkers that the decorated
    method cannot be overridden, and decorated class cannot be subclassed.
    For example::
        class Base:
            @final
            def done(self) -> None:
                ...
        class Sub(Base):
            def done(self) -> None:  # Error reported by type checker
                ...
        @final
        class Leaf:
            ...
        class Other(Leaf):  # Error reported by type checker
            ...
    There is no runtime checking of these properties. The decorator
    attempts to set the ``__final__`` attribute to ``True`` on the decorated
    object to allow runtime introspection.
    """
    try:
        f.__final__ = True
    except (AttributeError, TypeError):
        # Skip the attribute silently if it is not writable.
        # AttributeError happens if the object has __slots__ or a
        # read-only property, TypeError if it's a builtin class.
        pass
    return f
# Some unconstrained type variables.  These are used by the container types.
# (These are not for export.)
T = TypeVar('T')  # Any type.
KT = TypeVar('KT')  # Key type.
VT = TypeVar('VT')  # Value type.


VT = TypeVar('VT')  # Value type.
T_co = TypeVar('T_co', covariant=True)  # Any type covariant containers.
V_co = TypeVar('V_co', covariant=True)  # Any type covariant containers.
VT_co = TypeVar('VT_co', covariant=True)  # Value type covariant containers.
T_contra = TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
# Internal type variable used for Type[].
CT_co = TypeVar('CT_co', covariant=True, bound=type)
# A useful type variable with constraints.  This represents string types.
# (This one *is* for export!)
AnyStr = TypeVar('AnyStr', bytes, str)
# Various ABCs mimicking those in collections.abc.
_alias = _SpecialGenericAlias
Hashable = _alias(collections.abc.Hashable, 0)  # Not generic.
Awaitable = _alias(collections.abc.Awaitable, 1)
Coroutine = _alias(collections.abc.Coroutine, 3)
AsyncIterable = _alias(collections.abc.AsyncIterable, 1)
AsyncIterator = _alias(collections.abc.AsyncIterator, 1)
Iterable = _alias(collections.abc.Iterable, 1)
Iterator = _alias(collections.abc.Iterator, 1)
Reversible = _alias(collections.abc.Reversible, 1)
Sized = _alias(collections.abc.Sized, 0)  # Not generic.
Container = _alias(collections.abc.Container, 1)
Collection = _alias(collections.abc.Collection, 1)
Callable = _CallableType(collections.abc.Callable, 2)
Callable.__doc__ = \


Callable.__doc__ = \
    """Deprecated alias to collections.abc.Callable.
    Callable[[int], str] signifies a function that takes a single
    parameter of type int and returns a str.
    The subscription syntax must always be used with exactly two
    values: the argument list and the return type.
    The argument list must be a list of types, a ParamSpec,
    Concatenate or ellipsis. The return type must be a single type.
    There is no syntax to indicate optional or keyword arguments;
    such function types are rarely used as callback types.
    """
AbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet')
MutableSet = _alias(collections.abc.MutableSet, 1)
# NOTE: Mapping is only covariant in the value type.
Mapping = _alias(collections.abc.Mapping, 2)
MutableMapping = _alias(collections.abc.MutableMapping, 2)
Sequence = _alias(collections.abc.Sequence, 1)
MutableSequence = _alias(collections.abc.MutableSequence, 1)
ByteString = _alias(collections.abc.ByteString, 0)  # Not generic
# Tuple accepts variable number of parameters.
Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
Tuple.__doc__ = \
    """Deprecated alias to builtins.tuple.
    Tuple[X, Y] is the cross-product type of X and Y.
    Example: Tuple[T1, T2] is a tuple of two elements corresponding
    to type variables T1 and T2.  Tuple[int, float, str] is a tuple
    of an int, a float and a string.
    To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
    """


"""
List = _alias(list, 1, inst=False, name='List')
Deque = _alias(collections.deque, 1, name='Deque')
Set = _alias(set, 1, inst=False, name='Set')
FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet')
MappingView = _alias(collections.abc.MappingView, 1)
KeysView = _alias(collections.abc.KeysView, 1)
ItemsView = _alias(collections.abc.ItemsView, 2)
ValuesView = _alias(collections.abc.ValuesView, 1)
ContextManager = _alias(contextlib.AbstractContextManager, 1, name='ContextManager')
AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, 1, name='AsyncContextManager')
Dict = _alias(dict, 2, inst=False, name='Dict')
DefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict')
OrderedDict = _alias(collections.OrderedDict, 2)
Counter = _alias(collections.Counter, 1)
ChainMap = _alias(collections.ChainMap, 2)
Generator = _alias(collections.abc.Generator, 3)
AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
Type = _alias(type, 1, inst=False, name='Type')
Type.__doc__ = \
    """Deprecated alias to builtins.type.
    builtins.type or typing.Type can be used to annotate class objects.
    For example, suppose we have the following classes::
        class User: ...  # Abstract base for User classes
        class BasicUser(User): ...
        class ProUser(User): ...
        class TeamUser(User): ...


class ProUser(User): ...
        class TeamUser(User): ...
    And a function that takes a class argument that's a subclass of
    User and returns an instance of the corresponding class::
        U = TypeVar('U', bound=User)
        def new_user(user_class: Type[U]) -> U:
            user = user_class()
            # (Here we could write the user object to a database)
            return user
        joe = new_user(BasicUser)
    At this point the type checker knows that joe has type BasicUser.
    """
@runtime_checkable
class SupportsInt(Protocol):
    """An ABC with one abstract method __int__."""
    __slots__ = ()
    @abstractmethod
    def __int__(self) -> int:
        pass
@runtime_checkable
class SupportsFloat(Protocol):
    """An ABC with one abstract method __float__."""
    __slots__ = ()
    @abstractmethod
    def __float__(self) -> float:
        pass
@runtime_checkable
class SupportsComplex(Protocol):
    """An ABC with one abstract method __complex__."""
    __slots__ = ()
    @abstractmethod
    def __complex__(self) -> complex:
        pass
@runtime_checkable
class SupportsBytes(Protocol):
    """An ABC with one abstract method __bytes__."""
    __slots__ = ()
    @abstractmethod
    def __bytes__(self) -> bytes:
        pass
@runtime_checkable
class SupportsIndex(Protocol):
    """An ABC with one abstract method __index__."""
    __slots__ = ()
    @abstractmethod
    def __index__(self) -> int:
        pass
@runtime_checkable
class SupportsAbs(Protocol[T_co]):


pass
@runtime_checkable
class SupportsAbs(Protocol[T_co]):
    """An ABC with one abstract method __abs__ that is covariant in its return type."""
    __slots__ = ()
    @abstractmethod
    def __abs__(self) -> T_co:
        pass
@runtime_checkable
class SupportsRound(Protocol[T_co]):
    """An ABC with one abstract method __round__ that is covariant in its return type."""
    __slots__ = ()
    @abstractmethod
    def __round__(self, ndigits: int = 0) -> T_co:
        pass
def _make_nmtuple(name, types, module, defaults = ()):
    fields = [n for n, t in types]
    types = {n: _type_check(t, f"field {n} annotation must be a type")
             for n, t in types}
    nm_tpl = collections.namedtuple(name, fields,
                                    defaults=defaults, module=module)
    nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
    return nm_tpl
# attributes prohibited to set in NamedTuple class syntax
_prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
                         '_fields', '_field_defaults',
                         '_make', '_replace', '_asdict', '_source'})
_special = frozenset({'__module__', '__name__', '__annotations__'})
class NamedTupleMeta(type):
    def __new__(cls, typename, bases, ns):
        assert _NamedTuple in bases
        for base in bases:
            if base is not _NamedTuple and base is not Generic:
                raise TypeError(
                    'can only inherit from a NamedTuple type and Generic')


raise TypeError(
                    'can only inherit from a NamedTuple type and Generic')
        bases = tuple(tuple if base is _NamedTuple else base for base in bases)
        types = ns.get('__annotations__', {})
        default_names = []
        for field_name in types:
            if field_name in ns:
                default_names.append(field_name)
            elif default_names:
                raise TypeError(f"Non-default namedtuple field {field_name} "
                                f"cannot follow default field"
                                f"{'s' if len(default_names) > 1 else ''} "
                                f"{', '.join(default_names)}")
        nm_tpl = _make_nmtuple(typename, types.items(),
                               defaults=[ns[n] for n in default_names],
                               module=ns['__module__'])
        nm_tpl.__bases__ = bases
        if Generic in bases:
            class_getitem = Generic.__class_getitem__.__func__
            nm_tpl.__class_getitem__ = classmethod(class_getitem)
        # update from user namespace without overriding special namedtuple attributes
        for key in ns:
            if key in _prohibited:
                raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
            elif key not in _special and key not in nm_tpl._fields:
                setattr(nm_tpl, key, ns[key])
        if Generic in bases:
            nm_tpl.__init_subclass__()
        return nm_tpl
def NamedTuple(typename, fields=None, /, **kwargs):
    """Typed version of namedtuple.
    Usage::
        class Employee(NamedTuple):
            name: str
            id: int
    This is equivalent to::
        Employee = collections.namedtuple('Employee', ['name', 'id'])
    The resulting class has an extra __annotations__ attribute, giving a


The resulting class has an extra __annotations__ attribute, giving a
    dict that maps field names to types.  (The field names are also in
    the _fields attribute, which is part of the namedtuple API.)
    An alternative equivalent functional syntax is also accepted::
        Employee = NamedTuple('Employee', [('name', str), ('id', int)])
    """
    if fields is None:
        fields = kwargs.items()
    elif kwargs:
        raise TypeError("Either list of fields or keywords"
                        " can be provided to NamedTuple, not both")
    return _make_nmtuple(typename, fields, module=_caller())
_NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})
def _namedtuple_mro_entries(bases):
    assert NamedTuple in bases
    return (_NamedTuple,)
NamedTuple.__mro_entries__ = _namedtuple_mro_entries
class _TypedDictMeta(type):
    def __new__(cls, name, bases, ns, total=True):
        """Create a new typed dict class object.
        This method is called when TypedDict is subclassed,
        or when TypedDict is instantiated. This way
        TypedDict supports all three syntax forms described in its docstring.
        Subclasses and instances of TypedDict return actual dictionaries.
        """
        for base in bases:
            if type(base) is not _TypedDictMeta and base is not Generic:
                raise TypeError('cannot inherit from both a TypedDict type '
                                'and a non-TypedDict base class')
        if any(issubclass(b, Generic) for b in bases):
            generic_base = (Generic,)
        else:
            generic_base = ()


generic_base = (Generic,)
        else:
            generic_base = ()
        tp_dict = type.__new__(_TypedDictMeta, name, (*generic_base, dict), ns)
        annotations = {}
        own_annotations = ns.get('__annotations__', {})
        msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
        own_annotations = {
            n: _type_check(tp, msg, module=tp_dict.__module__)
            for n, tp in own_annotations.items()
        }
        required_keys = set()
        optional_keys = set()
        for base in bases:
            annotations.update(base.__dict__.get('__annotations__', {}))
            required_keys.update(base.__dict__.get('__required_keys__', ()))
            optional_keys.update(base.__dict__.get('__optional_keys__', ()))
        annotations.update(own_annotations)
        for annotation_key, annotation_type in own_annotations.items():
            annotation_origin = get_origin(annotation_type)
            if annotation_origin is Annotated:
                annotation_args = get_args(annotation_type)
                if annotation_args:
                    annotation_type = annotation_args[0]
                    annotation_origin = get_origin(annotation_type)
            if annotation_origin is Required:
                required_keys.add(annotation_key)
            elif annotation_origin is NotRequired:
                optional_keys.add(annotation_key)
            elif total:
                required_keys.add(annotation_key)
            else:
                optional_keys.add(annotation_key)
        tp_dict.__annotations__ = annotations
        tp_dict.__required_keys__ = frozenset(required_keys)
        tp_dict.__optional_keys__ = frozenset(optional_keys)
        if not hasattr(tp_dict, '__total__'):
            tp_dict.__total__ = total
        return tp_dict


tp_dict.__total__ = total
        return tp_dict
    __call__ = dict  # static method
    def __subclasscheck__(cls, other):
        # Typed dicts are only for static structural subtyping.
        raise TypeError('TypedDict does not support instance and class checks')
    __instancecheck__ = __subclasscheck__
def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
    """A simple typed namespace. At runtime it is equivalent to a plain dict.
    TypedDict creates a dictionary type such that a type checker will expect all
    instances to have a certain set of keys, where each key is
    associated with a value of a consistent type. This expectation
    is not checked at runtime.
    Usage::
        class Point2D(TypedDict):
            x: int
            y: int
            label: str
        a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
        b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
        assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
    The type info can be accessed via the Point2D.__annotations__ dict, and
    the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
    TypedDict supports an additional equivalent form::
        Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
    By default, all keys must be present in a TypedDict. It is possible
    to override this by specifying totality::
        class Point2D(TypedDict, total=False):


class Point2D(TypedDict, total=False):
            x: int
            y: int
    This means that a Point2D TypedDict can have any of the keys omitted. A type
    checker is only expected to support a literal False or True as the value of
    the total argument. True is the default, and makes all items defined in the
    class body be required.
    The Required and NotRequired special forms can also be used to mark
    individual keys as being required or not required::
        class Point2D(TypedDict):
            x: int               # the "x" key must always be present (Required is the default)
            y: NotRequired[int]  # the "y" key can be omitted
    See PEP 655 for more details on Required and NotRequired.
    """
    if fields is None:
        fields = kwargs
    elif kwargs:
        raise TypeError("TypedDict takes either a dict or keyword arguments,"
                        " but not both")
    if kwargs:
        warnings.warn(
            "The kwargs-based syntax for TypedDict definitions is deprecated "
            "in Python 3.11, will be removed in Python 3.13, and may not be "
            "understood by third-party type checkers.",
            DeprecationWarning,
            stacklevel=2,
        )
    ns = {'__annotations__': dict(fields)}
    module = _caller()
    if module is not None:
        # Setting correct module is necessary to make typed dict classes pickleable.
        ns['__module__'] = module
    return _TypedDictMeta(typename, (), ns, total=total)
_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})


_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
@_SpecialForm
def Required(self, parameters):
    """Special typing construct to mark a TypedDict key as required.
    This is mainly useful for total=False TypedDicts.
    For example::
        class Movie(TypedDict, total=False):
            title: Required[str]
            year: int
        m = Movie(
            title='The Matrix',  # typechecker error if key is omitted
            year=1999,
        )
    There is no runtime checking that a required key is actually provided
    when instantiating a related TypedDict.
    """
    item = _type_check(parameters, f'{self._name} accepts only a single type.')
    return _GenericAlias(self, (item,))
@_SpecialForm
def NotRequired(self, parameters):
    """Special typing construct to mark a TypedDict key as potentially missing.
    For example::
        class Movie(TypedDict):
            title: str
            year: NotRequired[int]
        m = Movie(
            title='The Matrix',  # typechecker error if key is omitted
            year=1999,
        )
    """
    item = _type_check(parameters, f'{self._name} accepts only a single type.')
    return _GenericAlias(self, (item,))
class NewType:
    """NewType creates simple unique types with almost zero runtime overhead.
    NewType(name, tp) is considered a subtype of tp
    by static type checkers. At runtime, NewType(name, tp) returns
    a dummy callable that simply returns its argument.
    Usage::
        UserId = NewType('UserId', int)


Usage::
        UserId = NewType('UserId', int)
        def name_by_id(user_id: UserId) -> str:
            ...
        UserId('user')          # Fails type check
        name_by_id(42)          # Fails type check
        name_by_id(UserId(42))  # OK
        num = UserId(5) + 1     # type: int
    """
    __call__ = _idfunc
    def __init__(self, name, tp):
        self.__qualname__ = name
        if '.' in name:
            name = name.rpartition('.')[-1]
        self.__name__ = name
        self.__supertype__ = tp
        def_mod = _caller()
        if def_mod != 'typing':
            self.__module__ = def_mod
    def __mro_entries__(self, bases):
        # We defined __mro_entries__ to get a better error message
        # if a user attempts to subclass a NewType instance. bpo-46170
        superclass_name = self.__name__
        class Dummy:
            def __init_subclass__(cls):
                subclass_name = cls.__name__
                raise TypeError(
                    f"Cannot subclass an instance of NewType. Perhaps you were looking for: "
                    f"`{subclass_name} = NewType({subclass_name!r}, {superclass_name})`"
                )
        return (Dummy,)
    def __repr__(self):
        return f'{self.__module__}.{self.__qualname__}'
    def __reduce__(self):
        return self.__qualname__
    def __or__(self, other):
        return Union[self, other]
    def __ror__(self, other):
        return Union[other, self]


def __ror__(self, other):
        return Union[other, self]
# Python-version-specific alias (Python 2: unicode; Python 3: str)
Text = str
# Constant that's True when type checking, but False here.
TYPE_CHECKING = False
class IO(Generic[AnyStr]):
    """Generic base class for TextIO and BinaryIO.
    This is an abstract, generic version of the return of open().
    NOTE: This does not distinguish between the different possible
    classes (text vs. binary, read vs. write vs. read/write,
    append-only, unbuffered).  The TextIO and BinaryIO subclasses
    below capture the distinctions between text vs. binary, which is
    pervasive in the interface; however we currently do not offer a
    way to track the other distinctions in the type system.
    """
    __slots__ = ()
    @property
    @abstractmethod
    def mode(self) -> str:
        pass
    @property
    @abstractmethod
    def name(self) -> str:
        pass
    @abstractmethod
    def close(self) -> None:
        pass
    @property
    @abstractmethod
    def closed(self) -> bool:
        pass
    @abstractmethod
    def fileno(self) -> int:
        pass
    @abstractmethod
    def flush(self) -> None:
        pass
    @abstractmethod
    def isatty(self) -> bool:
        pass
    @abstractmethod
    def read(self, n: int = -1) -> AnyStr:
        pass
    @abstractmethod
    def readable(self) -> bool:
        pass
    @abstractmethod
    def readline(self, limit: int = -1) -> AnyStr:
        pass
    @abstractmethod


pass
    @abstractmethod
    def readlines(self, hint: int = -1) -> List[AnyStr]:
        pass
    @abstractmethod
    def seek(self, offset: int, whence: int = 0) -> int:
        pass
    @abstractmethod
    def seekable(self) -> bool:
        pass
    @abstractmethod
    def tell(self) -> int:
        pass
    @abstractmethod
    def truncate(self, size: int = None) -> int:
        pass
    @abstractmethod
    def writable(self) -> bool:
        pass
    @abstractmethod
    def write(self, s: AnyStr) -> int:
        pass
    @abstractmethod
    def writelines(self, lines: List[AnyStr]) -> None:
        pass
    @abstractmethod
    def __enter__(self) -> 'IO[AnyStr]':
        pass
    @abstractmethod
    def __exit__(self, type, value, traceback) -> None:
        pass
class BinaryIO(IO[bytes]):
    """Typed version of the return of open() in binary mode."""
    __slots__ = ()
    @abstractmethod
    def write(self, s: Union[bytes, bytearray]) -> int:
        pass
    @abstractmethod
    def __enter__(self) -> 'BinaryIO':
        pass
class TextIO(IO[str]):
    """Typed version of the return of open() in text mode."""
    __slots__ = ()
    @property
    @abstractmethod
    def buffer(self) -> BinaryIO:
        pass
    @property
    @abstractmethod
    def encoding(self) -> str:
        pass
    @property
    @abstractmethod
    def errors(self) -> Optional[str]:
        pass
    @property
    @abstractmethod


pass
    @property
    @abstractmethod
    def line_buffering(self) -> bool:
        pass
    @property
    @abstractmethod
    def newlines(self) -> Any:
        pass
    @abstractmethod
    def __enter__(self) -> 'TextIO':
        pass
class _DeprecatedType(type):
    def __getattribute__(cls, name):
        if name not in ("__dict__", "__module__") and name in cls.__dict__:
            warnings.warn(
                f"{cls.__name__} is deprecated, import directly "
                f"from typing instead. {cls.__name__} will be removed "
                "in Python 3.12.",
                DeprecationWarning,
                stacklevel=2,
            )
        return super().__getattribute__(name)
class io(metaclass=_DeprecatedType):
    """Wrapper namespace for IO generic classes."""
    __all__ = ['IO', 'TextIO', 'BinaryIO']
    IO = IO
    TextIO = TextIO
    BinaryIO = BinaryIO
io.__name__ = __name__ + '.io'
sys.modules[io.__name__] = io
Pattern = _alias(stdlib_re.Pattern, 1)
Match = _alias(stdlib_re.Match, 1)
class re(metaclass=_DeprecatedType):
    """Wrapper namespace for re type aliases."""
    __all__ = ['Pattern', 'Match']
    Pattern = Pattern
    Match = Match
re.__name__ = __name__ + '.re'
sys.modules[re.__name__] = re
def reveal_type(obj: T, /) -> T:
    """Reveal the inferred type of a variable.
    When a static type checker encounters a call to ``reveal_type()``,


When a static type checker encounters a call to ``reveal_type()``,
    it will emit the inferred type of the argument::
        x: int = 1
        reveal_type(x)
    Running a static type checker (e.g., mypy) on this example
    will produce output similar to 'Revealed type is "builtins.int"'.
    At runtime, the function prints the runtime type of the
    argument and returns it unchanged.
    """
    print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
    return obj
def dataclass_transform(
    *,
    eq_default: bool = True,
    order_default: bool = False,
    kw_only_default: bool = False,
    field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (),
    **kwargs: Any,
) -> Callable[[T], T]:
    """Decorator to mark an object as providing dataclass-like behaviour.
    The decorator can be applied to a function, class, or metaclass.
    Example usage with a decorator function::
        T = TypeVar("T")
        @dataclass_transform()
        def create_model(cls: type[T]) -> type[T]:
            ...
            return cls
        @create_model
        class CustomerModel:
            id: int
            name: str
    On a base class::
        @dataclass_transform()
        class ModelBase: ...
        class CustomerModel(ModelBase):
            id: int
            name: str
    On a metaclass::
        @dataclass_transform()
        class ModelMeta(type): ...
        class ModelBase(metaclass=ModelMeta): ...
        class CustomerModel(ModelBase):
            id: int
            name: str


class CustomerModel(ModelBase):
            id: int
            name: str
    The ``CustomerModel`` classes defined above will
    be treated by type checkers similarly to classes created with
    ``@dataclasses.dataclass``.
    For example, type checkers will assume these classes have
    ``__init__`` methods that accept ``id`` and ``name``.
    The arguments to this decorator can be used to customize this behavior:
    - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
        ``True`` or ``False`` if it is omitted by the caller.
    - ``order_default`` indicates whether the ``order`` parameter is
        assumed to be True or False if it is omitted by the caller.
    - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
        assumed to be True or False if it is omitted by the caller.
    - ``field_specifiers`` specifies a static list of supported classes
        or functions that describe fields, similar to ``dataclasses.field()``.
    - Arbitrary other keyword arguments are accepted in order to allow for
        possible future extensions.
    At runtime, this decorator records its arguments in the
    ``__dataclass_transform__`` attribute on the decorated object.
    It has no other runtime effect.
    See PEP 681 for more details.
    """
    def decorator(cls_or_fn):
        cls_or_fn.__dataclass_transform__ = {
            "eq_default": eq_default,
            "order_default": order_default,
            "kw_only_default": kw_only_default,
            "field_specifiers": field_specifiers,
            "kwargs": kwargs,
        }
        return cls_or_fn
    return decorator


All modules for which code is available
_markupbase
ast
html.parser
langchain.agents.agent
langchain.agents.agent_iterator
langchain.agents.agent_toolkits.conversational_retrieval.openai_functions
langchain.agents.agent_toolkits.vectorstore.base
langchain.agents.agent_toolkits.vectorstore.toolkit
langchain.agents.agent_types
langchain.agents.chat.base
langchain.agents.chat.output_parser
langchain.agents.conversational.base
langchain.agents.conversational.output_parser
langchain.agents.conversational_chat.base
langchain.agents.conversational_chat.output_parser
langchain.agents.format_scratchpad.log
langchain.agents.format_scratchpad.log_to_messages
langchain.agents.format_scratchpad.openai_functions
langchain.agents.format_scratchpad.openai_tools
langchain.agents.format_scratchpad.xml
langchain.agents.initialize
langchain.agents.load_tools
langchain.agents.loading
langchain.agents.mrkl.base
langchain.agents.mrkl.output_parser
langchain.agents.openai_assistant.base
langchain.agents.openai_functions_agent.agent_token_buffer_memory
langchain.agents.openai_functions_agent.base
langchain.agents.openai_functions_multi_agent.base
langchain.agents.output_parsers.json
langchain.agents.output_parsers.openai_functions
langchain.agents.output_parsers.openai_tools
langchain.agents.output_parsers.react_json_single_input
langchain.agents.output_parsers.react_single_input
langchain.agents.output_parsers.self_ask
langchain.agents.output_parsers.xml
langchain.agents.react.base
langchain.agents.react.output_parser
langchain.agents.schema
langchain.agents.self_ask_with_search.base
langchain.agents.structured_chat.base
langchain.agents.structured_chat.output_parser
langchain.agents.tools


langchain.agents.structured_chat.output_parser
langchain.agents.tools
langchain.agents.utils
langchain.agents.xml.base
langchain.callbacks.file
langchain.callbacks.streaming_aiter
langchain.callbacks.streaming_aiter_final_only
langchain.callbacks.streaming_stdout_final_only
langchain.callbacks.tracers.logging
langchain.chains.api.base
langchain.chains.api.openapi.chain
langchain.chains.api.openapi.requests_chain
langchain.chains.api.openapi.response_chain
langchain.chains.base
langchain.chains.combine_documents.base
langchain.chains.combine_documents.map_reduce
langchain.chains.combine_documents.map_rerank
langchain.chains.combine_documents.reduce
langchain.chains.combine_documents.refine
langchain.chains.combine_documents.stuff
langchain.chains.constitutional_ai.base
langchain.chains.constitutional_ai.models
langchain.chains.conversation.base
langchain.chains.conversational_retrieval.base
langchain.chains.elasticsearch_database.base
langchain.chains.ernie_functions.base
langchain.chains.example_generator
langchain.chains.flare.base
langchain.chains.flare.prompts
langchain.chains.graph_qa.arangodb
langchain.chains.graph_qa.base
langchain.chains.graph_qa.cypher
langchain.chains.graph_qa.cypher_utils
langchain.chains.graph_qa.falkordb
langchain.chains.graph_qa.hugegraph
langchain.chains.graph_qa.kuzu
langchain.chains.graph_qa.nebulagraph
langchain.chains.graph_qa.neptune_cypher
langchain.chains.graph_qa.sparql
langchain.chains.hyde.base
langchain.chains.llm
langchain.chains.llm_checker.base
langchain.chains.llm_math.base
langchain.chains.llm_requests


langchain.chains.llm_math.base
langchain.chains.llm_requests
langchain.chains.llm_summarization_checker.base
langchain.chains.loading
langchain.chains.mapreduce
langchain.chains.moderation
langchain.chains.natbot.base
langchain.chains.natbot.crawler
langchain.chains.openai_functions.base
langchain.chains.openai_functions.citation_fuzzy_match
langchain.chains.openai_functions.extraction
langchain.chains.openai_functions.openapi
langchain.chains.openai_functions.qa_with_structure
langchain.chains.openai_functions.tagging
langchain.chains.openai_functions.utils
langchain.chains.openai_tools.extraction
langchain.chains.prompt_selector
langchain.chains.qa_generation.base
langchain.chains.qa_with_sources.base
langchain.chains.qa_with_sources.loading
langchain.chains.qa_with_sources.retrieval
langchain.chains.qa_with_sources.vector_db
langchain.chains.query_constructor.base
langchain.chains.query_constructor.ir
langchain.chains.query_constructor.parser
langchain.chains.query_constructor.schema
langchain.chains.retrieval_qa.base
langchain.chains.router.base
langchain.chains.router.embedding_router
langchain.chains.router.llm_router
langchain.chains.router.multi_prompt
langchain.chains.router.multi_retrieval_qa
langchain.chains.sequential
langchain.chains.sql_database.query
langchain.chains.transform
langchain.embeddings.cache
langchain.evaluation.agents.trajectory_eval_chain
langchain.evaluation.comparison.eval_chain
langchain.evaluation.criteria.eval_chain
langchain.evaluation.embedding_distance.base
langchain.evaluation.exact_match.base
langchain.evaluation.loading
langchain.evaluation.parsing.base
langchain.evaluation.parsing.json_distance


langchain.evaluation.parsing.base
langchain.evaluation.parsing.json_distance
langchain.evaluation.parsing.json_schema
langchain.evaluation.qa.eval_chain
langchain.evaluation.qa.generate_chain
langchain.evaluation.regex_match.base
langchain.evaluation.schema
langchain.evaluation.scoring.eval_chain
langchain.evaluation.string_distance.base
langchain.hub
langchain.indexes.base
langchain.indexes.graph
langchain.indexes.vectorstore
langchain.memory.buffer
langchain.memory.buffer_window
langchain.memory.chat_memory
langchain.memory.combined
langchain.memory.entity
langchain.memory.kg
langchain.memory.motorhead_memory
langchain.memory.readonly
langchain.memory.simple
langchain.memory.summary
langchain.memory.summary_buffer
langchain.memory.token_buffer
langchain.memory.utils
langchain.memory.vectorstore
langchain.memory.zep_memory
langchain.model_laboratory
langchain.output_parsers.boolean
langchain.output_parsers.combining
langchain.output_parsers.datetime
langchain.output_parsers.enum
langchain.output_parsers.ernie_functions
langchain.output_parsers.fix
langchain.output_parsers.json
langchain.output_parsers.loading
langchain.output_parsers.openai_functions
langchain.output_parsers.openai_tools
langchain.output_parsers.pandas_dataframe
langchain.output_parsers.pydantic
langchain.output_parsers.rail_parser
langchain.output_parsers.regex
langchain.output_parsers.regex_dict
langchain.output_parsers.retry
langchain.output_parsers.structured
langchain.output_parsers.xml
langchain.output_parsers.yaml
langchain.prompts.example_selector.ngram_overlap
langchain.retrievers.contextual_compression
langchain.retrievers.document_compressors.base
langchain.retrievers.document_compressors.chain_extract
langchain.retrievers.document_compressors.chain_filter


langchain.retrievers.document_compressors.chain_filter
langchain.retrievers.document_compressors.cohere_rerank
langchain.retrievers.document_compressors.embeddings_filter
langchain.retrievers.ensemble
langchain.retrievers.merger_retriever
langchain.retrievers.multi_query
langchain.retrievers.multi_vector
langchain.retrievers.parent_document_retriever
langchain.retrievers.re_phraser
langchain.retrievers.self_query.base
langchain.retrievers.self_query.chroma
langchain.retrievers.self_query.dashvector
langchain.retrievers.self_query.deeplake
langchain.retrievers.self_query.elasticsearch
langchain.retrievers.self_query.milvus
langchain.retrievers.self_query.mongodb_atlas
langchain.retrievers.self_query.myscale
langchain.retrievers.self_query.opensearch
langchain.retrievers.self_query.pinecone
langchain.retrievers.self_query.qdrant
langchain.retrievers.self_query.redis
langchain.retrievers.self_query.supabase
langchain.retrievers.self_query.timescalevector
langchain.retrievers.self_query.vectara
langchain.retrievers.self_query.weaviate
langchain.retrievers.time_weighted_retriever
langchain.retrievers.web_research
langchain.runnables.hub
langchain.runnables.openai_functions
langchain.smith.evaluation.config
langchain.smith.evaluation.name_generation
langchain.smith.evaluation.progress
langchain.smith.evaluation.runner_utils
langchain.smith.evaluation.string_run_evaluator
langchain.storage.encoder_backed
langchain.storage.file_system
langchain.storage.in_memory
langchain.text_splitter
langchain.tools.render
langchain.tools.retriever
langchain.utils.ernie_functions
langchain_community.adapters.openai


langchain.utils.ernie_functions
langchain_community.adapters.openai
langchain_community.agent_toolkits.ainetwork.toolkit
langchain_community.agent_toolkits.amadeus.toolkit
langchain_community.agent_toolkits.azure_cognitive_services
langchain_community.agent_toolkits.base
langchain_community.agent_toolkits.clickup.toolkit
langchain_community.agent_toolkits.file_management.toolkit
langchain_community.agent_toolkits.github.toolkit
langchain_community.agent_toolkits.gitlab.toolkit
langchain_community.agent_toolkits.gmail.toolkit
langchain_community.agent_toolkits.jira.toolkit
langchain_community.agent_toolkits.json.base
langchain_community.agent_toolkits.json.toolkit
langchain_community.agent_toolkits.multion.toolkit
langchain_community.agent_toolkits.nasa.toolkit
langchain_community.agent_toolkits.nla.tool
langchain_community.agent_toolkits.nla.toolkit
langchain_community.agent_toolkits.office365.toolkit
langchain_community.agent_toolkits.openapi.base
langchain_community.agent_toolkits.openapi.planner
langchain_community.agent_toolkits.openapi.spec
langchain_community.agent_toolkits.openapi.toolkit
langchain_community.agent_toolkits.playwright.toolkit
langchain_community.agent_toolkits.powerbi.base
langchain_community.agent_toolkits.powerbi.chat_base
langchain_community.agent_toolkits.powerbi.toolkit
langchain_community.agent_toolkits.slack.toolkit
langchain_community.agent_toolkits.spark_sql.base
langchain_community.agent_toolkits.spark_sql.toolkit
langchain_community.agent_toolkits.sql.base
langchain_community.agent_toolkits.sql.toolkit
langchain_community.agent_toolkits.steam.toolkit
langchain_community.agent_toolkits.zapier.toolkit
langchain_community.cache
langchain_community.callbacks.aim_callback
langchain_community.callbacks.argilla_callback
langchain_community.callbacks.arize_callback
langchain_community.callbacks.arthur_callback
langchain_community.callbacks.clearml_callback


langchain_community.callbacks.arthur_callback
langchain_community.callbacks.clearml_callback
langchain_community.callbacks.comet_ml_callback
langchain_community.callbacks.confident_callback
langchain_community.callbacks.context_callback
langchain_community.callbacks.flyte_callback
langchain_community.callbacks.human
langchain_community.callbacks.infino_callback
langchain_community.callbacks.labelstudio_callback
langchain_community.callbacks.llmonitor_callback
langchain_community.callbacks.manager
langchain_community.callbacks.mlflow_callback
langchain_community.callbacks.openai_info
langchain_community.callbacks.promptlayer_callback
langchain_community.callbacks.sagemaker_callback
langchain_community.callbacks.streamlit.mutable_expander
langchain_community.callbacks.streamlit.streamlit_callback_handler
langchain_community.callbacks.tracers.comet
langchain_community.callbacks.tracers.wandb
langchain_community.callbacks.trubrics_callback
langchain_community.callbacks.utils
langchain_community.callbacks.wandb_callback
langchain_community.callbacks.whylabs_callback
langchain_community.chat_loaders.base
langchain_community.chat_loaders.facebook_messenger
langchain_community.chat_loaders.gmail
langchain_community.chat_loaders.imessage
langchain_community.chat_loaders.langsmith
langchain_community.chat_loaders.slack
langchain_community.chat_loaders.telegram
langchain_community.chat_loaders.utils
langchain_community.chat_loaders.whatsapp
langchain_community.chat_message_histories.astradb
langchain_community.chat_message_histories.cassandra
langchain_community.chat_message_histories.cosmos_db
langchain_community.chat_message_histories.dynamodb
langchain_community.chat_message_histories.elasticsearch
langchain_community.chat_message_histories.file
langchain_community.chat_message_histories.firestore
langchain_community.chat_message_histories.in_memory
langchain_community.chat_message_histories.momento
langchain_community.chat_message_histories.mongodb
langchain_community.chat_message_histories.neo4j
langchain_community.chat_message_histories.postgres
langchain_community.chat_message_histories.redis


langchain_community.chat_message_histories.postgres
langchain_community.chat_message_histories.redis
langchain_community.chat_message_histories.rocksetdb
langchain_community.chat_message_histories.singlestoredb
langchain_community.chat_message_histories.sql
langchain_community.chat_message_histories.streamlit
langchain_community.chat_message_histories.upstash_redis
langchain_community.chat_message_histories.xata
langchain_community.chat_message_histories.zep
langchain_community.chat_models.anthropic
langchain_community.chat_models.anyscale
langchain_community.chat_models.azure_openai
langchain_community.chat_models.azureml_endpoint
langchain_community.chat_models.baichuan
langchain_community.chat_models.baidu_qianfan_endpoint
langchain_community.chat_models.bedrock
langchain_community.chat_models.cohere
langchain_community.chat_models.databricks
langchain_community.chat_models.ernie
langchain_community.chat_models.everlyai
langchain_community.chat_models.fake
langchain_community.chat_models.fireworks
langchain_community.chat_models.gigachat
langchain_community.chat_models.google_palm
langchain_community.chat_models.human
langchain_community.chat_models.hunyuan
langchain_community.chat_models.javelin_ai_gateway
langchain_community.chat_models.jinachat
langchain_community.chat_models.konko
langchain_community.chat_models.litellm
langchain_community.chat_models.meta
langchain_community.chat_models.minimax
langchain_community.chat_models.mlflow
langchain_community.chat_models.mlflow_ai_gateway
langchain_community.chat_models.ollama
langchain_community.chat_models.openai
langchain_community.chat_models.pai_eas_endpoint
langchain_community.chat_models.promptlayer_openai
langchain_community.chat_models.tongyi
langchain_community.chat_models.vertexai
langchain_community.chat_models.volcengine_maas
langchain_community.chat_models.yandex
langchain_community.docstore.arbitrary_fn


langchain_community.chat_models.yandex
langchain_community.docstore.arbitrary_fn
langchain_community.docstore.base
langchain_community.docstore.in_memory
langchain_community.docstore.wikipedia
langchain_community.document_loaders.acreom
langchain_community.document_loaders.airbyte
langchain_community.document_loaders.airbyte_json
langchain_community.document_loaders.airtable
langchain_community.document_loaders.apify_dataset
langchain_community.document_loaders.arcgis_loader
langchain_community.document_loaders.arxiv
langchain_community.document_loaders.assemblyai
langchain_community.document_loaders.async_html
langchain_community.document_loaders.azlyrics
langchain_community.document_loaders.azure_ai_data
langchain_community.document_loaders.azure_blob_storage_container
langchain_community.document_loaders.azure_blob_storage_file
langchain_community.document_loaders.baiducloud_bos_directory
langchain_community.document_loaders.baiducloud_bos_file
langchain_community.document_loaders.base
langchain_community.document_loaders.base_o365
langchain_community.document_loaders.bibtex
langchain_community.document_loaders.bigquery
langchain_community.document_loaders.bilibili
langchain_community.document_loaders.blackboard
langchain_community.document_loaders.blob_loaders.file_system
langchain_community.document_loaders.blob_loaders.schema
langchain_community.document_loaders.blob_loaders.youtube_audio
langchain_community.document_loaders.blockchain
langchain_community.document_loaders.brave_search
langchain_community.document_loaders.browserless
langchain_community.document_loaders.chatgpt
langchain_community.document_loaders.chromium
langchain_community.document_loaders.college_confidential
langchain_community.document_loaders.concurrent
langchain_community.document_loaders.confluence
langchain_community.document_loaders.conllu
langchain_community.document_loaders.couchbase
langchain_community.document_loaders.csv_loader
langchain_community.document_loaders.cube_semantic


langchain_community.document_loaders.csv_loader
langchain_community.document_loaders.cube_semantic
langchain_community.document_loaders.datadog_logs
langchain_community.document_loaders.dataframe
langchain_community.document_loaders.diffbot
langchain_community.document_loaders.directory
langchain_community.document_loaders.discord
langchain_community.document_loaders.docugami
langchain_community.document_loaders.docusaurus
langchain_community.document_loaders.dropbox
langchain_community.document_loaders.duckdb_loader
langchain_community.document_loaders.email
langchain_community.document_loaders.epub
langchain_community.document_loaders.etherscan
langchain_community.document_loaders.evernote
langchain_community.document_loaders.excel
langchain_community.document_loaders.facebook_chat
langchain_community.document_loaders.fauna
langchain_community.document_loaders.figma
langchain_community.document_loaders.gcs_directory
langchain_community.document_loaders.gcs_file
langchain_community.document_loaders.generic
langchain_community.document_loaders.geodataframe
langchain_community.document_loaders.git
langchain_community.document_loaders.gitbook
langchain_community.document_loaders.github
langchain_community.document_loaders.google_speech_to_text
langchain_community.document_loaders.googledrive
langchain_community.document_loaders.gutenberg
langchain_community.document_loaders.helpers
langchain_community.document_loaders.hn
langchain_community.document_loaders.html
langchain_community.document_loaders.html_bs
langchain_community.document_loaders.hugging_face_dataset
langchain_community.document_loaders.ifixit
langchain_community.document_loaders.image
langchain_community.document_loaders.image_captions
langchain_community.document_loaders.imsdb
langchain_community.document_loaders.iugu
langchain_community.document_loaders.joplin
langchain_community.document_loaders.json_loader
langchain_community.document_loaders.lakefs


langchain_community.document_loaders.json_loader
langchain_community.document_loaders.lakefs
langchain_community.document_loaders.larksuite
langchain_community.document_loaders.markdown
langchain_community.document_loaders.mastodon
langchain_community.document_loaders.max_compute
langchain_community.document_loaders.mediawikidump
langchain_community.document_loaders.merge
langchain_community.document_loaders.mhtml
langchain_community.document_loaders.modern_treasury
langchain_community.document_loaders.mongodb
langchain_community.document_loaders.news
langchain_community.document_loaders.notebook
langchain_community.document_loaders.notion
langchain_community.document_loaders.notiondb
langchain_community.document_loaders.nuclia
langchain_community.document_loaders.obs_directory
langchain_community.document_loaders.obs_file
langchain_community.document_loaders.obsidian
langchain_community.document_loaders.odt
langchain_community.document_loaders.onedrive
langchain_community.document_loaders.onedrive_file
langchain_community.document_loaders.onenote
langchain_community.document_loaders.open_city_data
langchain_community.document_loaders.org_mode
langchain_community.document_loaders.parsers.audio
langchain_community.document_loaders.parsers.docai
langchain_community.document_loaders.parsers.generic
langchain_community.document_loaders.parsers.grobid
langchain_community.document_loaders.parsers.html.bs4
langchain_community.document_loaders.parsers.language.cobol
langchain_community.document_loaders.parsers.language.code_segmenter
langchain_community.document_loaders.parsers.language.javascript
langchain_community.document_loaders.parsers.language.language_parser
langchain_community.document_loaders.parsers.language.python
langchain_community.document_loaders.parsers.msword
langchain_community.document_loaders.parsers.pdf
langchain_community.document_loaders.parsers.registry
langchain_community.document_loaders.parsers.txt
langchain_community.document_loaders.pdf


langchain_community.document_loaders.parsers.txt
langchain_community.document_loaders.pdf
langchain_community.document_loaders.polars_dataframe
langchain_community.document_loaders.powerpoint
langchain_community.document_loaders.psychic
langchain_community.document_loaders.pubmed
langchain_community.document_loaders.pyspark_dataframe
langchain_community.document_loaders.python
langchain_community.document_loaders.quip
langchain_community.document_loaders.readthedocs
langchain_community.document_loaders.recursive_url_loader
langchain_community.document_loaders.reddit
langchain_community.document_loaders.roam
langchain_community.document_loaders.rocksetdb
langchain_community.document_loaders.rspace
langchain_community.document_loaders.rss
langchain_community.document_loaders.rst
langchain_community.document_loaders.rtf
langchain_community.document_loaders.s3_directory
langchain_community.document_loaders.s3_file
langchain_community.document_loaders.sharepoint
langchain_community.document_loaders.sitemap
langchain_community.document_loaders.slack_directory
langchain_community.document_loaders.snowflake_loader
langchain_community.document_loaders.spreedly
langchain_community.document_loaders.srt
langchain_community.document_loaders.stripe
langchain_community.document_loaders.telegram
langchain_community.document_loaders.tencent_cos_directory
langchain_community.document_loaders.tencent_cos_file
langchain_community.document_loaders.tensorflow_datasets
langchain_community.document_loaders.text
langchain_community.document_loaders.tomarkdown
langchain_community.document_loaders.toml
langchain_community.document_loaders.trello
langchain_community.document_loaders.tsv
langchain_community.document_loaders.twitter
langchain_community.document_loaders.unstructured
langchain_community.document_loaders.url
langchain_community.document_loaders.url_playwright
langchain_community.document_loaders.url_selenium
langchain_community.document_loaders.weather
langchain_community.document_loaders.web_base


langchain_community.document_loaders.weather
langchain_community.document_loaders.web_base
langchain_community.document_loaders.whatsapp_chat
langchain_community.document_loaders.wikipedia
langchain_community.document_loaders.word_document
langchain_community.document_loaders.xml
langchain_community.document_loaders.xorbits
langchain_community.document_loaders.youtube
langchain_community.document_transformers.beautiful_soup_transformer
langchain_community.document_transformers.doctran_text_extract
langchain_community.document_transformers.doctran_text_qa
langchain_community.document_transformers.doctran_text_translate
langchain_community.document_transformers.embeddings_redundant_filter
langchain_community.document_transformers.google_translate
langchain_community.document_transformers.html2text
langchain_community.document_transformers.long_context_reorder
langchain_community.document_transformers.nuclia_text_transform
langchain_community.document_transformers.openai_functions
langchain_community.embeddings.aleph_alpha
langchain_community.embeddings.awa
langchain_community.embeddings.azure_openai
langchain_community.embeddings.baidu_qianfan_endpoint
langchain_community.embeddings.bedrock
langchain_community.embeddings.bookend
langchain_community.embeddings.clarifai
langchain_community.embeddings.cloudflare_workersai
langchain_community.embeddings.cohere
langchain_community.embeddings.dashscope
langchain_community.embeddings.databricks
langchain_community.embeddings.deepinfra
langchain_community.embeddings.edenai
langchain_community.embeddings.elasticsearch
langchain_community.embeddings.embaas
langchain_community.embeddings.ernie
langchain_community.embeddings.fake
langchain_community.embeddings.fastembed
langchain_community.embeddings.google_palm
langchain_community.embeddings.gpt4all
langchain_community.embeddings.gradient_ai
langchain_community.embeddings.huggingface
langchain_community.embeddings.huggingface_hub
langchain_community.embeddings.infinity


langchain_community.embeddings.huggingface_hub
langchain_community.embeddings.infinity
langchain_community.embeddings.javelin_ai_gateway
langchain_community.embeddings.jina
langchain_community.embeddings.johnsnowlabs
langchain_community.embeddings.llamacpp
langchain_community.embeddings.llm_rails
langchain_community.embeddings.localai
langchain_community.embeddings.minimax
langchain_community.embeddings.mlflow
langchain_community.embeddings.mlflow_gateway
langchain_community.embeddings.modelscope_hub
langchain_community.embeddings.mosaicml
langchain_community.embeddings.nlpcloud
langchain_community.embeddings.octoai_embeddings
langchain_community.embeddings.ollama
langchain_community.embeddings.openai
langchain_community.embeddings.sagemaker_endpoint
langchain_community.embeddings.self_hosted
langchain_community.embeddings.self_hosted_hugging_face
langchain_community.embeddings.spacy_embeddings
langchain_community.embeddings.tensorflow_hub
langchain_community.embeddings.vertexai
langchain_community.embeddings.voyageai
langchain_community.embeddings.xinference
langchain_community.graphs.arangodb_graph
langchain_community.graphs.falkordb_graph
langchain_community.graphs.graph_document
langchain_community.graphs.graph_store
langchain_community.graphs.hugegraph
langchain_community.graphs.kuzu_graph
langchain_community.graphs.memgraph_graph
langchain_community.graphs.nebula_graph
langchain_community.graphs.neo4j_graph
langchain_community.graphs.neptune_graph
langchain_community.graphs.networkx_graph
langchain_community.graphs.rdf_graph
langchain_community.indexes.base
langchain_community.llms.ai21
langchain_community.llms.aleph_alpha
langchain_community.llms.amazon_api_gateway
langchain_community.llms.anthropic
langchain_community.llms.anyscale
langchain_community.llms.arcee


langchain_community.llms.anyscale
langchain_community.llms.arcee
langchain_community.llms.aviary
langchain_community.llms.azureml_endpoint
langchain_community.llms.baidu_qianfan_endpoint
langchain_community.llms.bananadev
langchain_community.llms.baseten
langchain_community.llms.beam
langchain_community.llms.bedrock
langchain_community.llms.bittensor
langchain_community.llms.cerebriumai
langchain_community.llms.chatglm
langchain_community.llms.clarifai
langchain_community.llms.cloudflare_workersai
langchain_community.llms.cohere
langchain_community.llms.ctransformers
langchain_community.llms.ctranslate2
langchain_community.llms.databricks
langchain_community.llms.deepinfra
langchain_community.llms.deepsparse
langchain_community.llms.edenai
langchain_community.llms.fake
langchain_community.llms.fireworks
langchain_community.llms.forefrontai
langchain_community.llms.gigachat
langchain_community.llms.google_palm
langchain_community.llms.gooseai
langchain_community.llms.gpt4all
langchain_community.llms.gradient_ai
langchain_community.llms.huggingface_endpoint
langchain_community.llms.huggingface_hub
langchain_community.llms.huggingface_pipeline
langchain_community.llms.huggingface_text_gen_inference
langchain_community.llms.human
langchain_community.llms.javelin_ai_gateway
langchain_community.llms.koboldai
langchain_community.llms.llamacpp
langchain_community.llms.loading
langchain_community.llms.manifest
langchain_community.llms.minimax
langchain_community.llms.mlflow
langchain_community.llms.mlflow_ai_gateway
langchain_community.llms.modal
langchain_community.llms.mosaicml


langchain_community.llms.modal
langchain_community.llms.mosaicml
langchain_community.llms.nlpcloud
langchain_community.llms.octoai_endpoint
langchain_community.llms.ollama
langchain_community.llms.opaqueprompts
langchain_community.llms.openai
langchain_community.llms.openllm
langchain_community.llms.openlm
langchain_community.llms.pai_eas_endpoint
langchain_community.llms.petals
langchain_community.llms.pipelineai
langchain_community.llms.predibase
langchain_community.llms.predictionguard
langchain_community.llms.promptlayer_openai
langchain_community.llms.replicate
langchain_community.llms.rwkv
langchain_community.llms.sagemaker_endpoint
langchain_community.llms.self_hosted
langchain_community.llms.self_hosted_hugging_face
langchain_community.llms.stochasticai
langchain_community.llms.symblai_nebula
langchain_community.llms.textgen
langchain_community.llms.titan_takeoff
langchain_community.llms.titan_takeoff_pro
langchain_community.llms.together
langchain_community.llms.tongyi
langchain_community.llms.utils
langchain_community.llms.vertexai
langchain_community.llms.vllm
langchain_community.llms.volcengine_maas
langchain_community.llms.watsonxllm
langchain_community.llms.writer
langchain_community.llms.xinference
langchain_community.llms.yandex
langchain_community.retrievers.arcee
langchain_community.retrievers.arxiv
langchain_community.retrievers.azure_cognitive_search
langchain_community.retrievers.bedrock
langchain_community.retrievers.bm25
langchain_community.retrievers.chaindesk
langchain_community.retrievers.chatgpt_plugin_retriever


langchain_community.retrievers.chatgpt_plugin_retriever
langchain_community.retrievers.cohere_rag_retriever
langchain_community.retrievers.databerry
langchain_community.retrievers.docarray
langchain_community.retrievers.elastic_search_bm25
langchain_community.retrievers.embedchain
langchain_community.retrievers.google_cloud_documentai_warehouse
langchain_community.retrievers.google_vertex_ai_search
langchain_community.retrievers.kay
langchain_community.retrievers.kendra
langchain_community.retrievers.knn
langchain_community.retrievers.llama_index
langchain_community.retrievers.metal
langchain_community.retrievers.milvus
langchain_community.retrievers.outline
langchain_community.retrievers.pinecone_hybrid_search
langchain_community.retrievers.pubmed
langchain_community.retrievers.remote_retriever
langchain_community.retrievers.svm
langchain_community.retrievers.tavily_search_api
langchain_community.retrievers.tfidf
langchain_community.retrievers.vespa_retriever
langchain_community.retrievers.weaviate_hybrid_search
langchain_community.retrievers.wikipedia
langchain_community.retrievers.you
langchain_community.retrievers.zep
langchain_community.retrievers.zilliz
langchain_community.storage.exceptions
langchain_community.storage.redis
langchain_community.storage.upstash_redis
langchain_community.tools.ainetwork.app
langchain_community.tools.ainetwork.base
langchain_community.tools.ainetwork.owner
langchain_community.tools.ainetwork.rule
langchain_community.tools.ainetwork.transfer
langchain_community.tools.ainetwork.utils
langchain_community.tools.ainetwork.value
langchain_community.tools.amadeus.base
langchain_community.tools.amadeus.closest_airport
langchain_community.tools.amadeus.flight_search


langchain_community.tools.amadeus.flight_search
langchain_community.tools.amadeus.utils
langchain_community.tools.arxiv.tool
langchain_community.tools.azure_cognitive_services.form_recognizer
langchain_community.tools.azure_cognitive_services.image_analysis
langchain_community.tools.azure_cognitive_services.speech2text
langchain_community.tools.azure_cognitive_services.text2speech
langchain_community.tools.azure_cognitive_services.text_analytics_health
langchain_community.tools.azure_cognitive_services.utils
langchain_community.tools.bearly.tool
langchain_community.tools.bing_search.tool
langchain_community.tools.brave_search.tool
langchain_community.tools.clickup.tool
langchain_community.tools.convert_to_openai
langchain_community.tools.dataforseo_api_search.tool
langchain_community.tools.ddg_search.tool
langchain_community.tools.e2b_data_analysis.tool
langchain_community.tools.e2b_data_analysis.unparse
langchain_community.tools.edenai.audio_speech_to_text
langchain_community.tools.edenai.audio_text_to_speech
langchain_community.tools.edenai.edenai_base_tool
langchain_community.tools.edenai.image_explicitcontent
langchain_community.tools.edenai.image_objectdetection
langchain_community.tools.edenai.ocr_identityparser
langchain_community.tools.edenai.ocr_invoiceparser
langchain_community.tools.edenai.text_moderation
langchain_community.tools.eleven_labs.models
langchain_community.tools.eleven_labs.text2speech
langchain_community.tools.file_management.copy
langchain_community.tools.file_management.delete
langchain_community.tools.file_management.file_search
langchain_community.tools.file_management.list_dir
langchain_community.tools.file_management.move
langchain_community.tools.file_management.read
langchain_community.tools.file_management.utils
langchain_community.tools.file_management.write
langchain_community.tools.github.tool
langchain_community.tools.gitlab.tool
langchain_community.tools.gmail.base


langchain_community.tools.gitlab.tool
langchain_community.tools.gmail.base
langchain_community.tools.gmail.create_draft
langchain_community.tools.gmail.get_message
langchain_community.tools.gmail.get_thread
langchain_community.tools.gmail.search
langchain_community.tools.gmail.send_message
langchain_community.tools.gmail.utils
langchain_community.tools.golden_query.tool
langchain_community.tools.google_cloud.texttospeech
langchain_community.tools.google_finance.tool
langchain_community.tools.google_jobs.tool
langchain_community.tools.google_lens.tool
langchain_community.tools.google_places.tool
langchain_community.tools.google_scholar.tool
langchain_community.tools.google_search.tool
langchain_community.tools.google_serper.tool
langchain_community.tools.google_trends.tool
langchain_community.tools.graphql.tool
langchain_community.tools.human.tool
langchain_community.tools.ifttt
langchain_community.tools.interaction.tool
langchain_community.tools.jira.tool
langchain_community.tools.json.tool
langchain_community.tools.memorize.tool
langchain_community.tools.merriam_webster.tool
langchain_community.tools.metaphor_search.tool
langchain_community.tools.multion.close_session
langchain_community.tools.multion.create_session
langchain_community.tools.multion.update_session
langchain_community.tools.nasa.tool
langchain_community.tools.nuclia.tool
langchain_community.tools.office365.base
langchain_community.tools.office365.create_draft_message
langchain_community.tools.office365.events_search
langchain_community.tools.office365.messages_search
langchain_community.tools.office365.send_event
langchain_community.tools.office365.send_message
langchain_community.tools.office365.utils
langchain_community.tools.openapi.utils.api_models
langchain_community.tools.openweathermap.tool
langchain_community.tools.playwright.base
langchain_community.tools.playwright.click
langchain_community.tools.playwright.current_page
langchain_community.tools.playwright.extract_hyperlinks
langchain_community.tools.playwright.extract_text


langchain_community.tools.playwright.extract_hyperlinks
langchain_community.tools.playwright.extract_text
langchain_community.tools.playwright.get_elements
langchain_community.tools.playwright.navigate
langchain_community.tools.playwright.navigate_back
langchain_community.tools.playwright.utils
langchain_community.tools.plugin
langchain_community.tools.powerbi.tool
langchain_community.tools.pubmed.tool
langchain_community.tools.reddit_search.tool
langchain_community.tools.render
langchain_community.tools.requests.tool
langchain_community.tools.scenexplain.tool
langchain_community.tools.searchapi.tool
langchain_community.tools.searx_search.tool
langchain_community.tools.shell.tool
langchain_community.tools.slack.base
langchain_community.tools.slack.get_channel
langchain_community.tools.slack.get_message
langchain_community.tools.slack.schedule_message
langchain_community.tools.slack.send_message
langchain_community.tools.slack.utils
langchain_community.tools.sleep.tool
langchain_community.tools.spark_sql.tool
langchain_community.tools.sql_database.tool
langchain_community.tools.stackexchange.tool
langchain_community.tools.steam.tool
langchain_community.tools.steamship_image_generation.tool
langchain_community.tools.steamship_image_generation.utils
langchain_community.tools.tavily_search.tool
langchain_community.tools.vectorstore.tool
langchain_community.tools.wikipedia.tool
langchain_community.tools.wolfram_alpha.tool
langchain_community.tools.yahoo_finance_news
langchain_community.tools.youtube.search
langchain_community.tools.zapier.tool
langchain_community.utilities.alpha_vantage
langchain_community.utilities.anthropic
langchain_community.utilities.apify
langchain_community.utilities.arcee
langchain_community.utilities.arxiv
langchain_community.utilities.awslambda
langchain_community.utilities.bibtex
langchain_community.utilities.bing_search
langchain_community.utilities.brave_search
langchain_community.utilities.clickup
langchain_community.utilities.dalle_image_generator
langchain_community.utilities.dataforseo_api_search


langchain_community.utilities.dalle_image_generator
langchain_community.utilities.dataforseo_api_search
langchain_community.utilities.duckduckgo_search
langchain_community.utilities.github
langchain_community.utilities.gitlab
langchain_community.utilities.golden_query
langchain_community.utilities.google_finance
langchain_community.utilities.google_jobs
langchain_community.utilities.google_lens
langchain_community.utilities.google_places_api
langchain_community.utilities.google_scholar
langchain_community.utilities.google_search
langchain_community.utilities.google_serper
langchain_community.utilities.google_trends
langchain_community.utilities.graphql
langchain_community.utilities.jira
langchain_community.utilities.max_compute
langchain_community.utilities.merriam_webster
langchain_community.utilities.metaphor_search
langchain_community.utilities.nasa
langchain_community.utilities.opaqueprompts
langchain_community.utilities.openapi
langchain_community.utilities.openweathermap
langchain_community.utilities.outline
langchain_community.utilities.portkey
langchain_community.utilities.powerbi
langchain_community.utilities.pubmed
langchain_community.utilities.python
langchain_community.utilities.reddit_search
langchain_community.utilities.redis
langchain_community.utilities.requests
langchain_community.utilities.scenexplain
langchain_community.utilities.searchapi
langchain_community.utilities.searx_search
langchain_community.utilities.serpapi
langchain_community.utilities.spark_sql
langchain_community.utilities.sql_database
langchain_community.utilities.stackexchange
langchain_community.utilities.steam
langchain_community.utilities.tavily_search
langchain_community.utilities.tensorflow_datasets
langchain_community.utilities.twilio
langchain_community.utilities.vertexai
langchain_community.utilities.wikipedia
langchain_community.utilities.wolfram_alpha
langchain_community.utilities.zapier
langchain_community.utils.math
langchain_community.utils.openai
langchain_community.utils.openai_functions
langchain_community.vectorstores.alibabacloud_opensearch
langchain_community.vectorstores.analyticdb
langchain_community.vectorstores.annoy


langchain_community.vectorstores.analyticdb
langchain_community.vectorstores.annoy
langchain_community.vectorstores.astradb
langchain_community.vectorstores.atlas
langchain_community.vectorstores.awadb
langchain_community.vectorstores.azure_cosmos_db
langchain_community.vectorstores.azuresearch
langchain_community.vectorstores.bageldb
langchain_community.vectorstores.baiducloud_vector_search
langchain_community.vectorstores.cassandra
langchain_community.vectorstores.chroma
langchain_community.vectorstores.clarifai
langchain_community.vectorstores.clickhouse
langchain_community.vectorstores.dashvector
langchain_community.vectorstores.databricks_vector_search
langchain_community.vectorstores.deeplake
langchain_community.vectorstores.dingo
langchain_community.vectorstores.docarray.base
langchain_community.vectorstores.docarray.hnsw
langchain_community.vectorstores.docarray.in_memory
langchain_community.vectorstores.elastic_vector_search
langchain_community.vectorstores.elasticsearch
langchain_community.vectorstores.epsilla
langchain_community.vectorstores.faiss
langchain_community.vectorstores.hippo
langchain_community.vectorstores.hologres
langchain_community.vectorstores.lancedb
langchain_community.vectorstores.llm_rails
langchain_community.vectorstores.marqo
langchain_community.vectorstores.matching_engine
langchain_community.vectorstores.meilisearch
langchain_community.vectorstores.milvus
langchain_community.vectorstores.momento_vector_index
langchain_community.vectorstores.mongodb_atlas
langchain_community.vectorstores.myscale
langchain_community.vectorstores.neo4j_vector
langchain_community.vectorstores.nucliadb
langchain_community.vectorstores.opensearch_vector_search
langchain_community.vectorstores.pgembedding
langchain_community.vectorstores.pgvecto_rs
langchain_community.vectorstores.pgvector
langchain_community.vectorstores.pinecone
langchain_community.vectorstores.qdrant


langchain_community.vectorstores.pinecone
langchain_community.vectorstores.qdrant
langchain_community.vectorstores.redis.base
langchain_community.vectorstores.redis.filters
langchain_community.vectorstores.redis.schema
langchain_community.vectorstores.rocksetdb
langchain_community.vectorstores.scann
langchain_community.vectorstores.semadb
langchain_community.vectorstores.singlestoredb
langchain_community.vectorstores.sklearn
langchain_community.vectorstores.sqlitevss
langchain_community.vectorstores.starrocks
langchain_community.vectorstores.supabase
langchain_community.vectorstores.surrealdb
langchain_community.vectorstores.tair
langchain_community.vectorstores.tencentvectordb
langchain_community.vectorstores.tigris
langchain_community.vectorstores.tiledb
langchain_community.vectorstores.timescalevector
langchain_community.vectorstores.typesense
langchain_community.vectorstores.usearch
langchain_community.vectorstores.utils
langchain_community.vectorstores.vald
langchain_community.vectorstores.vearch
langchain_community.vectorstores.vectara
langchain_community.vectorstores.vespa
langchain_community.vectorstores.weaviate
langchain_community.vectorstores.xata
langchain_community.vectorstores.yellowbrick
langchain_community.vectorstores.zep
langchain_community.vectorstores.zilliz
langchain_core.agents
langchain_core.beta.runnables.context
langchain_core.caches
langchain_core.callbacks.base
langchain_core.callbacks.manager
langchain_core.callbacks.stdout
langchain_core.callbacks.streaming_stdout
langchain_core.chat_history
langchain_core.chat_sessions
langchain_core.documents.base
langchain_core.documents.transformers
langchain_core.embeddings
langchain_core.example_selectors.base
langchain_core.example_selectors.length_based
langchain_core.example_selectors.semantic_similarity
langchain_core.exceptions
langchain_core.language_models.base
langchain_core.language_models.chat_models
langchain_core.language_models.llms


langchain_core.language_models.chat_models
langchain_core.language_models.llms
langchain_core.load.dump
langchain_core.load.load
langchain_core.load.serializable
langchain_core.memory
langchain_core.messages.ai
langchain_core.messages.base
langchain_core.messages.chat
langchain_core.messages.function
langchain_core.messages.human
langchain_core.messages.system
langchain_core.messages.tool
langchain_core.output_parsers.base
langchain_core.output_parsers.list
langchain_core.output_parsers.string
langchain_core.output_parsers.transform
langchain_core.outputs.chat_generation
langchain_core.outputs.chat_result
langchain_core.outputs.generation
langchain_core.outputs.llm_result
langchain_core.outputs.run_info
langchain_core.prompt_values
langchain_core.prompts.base
langchain_core.prompts.chat
langchain_core.prompts.few_shot
langchain_core.prompts.few_shot_with_templates
langchain_core.prompts.loading
langchain_core.prompts.pipeline
langchain_core.prompts.prompt
langchain_core.prompts.string
langchain_core.retrievers
langchain_core.runnables.base
langchain_core.runnables.branch
langchain_core.runnables.config
langchain_core.runnables.configurable
langchain_core.runnables.fallbacks
langchain_core.runnables.history
langchain_core.runnables.passthrough
langchain_core.runnables.retry
langchain_core.runnables.router
langchain_core.runnables.utils
langchain_core.stores
langchain_core.tools
langchain_core.tracers.base
langchain_core.tracers.context
langchain_core.tracers.evaluation
langchain_core.tracers.langchain
langchain_core.tracers.langchain_v1
langchain_core.tracers.log_stream
langchain_core.tracers.root_listeners
langchain_core.tracers.run_collector
langchain_core.tracers.schemas


langchain_core.tracers.run_collector
langchain_core.tracers.schemas
langchain_core.tracers.stdout
langchain_core.utils.aiter
langchain_core.utils.env
langchain_core.utils.formatting
langchain_core.utils.html
langchain_core.utils.input
langchain_core.utils.iter
langchain_core.utils.json_schema
langchain_core.utils.loading
langchain_core.utils.pydantic
langchain_core.utils.strings
langchain_core.utils.utils
langchain_core.vectorstores
langchain_experimental.agents.agent_toolkits.csv.base
langchain_experimental.agents.agent_toolkits.pandas.base
langchain_experimental.agents.agent_toolkits.python.base
langchain_experimental.agents.agent_toolkits.spark.base
langchain_experimental.agents.agent_toolkits.xorbits.base
langchain_experimental.autonomous_agents.autogpt.agent
langchain_experimental.autonomous_agents.autogpt.memory
langchain_experimental.autonomous_agents.autogpt.output_parser
langchain_experimental.autonomous_agents.autogpt.prompt
langchain_experimental.autonomous_agents.autogpt.prompt_generator
langchain_experimental.autonomous_agents.baby_agi.baby_agi
langchain_experimental.autonomous_agents.baby_agi.task_creation
langchain_experimental.autonomous_agents.baby_agi.task_execution
langchain_experimental.autonomous_agents.baby_agi.task_prioritization
langchain_experimental.autonomous_agents.hugginggpt.hugginggpt
langchain_experimental.autonomous_agents.hugginggpt.repsonse_generator
langchain_experimental.autonomous_agents.hugginggpt.task_executor
langchain_experimental.autonomous_agents.hugginggpt.task_planner
langchain_experimental.chat_models.llm_wrapper
langchain_experimental.comprehend_moderation.amazon_comprehend_moderation
langchain_experimental.comprehend_moderation.base_moderation


langchain_experimental.comprehend_moderation.base_moderation
langchain_experimental.comprehend_moderation.base_moderation_callbacks
langchain_experimental.comprehend_moderation.base_moderation_config
langchain_experimental.comprehend_moderation.base_moderation_exceptions
langchain_experimental.comprehend_moderation.pii
langchain_experimental.comprehend_moderation.prompt_safety
langchain_experimental.comprehend_moderation.toxicity
langchain_experimental.cpal.base
langchain_experimental.cpal.constants
langchain_experimental.cpal.models
langchain_experimental.data_anonymizer.base
langchain_experimental.data_anonymizer.deanonymizer_mapping
langchain_experimental.data_anonymizer.deanonymizer_matching_strategies
langchain_experimental.data_anonymizer.faker_presidio_mapping
langchain_experimental.data_anonymizer.presidio
langchain_experimental.fallacy_removal.base
langchain_experimental.fallacy_removal.models
langchain_experimental.generative_agents.generative_agent
langchain_experimental.generative_agents.memory
langchain_experimental.graph_transformers.diffbot
langchain_experimental.llm_bash.base
langchain_experimental.llm_bash.bash
langchain_experimental.llm_bash.prompt
langchain_experimental.llm_symbolic_math.base
langchain_experimental.llms.anthropic_functions
langchain_experimental.llms.jsonformer_decoder
langchain_experimental.llms.llamaapi
langchain_experimental.llms.lmformatenforcer_decoder
langchain_experimental.llms.ollama_functions
langchain_experimental.llms.rellm_decoder
langchain_experimental.open_clip.open_clip
langchain_experimental.pal_chain.base
langchain_experimental.plan_and_execute.agent_executor
langchain_experimental.plan_and_execute.executors.agent_executor


langchain_experimental.plan_and_execute.executors.agent_executor
langchain_experimental.plan_and_execute.executors.base
langchain_experimental.plan_and_execute.planners.base
langchain_experimental.plan_and_execute.planners.chat_planner
langchain_experimental.plan_and_execute.schema
langchain_experimental.prompt_injection_identifier.hugging_face_identifier
langchain_experimental.prompts.load
langchain_experimental.retrievers.vector_sql_database
langchain_experimental.rl_chain.base
langchain_experimental.rl_chain.metrics
langchain_experimental.rl_chain.model_repository
langchain_experimental.rl_chain.pick_best_chain
langchain_experimental.rl_chain.vw_logger
langchain_experimental.smart_llm.base
langchain_experimental.sql.base
langchain_experimental.sql.vector_sql
langchain_experimental.tabular_synthetic_data.base
langchain_experimental.tabular_synthetic_data.openai
langchain_experimental.tools.python.tool
langchain_experimental.tot.base
langchain_experimental.tot.checker
langchain_experimental.tot.controller
langchain_experimental.tot.memory
langchain_experimental.tot.prompts
langchain_experimental.tot.thought
langchain_experimental.tot.thought_generation
langchain_experimental.utilities.python
langchain_google_genai.chat_models
langchain_google_genai.embeddings
langchain_google_genai.llms
langchain_nvidia_ai_endpoints._common
langchain_nvidia_ai_endpoints.chat_models
langchain_nvidia_ai_endpoints.embeddings
pydantic.fields
pydantic.main
sqlalchemy.orm.decl_base
sqlalchemy.orm.instrumentation
string
typing


Source code for langchain_nvidia_ai_endpoints._common
from __future__ import annotations
import json
import logging
from typing import (
    Any,
    AsyncIterator,
    Callable,
    Dict,
    Generator,
    Iterator,
    List,
    Optional,
    Sequence,
    Tuple,
    Union,
)
import aiohttp
import requests
from langchain_core.messages import BaseMessage
from langchain_core.pydantic_v1 import (
    BaseModel,
    Field,
    PrivateAttr,
    SecretStr,
    root_validator,
)
from langchain_core.utils import get_from_dict_or_env
from requests.models import Response
logger = logging.getLogger(__name__)
class NVEModel(BaseModel):
    """
    Underlying Client for interacting with the AI Foundation Model Function API.
    Leveraged by the NVIDIABaseModel to provide a simple requests-oriented interface.
    Direct abstraction over NGC-recommended streaming/non-streaming Python solutions.
    NOTE: Models in the playground does not currently support raw text continuation.
    """
    ## Core defaults. These probably should not be changed
    fetch_url_format: str = Field("https://api.nvcf.nvidia.com/v2/nvcf/pexec/status/")
    call_invoke_base: str = Field("https://api.nvcf.nvidia.com/v2/nvcf/pexec/functions")
    get_session_fn: Callable = Field(requests.Session)
    get_asession_fn: Callable = Field(aiohttp.ClientSession)
    nvidia_api_key: SecretStr = Field(
        ...,
        description="API key for NVIDIA Foundation Endpoints. Starts with `nvapi-`",
    )
    is_staging: bool = Field(False, description="Whether to use staging API")
    ## Generation arguments


## Generation arguments
    max_tries: int = Field(5, ge=1)
    headers_tmpl: dict = Field(
        ...,
        description="Headers template for API calls."
        " Should contain `call` and `stream` keys.",
    )
    _available_functions: Optional[List[dict]] = PrivateAttr(default=None)
    _available_models: Optional[dict] = PrivateAttr(default=None)
    @property
    def headers(self) -> dict:
        """Return headers with API key injected"""
        headers_ = self.headers_tmpl.copy()
        for header in headers_.values():
            if "{nvidia_api_key}" in header["Authorization"]:
                header["Authorization"] = header["Authorization"].format(
                    nvidia_api_key=self.nvidia_api_key.get_secret_value(),
                )
        return headers_
    @root_validator(pre=True)
    def validate_model(cls, values: Dict[str, Any]) -> Dict[str, Any]:
        """Validate and update model arguments, including API key and formatting"""
        values["nvidia_api_key"] = get_from_dict_or_env(
            values,
            "nvidia_api_key",
            "NVIDIA_API_KEY",
        )
        if "nvapi-" not in values.get("nvidia_api_key", ""):
            raise ValueError("Invalid NVAPI key detected. Should start with `nvapi-`")
        is_staging = "nvapi-stg-" in values["nvidia_api_key"]
        values["is_staging"] = is_staging
        if "headers_tmpl" not in values:
            values["headers_tmpl"] = {
                "call": {
                    "Authorization": "Bearer {nvidia_api_key}",
                    "Accept": "application/json",
                },
                "stream": {


"Accept": "application/json",
                },
                "stream": {
                    "Authorization": "Bearer {nvidia_api_key}",
                    "Accept": "text/event-stream",
                    "content-type": "application/json",
                },
            }
        values["fetch_url_format"] = cls._stagify(
            is_staging,
            values.get(
                "fetch_url_format", "https://api.nvcf.nvidia.com/v2/nvcf/pexec/status/"
            ),
        )
        values["call_invoke_base"] = cls._stagify(
            is_staging,
            values.get(
                "call_invoke_base",
                "https://api.nvcf.nvidia.com/v2/nvcf/pexec/functions",
            ),
        )
        return values
    @property
    def available_models(self) -> dict:
        """List the available models that can be invoked."""
        if self._available_models is not None:
            return self._available_models
        live_fns = [v for v in self.available_functions if v.get("status") == "ACTIVE"]
        self._available_models = {v["name"]: v["id"] for v in live_fns}
        return self._available_models
    @property
    def available_functions(self) -> List[dict]:
        """List the available functions that can be invoked."""
        if self._available_functions is not None:
            return self._available_functions
        invoke_url = self._stagify(
            self.is_staging, "https://api.nvcf.nvidia.com/v2/nvcf/functions"
        )
        query_res = self.query(invoke_url)
        if "functions" not in query_res:
            raise ValueError(


if "functions" not in query_res:
            raise ValueError(
                f"Unexpected response when querying {invoke_url}\n{query_res}"
            )
        self._available_functions = query_res["functions"]
        return self._available_functions
    @classmethod
    def _stagify(cls, is_staging: bool, path: str) -> str:
        """Helper method to switch between staging and production endpoints"""
        if is_staging and "stg.api" not in path:
            return path.replace("api.", "stg.api.")
        if not is_staging and "stg.api" in path:
            return path.replace("stg.api.", "api.")
        return path
    ####################################################################################
    ## Core utilities for posting and getting from NV Endpoints
    def _post(self, invoke_url: str, payload: dict = {}) -> Tuple[Response, Any]:
        """Method for posting to the AI Foundation Model Function API."""
        call_inputs = {
            "url": invoke_url,
            "headers": self.headers["call"],
            "json": payload,
            "stream": False,
        }
        session = self.get_session_fn()
        response = session.post(**call_inputs)
        self._try_raise(response)
        return response, session
    def _get(self, invoke_url: str, payload: dict = {}) -> Tuple[Response, Any]:
        """Method for getting from the AI Foundation Model Function API."""
        last_inputs = {
            "url": invoke_url,
            "headers": self.headers["call"],
            "json": payload,
            "stream": False,
        }
        session = self.get_session_fn()
        last_response = session.get(**last_inputs)
        self._try_raise(last_response)
        return last_response, session


self._try_raise(last_response)
        return last_response, session
    def _wait(self, response: Response, session: Any) -> Response:
        """Wait for a response from API after an initial response is made."""
        i = 1
        while response.status_code == 202:
            request_id = response.headers.get("NVCF-REQID", "")
            response = session.get(
                self.fetch_url_format + request_id,
                headers=self.headers["call"],
            )
            if response.status_code == 202:
                try:
                    body = response.json()
                except ValueError:
                    body = str(response)
                if i > self.max_tries:
                    raise ValueError(f"Failed to get response with {i} tries: {body}")
        self._try_raise(response)
        return response
    def _try_raise(self, response: Response) -> None:
        """Try to raise an error from a response"""
        try:
            response.raise_for_status()
        except requests.HTTPError as e:
            try:
                rd = response.json()
            except json.JSONDecodeError:
                rd = response.__dict__
                rd = rd.get("_content", rd)
                if isinstance(rd, bytes):
                    rd = rd.decode("utf-8")[5:]  ## remove "data:" prefix
                try:
                    rd = json.loads(rd)
                except Exception:
                    rd = {"detail": rd}
            title = f"[{rd.get('status', '###')}] {rd.get('title', 'Unknown Error')}"
            body = f"{rd.get('detail', rd.get('type', rd))}"
            raise Exception(f"{title}\n{body}") from e
    ####################################################################################


raise Exception(f"{title}\n{body}") from e
    ####################################################################################
    ## Simple query interface to show the set of model options
    def query(self, invoke_url: str, payload: dict = {}) -> dict:
        """Simple method for an end-to-end get query. Returns result dictionary"""
        response, session = self._get(invoke_url, payload)
        response = self._wait(response, session)
        output = self._process_response(response)[0]
        return output
    def _process_response(self, response: Union[str, Response]) -> List[dict]:
        """General-purpose response processing for single responses and streams"""
        if hasattr(response, "json"):  ## For single response (i.e. non-streaming)
            try:
                return [response.json()]
            except json.JSONDecodeError:
                response = str(response.__dict__)
        if isinstance(response, str):  ## For set of responses (i.e. streaming)
            msg_list = []
            for msg in response.split("\n\n"):
                if "{" not in msg:
                    continue
                msg_list += [json.loads(msg[msg.find("{") :])]
            return msg_list
        raise ValueError(f"Received ill-formed response: {response}")
    def _get_invoke_url(
        self, model_name: Optional[str] = None, invoke_url: Optional[str] = None
    ) -> str:
        """Helper method to get invoke URL from a model name, URL, or endpoint stub"""
        if not invoke_url:
            if not model_name:
                raise ValueError("URL or model name must be specified to invoke")
            if model_name in self.available_models:
                invoke_url = self.available_models[model_name]
            elif f"playground_{model_name}" in self.available_models:


elif f"playground_{model_name}" in self.available_models:
                invoke_url = self.available_models[f"playground_{model_name}"]
            else:
                available_models_str = "\n".join(
                    [f"{k} - {v}" for k, v in self.available_models.items()]
                )
                raise ValueError(
                    f"Unknown model name {model_name} specified."
                    "\nAvailable models are:\n"
                    f"{available_models_str}"
                )
        if not invoke_url:
            # For mypy
            raise ValueError("URL or model name must be specified to invoke")
        # Why is this even needed?
        if "http" not in invoke_url:
            invoke_url = f"{self.call_invoke_base}/{invoke_url}"
        return invoke_url
    ####################################################################################
    ## Generation interface to allow users to generate new values from endpoints
    def get_req(
        self,
        model_name: Optional[str] = None,
        payload: dict = {},
        invoke_url: Optional[str] = None,
        stop: Optional[Sequence[str]] = None,
    ) -> Response:
        """Post to the API."""
        invoke_url = self._get_invoke_url(model_name, invoke_url)
        if payload.get("stream", False) is True:
            payload = {**payload, "stream": False}
        response, session = self._post(invoke_url, payload)
        return self._wait(response, session)
    def get_req_generation(
        self,
        model_name: Optional[str] = None,
        payload: dict = {},
        invoke_url: Optional[str] = None,
        stop: Optional[Sequence[str]] = None,
    ) -> dict: