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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
"""Script for auto-generating api_reference.rst."""

import importlib
import inspect
import os
import sys
import typing
from enum import Enum
from pathlib import Path
from typing import Dict, List, Literal, Optional, Sequence, TypedDict, Union

import toml
import typing_extensions
from langchain_core.runnables import Runnable, RunnableSerializable
from pydantic import BaseModel

ROOT_DIR = Path(__file__).parents[2].absolute()
HERE = Path(__file__).parent

ClassKind = Literal[
    "TypedDict",
    "Regular",
    "Pydantic",
    "enum",
    "RunnablePydantic",
    "RunnableNonPydantic",
]


class ClassInfo(TypedDict):
    """Information about a class."""

    name: str
    """The name of the class."""
    qualified_name: str
    """The fully qualified name of the class."""
    kind: ClassKind
    """The kind of the class."""
    is_public: bool
    """Whether the class is public or not."""
    is_deprecated: bool
    """Whether the class is deprecated."""


class FunctionInfo(TypedDict):
    """Information about a function."""

    name: str
    """The name of the function."""
    qualified_name: str
    """The fully qualified name of the function."""
    is_public: bool
    """Whether the function is public or not."""
    is_deprecated: bool
    """Whether the function is deprecated."""


class ModuleMembers(TypedDict):
    """A dictionary of module members."""

    classes_: Sequence[ClassInfo]
    functions: Sequence[FunctionInfo]


def _load_module_members(module_path: str, namespace: str) -> ModuleMembers:
    """Load all members of a module.

    Args:
        module_path: Path to the module.
        namespace: the namespace of the module.

    Returns:
        list: A list of loaded module objects.
    """

    classes_: List[ClassInfo] = []
    functions: List[FunctionInfo] = []
    module = importlib.import_module(module_path)

    if ":private:" in (module.__doc__ or ""):
        return ModuleMembers(classes_=[], functions=[])

    for name, type_ in inspect.getmembers(module):
        if not hasattr(type_, "__module__"):
            continue
        if type_.__module__ != module_path:
            continue
        if ":private:" in (type_.__doc__ or ""):
            continue

        if inspect.isclass(type_):
            # The type of the class is used to select a template
            # for the object when rendering the documentation.
            # See `templates` directory for defined templates.
            # This is a hacky solution to distinguish between different
            # kinds of thing that we want to render.
            if type(type_) is typing_extensions._TypedDictMeta:  # type: ignore
                kind: ClassKind = "TypedDict"
            elif type(type_) is typing._TypedDictMeta:  # type: ignore
                kind: ClassKind = "TypedDict"
            elif (
                issubclass(type_, Runnable)
                and issubclass(type_, BaseModel)
                and type_ is not Runnable
            ):
                # RunnableSerializable subclasses from Pydantic which
                # for which we use autodoc_pydantic for rendering.
                # We need to distinguish these from regular Pydantic
                # classes so we can hide inherited Runnable methods
                # and provide a link to the Runnable interface from
                # the template.
                kind = "RunnablePydantic"
            elif (
                issubclass(type_, Runnable)
                and not issubclass(type_, BaseModel)
                and type_ is not Runnable
            ):
                # These are not pydantic classes but are Runnable.
                # We'll hide all the inherited methods from Runnable
                # but use a regular class template to render.
                kind = "RunnableNonPydantic"
            elif issubclass(type_, Enum):
                kind = "enum"
            elif issubclass(type_, BaseModel):
                kind = "Pydantic"
            else:
                kind = "Regular"

            classes_.append(
                ClassInfo(
                    name=name,
                    qualified_name=f"{namespace}.{name}",
                    kind=kind,
                    is_public=not name.startswith("_"),
                    is_deprecated=".. deprecated::" in (type_.__doc__ or ""),
                )
            )
        elif inspect.isfunction(type_):
            functions.append(
                FunctionInfo(
                    name=name,
                    qualified_name=f"{namespace}.{name}",
                    is_public=not name.startswith("_"),
                    is_deprecated=".. deprecated::" in (type_.__doc__ or ""),
                )
            )
        else:
            continue

    return ModuleMembers(
        classes_=classes_,
        functions=functions,
    )


def _merge_module_members(
    module_members: Sequence[ModuleMembers],
) -> ModuleMembers:
    """Merge module members."""
    classes_: List[ClassInfo] = []
    functions: List[FunctionInfo] = []
    for module in module_members:
        classes_.extend(module["classes_"])
        functions.extend(module["functions"])

    return ModuleMembers(
        classes_=classes_,
        functions=functions,
    )


def _load_package_modules(
    package_directory: Union[str, Path], submodule: Optional[str] = None
) -> Dict[str, ModuleMembers]:
    """Recursively load modules of a package based on the file system.

    Traversal based on the file system makes it easy to determine which
    of the modules/packages are part of the package vs. 3rd party or built-in.

    Parameters:
        package_directory (Union[str, Path]): Path to the package directory.
        submodule (Optional[str]): Optional name of submodule to load.

    Returns:
        Dict[str, ModuleMembers]: A dictionary where keys are module names and values are ModuleMembers objects.
    """
    package_path = (
        Path(package_directory)
        if isinstance(package_directory, str)
        else package_directory
    )
    modules_by_namespace = {}

    # Get the high level package name
    package_name = package_path.name

    # If we are loading a submodule, add it in
    if submodule is not None:
        package_path = package_path / submodule

    for file_path in package_path.rglob("*.py"):
        if file_path.name.startswith("_"):
            continue

        relative_module_name = file_path.relative_to(package_path)

        # Skip if any module part starts with an underscore
        if any(part.startswith("_") for part in relative_module_name.parts):
            continue

        # Get the full namespace of the module
        namespace = str(relative_module_name).replace(".py", "").replace("/", ".")
        # Keep only the top level namespace
        top_namespace = namespace.split(".")[0]

        try:
            # If submodule is present, we need to construct the paths in a slightly
            # different way
            if submodule is not None:
                module_members = _load_module_members(
                    f"{package_name}.{submodule}.{namespace}",
                    f"{submodule}.{namespace}",
                )
            else:
                module_members = _load_module_members(
                    f"{package_name}.{namespace}", namespace
                )
            # Merge module members if the namespace already exists
            if top_namespace in modules_by_namespace:
                existing_module_members = modules_by_namespace[top_namespace]
                _module_members = _merge_module_members(
                    [existing_module_members, module_members]
                )
            else:
                _module_members = module_members

            modules_by_namespace[top_namespace] = _module_members

        except ImportError as e:
            print(f"Error: Unable to import module '{namespace}' with error: {e}")

    return modules_by_namespace


def _construct_doc(
    package_namespace: str,
    members_by_namespace: Dict[str, ModuleMembers],
    package_version: str,
) -> List[typing.Tuple[str, str]]:
    """Construct the contents of the reference.rst file for the given package.

    Args:
        package_namespace: The package top level namespace
        members_by_namespace: The members of the package, dict organized by top level
                              module contains a list of classes and functions
                              inside of the top level namespace.

    Returns:
        The contents of the reference.rst file.
    """
    docs = []
    index_doc = f"""\
:html_theme.sidebar_secondary.remove:

.. currentmodule:: {package_namespace}

.. _{package_namespace}:

======================================
{package_namespace.replace('_', '-')}: {package_version}
======================================

.. automodule:: {package_namespace}
    :no-members:
    :no-inherited-members:

.. toctree::
    :hidden:
    :maxdepth: 2
    
"""
    index_autosummary = """
"""
    namespaces = sorted(members_by_namespace)

    for module in namespaces:
        index_doc += f"    {module}\n"
        module_doc = f"""\
.. currentmodule:: {package_namespace}

.. _{package_namespace}_{module}:
"""
        _members = members_by_namespace[module]
        classes = [
            el
            for el in _members["classes_"]
            if el["is_public"] and not el["is_deprecated"]
        ]
        functions = [
            el
            for el in _members["functions"]
            if el["is_public"] and not el["is_deprecated"]
        ]
        deprecated_classes = [
            el for el in _members["classes_"] if el["is_public"] and el["is_deprecated"]
        ]
        deprecated_functions = [
            el
            for el in _members["functions"]
            if el["is_public"] and el["is_deprecated"]
        ]
        if not (classes or functions):
            continue
        section = f":mod:`{module}`"
        underline = "=" * (len(section) + 1)
        module_doc += f"""
{section}
{underline}

.. automodule:: {package_namespace}.{module}
    :no-members:
    :no-inherited-members:

"""

        index_autosummary += f"""
:ref:`{package_namespace}_{module}`
{'^' * (len(package_namespace) + len(module) + 8)}
"""

        if classes:
            module_doc += f"""\
**Classes**

.. currentmodule:: {package_namespace}

.. autosummary::
    :toctree: {module}
"""
            index_autosummary += """
**Classes**

.. autosummary::
"""

            for class_ in sorted(classes, key=lambda c: c["qualified_name"]):
                if class_["kind"] == "TypedDict":
                    template = "typeddict.rst"
                elif class_["kind"] == "enum":
                    template = "enum.rst"
                elif class_["kind"] == "Pydantic":
                    template = "pydantic.rst"
                elif class_["kind"] == "RunnablePydantic":
                    template = "runnable_pydantic.rst"
                elif class_["kind"] == "RunnableNonPydantic":
                    template = "runnable_non_pydantic.rst"
                else:
                    template = "class.rst"

                module_doc += f"""\
    :template: {template}
    
    {class_["qualified_name"]}
    
"""
                index_autosummary += f"""
    {class_['qualified_name']}
"""

        if functions:
            _functions = [f["qualified_name"] for f in functions]
            fstring = "\n    ".join(sorted(_functions))
            module_doc += f"""\
**Functions**

.. currentmodule:: {package_namespace}

.. autosummary::
    :toctree: {module}
    :template: function.rst

    {fstring}

"""

            index_autosummary += f"""
**Functions**

.. autosummary::

    {fstring}
"""
        if deprecated_classes:
            module_doc += f"""\
**Deprecated classes**

.. currentmodule:: {package_namespace}

.. autosummary::
    :toctree: {module}
"""

            index_autosummary += """
**Deprecated classes**

.. autosummary::
"""

            for class_ in sorted(deprecated_classes, key=lambda c: c["qualified_name"]):
                if class_["kind"] == "TypedDict":
                    template = "typeddict.rst"
                elif class_["kind"] == "enum":
                    template = "enum.rst"
                elif class_["kind"] == "Pydantic":
                    template = "pydantic.rst"
                elif class_["kind"] == "RunnablePydantic":
                    template = "runnable_pydantic.rst"
                elif class_["kind"] == "RunnableNonPydantic":
                    template = "runnable_non_pydantic.rst"
                else:
                    template = "class.rst"

                module_doc += f"""\
    :template: {template}

    {class_["qualified_name"]}

"""
                index_autosummary += f"""
    {class_['qualified_name']}
"""

        if deprecated_functions:
            _functions = [f["qualified_name"] for f in deprecated_functions]
            fstring = "\n    ".join(sorted(_functions))
            module_doc += f"""\
**Deprecated functions**

.. currentmodule:: {package_namespace}

.. autosummary::
    :toctree: {module}
    :template: function.rst

    {fstring}

"""
            index_autosummary += f"""
**Deprecated functions**

.. autosummary::

    {fstring}

"""
        docs.append((f"{module}.rst", module_doc))
    docs.append(("index.rst", index_doc + index_autosummary))
    return docs


def _build_rst_file(package_name: str = "langchain") -> None:
    """Create a rst file for building of documentation.

    Args:
        package_name: Can be either "langchain" or "core" or "experimental".
    """
    package_dir = _package_dir(package_name)
    package_members = _load_package_modules(package_dir)
    package_version = _get_package_version(package_dir)
    output_dir = _out_file_path(package_name)
    os.mkdir(output_dir)
    rsts = _construct_doc(
        _package_namespace(package_name), package_members, package_version
    )
    for name, rst in rsts:
        with open(output_dir / name, "w") as f:
            f.write(rst)


def _package_namespace(package_name: str) -> str:
    """Returns the package name used.

    Args:
        package_name: Can be either "langchain" or "core" or "experimental".

    Returns:
        modified package_name: Can be either "langchain" or "langchain_{package_name}"
    """
    if package_name == "langchain":
        return "langchain"
    if package_name == "standard-tests":
        return "langchain_tests"
    return f"langchain_{package_name.replace('-', '_')}"


def _package_dir(package_name: str = "langchain") -> Path:
    """Return the path to the directory containing the documentation."""
    if package_name in (
        "langchain",
        "experimental",
        "community",
        "core",
        "cli",
        "text-splitters",
        "standard-tests",
    ):
        return ROOT_DIR / "libs" / package_name / _package_namespace(package_name)
    else:
        return (
            ROOT_DIR
            / "libs"
            / "partners"
            / package_name
            / _package_namespace(package_name)
        )


def _get_package_version(package_dir: Path) -> str:
    """Return the version of the package."""
    try:
        with open(package_dir.parent / "pyproject.toml", "r") as f:
            pyproject = toml.load(f)
    except FileNotFoundError as e:
        print(
            f"pyproject.toml not found in {package_dir.parent}.\n"
            "You are either attempting to build a directory which is not a package or "
            "the package is missing a pyproject.toml file which should be added."
            "Aborting the build."
        )
        exit(1)
    try:
        # uses uv
        return pyproject["project"]["version"]
    except KeyError:
        # uses poetry
        return pyproject["tool"]["poetry"]["version"]


def _out_file_path(package_name: str) -> Path:
    """Return the path to the file containing the documentation."""
    return HERE / f"{package_name.replace('-', '_')}"


def _build_index(dirs: List[str]) -> None:
    custom_names = {
        "aws": "AWS",
        "ai21": "AI21",
        "ibm": "IBM",
    }
    ordered = ["core", "langchain", "text-splitters", "community", "experimental"]
    main_ = [dir_ for dir_ in ordered if dir_ in dirs]
    integrations = sorted(dir_ for dir_ in dirs if dir_ not in main_)
    doc = """# LangChain Python API Reference

Welcome to the LangChain Python API reference. This is a reference for all 
`langchain-x` packages. 

For user guides see [https://python.langchain.com](https://python.langchain.com).

For the legacy API reference hosted on ReadTheDocs see [https://api.python.langchain.com/](https://api.python.langchain.com/).
"""

    if main_:
        main_headers = [
            " ".join(custom_names.get(x, x.title()) for x in dir_.split("-"))
            for dir_ in main_
        ]
        main_tree = "\n".join(
            f"{header_name}<{dir_.replace('-', '_')}/index>"
            for header_name, dir_ in zip(main_headers, main_)
        )
        main_grid = "\n".join(
            f'- header: "**{header_name}**"\n  content: "{_package_namespace(dir_).replace("_", "-")}: {_get_package_version(_package_dir(dir_))}"\n  link: {dir_.replace("-", "_")}/index.html'
            for header_name, dir_ in zip(main_headers, main_)
        )
        doc += f"""## Base packages

```{{gallery-grid}}
:grid-columns: "1 2 2 3"

{main_grid}
```

```{{toctree}}
:maxdepth: 2
:hidden:
:caption: Base packages

{main_tree}
```
"""
    if integrations:
        integration_headers = [
            " ".join(
                custom_names.get(x, x.title().replace("ai", "AI").replace("db", "DB"))
                for x in dir_.split("-")
            )
            for dir_ in integrations
        ]
        integration_tree = "\n".join(
            f"{header_name}<{dir_.replace('-', '_')}/index>"
            for header_name, dir_ in zip(integration_headers, integrations)
        )

        integration_grid = ""
        integrations_to_show = [
            "openai",
            "anthropic",
            "google-vertexai",
            "aws",
            "huggingface",
            "mistralai",
        ]
        for header_name, dir_ in sorted(
            zip(integration_headers, integrations),
            key=lambda h_d: (
                integrations_to_show.index(h_d[1])
                if h_d[1] in integrations_to_show
                else len(integrations_to_show)
            ),
        )[: len(integrations_to_show)]:
            integration_grid += f'\n- header: "**{header_name}**"\n  content: {_package_namespace(dir_).replace("_", "-")} {_get_package_version(_package_dir(dir_))}\n  link: {dir_.replace("-", "_")}/index.html'
        doc += f"""## Integrations

```{{gallery-grid}}
:grid-columns: "1 2 2 3"

{integration_grid}
```

See the full list of integrations in the Section Navigation.

```{{toctree}}
:maxdepth: 2
:hidden:
:caption: Integrations

{integration_tree}
```
"""
    with open(HERE / "reference.md", "w") as f:
        f.write(doc)

    dummy_index = """\
# API reference

```{toctree}
:maxdepth: 3
:hidden:

Reference<reference>
```
"""
    with open(HERE / "index.md", "w") as f:
        f.write(dummy_index)


def main(dirs: Optional[list] = None) -> None:
    """Generate the api_reference.rst file for each package."""
    print("Starting to build API reference files.")
    if not dirs:
        dirs = [
            dir_
            for dir_ in os.listdir(ROOT_DIR / "libs")
            if dir_ not in ("cli", "partners", "packages.yml")
        ]
        dirs += [
            dir_
            for dir_ in os.listdir(ROOT_DIR / "libs" / "partners")
            if os.path.isdir(ROOT_DIR / "libs" / "partners" / dir_)
            and "pyproject.toml" in os.listdir(ROOT_DIR / "libs" / "partners" / dir_)
        ]
    for dir_ in dirs:
        # Skip any hidden directories
        # Some of these could be present by mistake in the code base
        # e.g., .pytest_cache from running tests from the wrong location.
        if dir_.startswith("."):
            print("Skipping dir:", dir_)
            continue
        else:
            print("Building package:", dir_)
            _build_rst_file(package_name=dir_)

    _build_index(dirs)
    print("API reference files built.")


if __name__ == "__main__":
    dirs = sys.argv[1:] or None
    main(dirs=dirs)